Android Boot Systemserver Boot

Source: Internet
Author: User
Tags call back strcmp

Systemserver is at the heart of the Android system, and most of the system services that can interact directly in the APK app run in that process, such as Windowmanagerserver (WMS), Activitymanagersystemservice (AmS), Packagemanagerserver (PmS), etc., these systemsThe systemserver process is present in a single thread. Startsystemserver

Systemserver is started by zygote when Fork starts, we first look back to the Zygoteinit.java class to see the start of Systemserver. during the zygote boot process, start the systemserver by calling Startsystemserver:

private static Boolean Startsystemserver () throws Methodandargscaller, RuntimeException {/* hardcoded C             Ommand line to start the system server */String args[] = {"--setuid=1000", "--setgid=1000", "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006,3007", "--c            apabilities=130104352,130104352 ","--runtime-init ","--nice-name=system_server ",//FINAL process name        "Com.android.server.SystemServer",};        Zygoteconnection.arguments Parsedargs = null;        int pid;            try {Parsedargs = new zygoteconnection.arguments (args);            Zygoteconnection.applydebuggersystemproperty (Parsedargs);            Zygoteconnection.applyinvokewithsystemproperty (Parsedargs); /* Request to fork the system server process */pid = Zygote.forksystemserver (Parsedargs.ui D, Parsedargs.gid, PARSEDARGS.GIDS, parsedargs.debugflags, NULL, Parsedargs.permittedcapabilitie        s, parsedargs.effectivecapabilities);        } catch (IllegalArgumentException ex) {throw new RuntimeException (ex);        }/* for child process */if (PID = = 0) {handlesystemserverprocess (Parsedargs);    } return true; }
First through the Zygote.forksystemserver fork out a sub-process, and passed some parameters to set the new process of some information, such as UID, GID, etc., after the function is returned, if it is a child process pid= 0, enter the Handlesystemserverprocess function as follows:
private static void Handlesystemserverprocess (Zygoteconnection.arguments Parsedargs) throws Zygotei Nit.        Methodandargscaller {closeserversocket ();        Set Umask to 0077 so new files and directories would default to owner-only permissions. Libcore.os.umask (S_irwxg |        S_IRWXO);        PS can see the System 261 98 391508 49008 ffffffff 4005c880 S system_server, here system_server is that parsedargs.nicename        if (parsedargs.nicename! = null) {process.setargv0 (parsedargs.nicename);                    } if (Parsedargs.invokewith! = null) {wrapperinit.execapplication (Parsedargs.invokewith,        Parsedargs.nicename, parsedargs.targetsdkversion, NULL, Parsedargs.remainingargs);             } else {/* * Pass the remaining arguments to Systemserver.        */Runtimeinit.zygoteinit (parsedargs.targetsdkversion, Parsedargs.remainingargs); }/* should never reach Here the note should not be run here */} 
First Call Closeserversocket () in this function to close the socket service that was copied from the parent process zygote, as long as the zygote to listen for the socket request is enough. Then proceed, Runtimeinit.zygoteinit () invokes the Onzygoteinit in App_main.cpp through JNI and initiates the thread pool to handle binder events. Finally, an exception Methodandargscaller is thrown through the Invokestaticmain () function.
public static class Methodandargscaller extends Exception implements Runnable {/** method to call */privat        e final Method Mmethod;        /** argument array */private final string[] Margs;            Public Methodandargscaller (method, string[] args) {Mmethod = method;        Margs = args;            public void Run () {try {Mmethod.invoke (null, new object[] {Margs});            } catch (Illegalaccessexception ex) {throw new RuntimeException (ex);                } catch (InvocationTargetException ex) {throwable cause = Ex.getcause ();                if (cause instanceof RuntimeException) {throw (runtimeexception) cause;                } else if (cause instanceof error) {throw (error) cause;            } throw new RuntimeException (ex); }        }    }
This class inherits from exception and implements the runnable. The exception is caught by the main function of the Zygoteinit.java class and executes the run () function, starting the main function of Systemserver by reflection.
The following is the code for the main function of the Zygoteinit.java class to catch exceptions:
} catch (Methodandargscaller caller) {            caller.run ();}

So we started the Systemserver.java main function, the source code in (Base\services\java\com\android\server).

Systemserver.java

Let's take a look at some of the code in this class:

 /** * This method was called from Zygote to initialize the system. This would cause the native * Services (Surfaceflinger, Audioflinger, etc.) to be started.     After that it would call back * up into init2 () to start the Android services.    */Native public static void Init1 (string[] args); public static void Main (string[] args) {//First check system time settings and Samplingprofiler if (System.currenttimemillis () < E Arliest_supported_time) {//If a device ' s clock is before 1970 (before 0), a lot of//APIs crash D Ealing with negative numbers, notably//java.io.file#setlastmodified, so instead we fake it and//            Hope that time from cell towers or NTP fixes it//shortly. SLOG.W (TAG, "System clock is before 1970;            Setting to 1970. ");        Systemclock.setcurrenttimemillis (Earliest_supported_time); } if (samplingprofilerintegration.isenabled ()) {Samplingprofilerintegration.start ();           Timer = new timer (); Timer.schedule (New TimerTask () {@Override public void run () {SAMPLINGPR                Ofilerintegration.writesnapshot ("System_server", null);        }}, Snapshot_interval, Snapshot_interval); }//Mmmmmm ...        More memory!        Dalvik.system.VMRuntime.getRuntime (). Cleargrowthlimit (); The system server has a to run all of the time, so it needs to be/as efficient as possible with its memory USAG        E. vmruntime.getruntime (). Settargetheaputilization (0.8f);        Load Dynamic library libandroid_servers.so system.loadlibrary ("Android_servers"); The Init1 () function is a native function that, through JNI, eventually calls the System_init () function in System_init.cpp, and internally carries out some initialization work related to Dalvik virtual machines.        When the function is finished, it calls the Java-side init2 () function inside, which is why there is no reference to Init2 () in the Java source code.    Init1 (args);    }//The primary system service is done in the Init2 () function.        public static final void Init2 () {slog.i (TAG, "entered the Android system server!"); The function first creates aA Serverthread object that is a thread, and then runs the thread directly from within the Serverthread run () method to actually start the various service threads.        Thread thr = new Serverthread ();        Thr.setname ("Android.server.ServerThread");    Thr.start (); }
The main () function first executes the init1 () function, and the init1 () function is a native function that ultimately calls the System_init () function in System_init.cpp via JNI:

extern "C" status_t system_init () {Alogi ("entered System_init ()");    sp<processstate> proc (processstate::self ());    sp<iservicemanager> sm = Defaultservicemanager ();    Alogi ("ServiceManager:%p\n", Sm.get ());    Sp<grimreaper> grim = new Grimreaper ();    Sm->asbinder ()->linktodeath (Grim, Grim.get (), 0);    Char Propbuf[property_value_max];    Property_get ("System_init.startsurfaceflinger", Propbuf, "1");    if (strcmp (Propbuf, "1") = = 0) {//Start Surfaceflinger surfaceflinger::instantiate ();    } property_get ("System_init.startsensorservice", Propbuf, "1");    if (strcmp (Propbuf, "1") = = 0) {//Start Sensor service sensorservice::instantiate ();  }//And now start the Android runtime. We have to do this bit//of nastiness because the Android runtime initialization requires//some of the core syste    M services to already is started. All other servers should just start the Android runtime at//the beginning of thEIR processes ' s main (), before calling//the INIT function.    Alogi ("System server:starting Android runtime.\n");    androidruntime* runtime = Androidruntime::getruntime ();    Alogi ("System server:starting Android services.\n");    jnienv* env = runtime->getjnienv ();    if (env = = NULL) {return unknown_error; }//through "com/android/server/systemserver" to find Systemserver.java class Jclass clazz = Env->findclass ("Com/android/server/S    Ystemserver ");    if (clazz = = NULL) {return unknown_error;    }//Find the Init2 method of the Systemserver.java class Jmethodid Methodid = Env->getstaticmethodid (Clazz, "Init2", "() V");    if (Methodid = = NULL) {return unknown_error;    }//Run Init2 () function Env->callstaticvoidmethod (Clazz, Methodid);    Alogi ("System server:entering thread pool.\n");    Processstate::self ()->startthreadpool ();    Ipcthreadstate::self ()->jointhreadpool ();    Alogi ("System server:exiting thread pool.\n"); return no_error;}
System_init () function callback Init2 () function, Init2 () function starts Serverthread thread to add various services and some other initialization work, Serverthread is an internal class, the approximate code is as follows;
Class Serverthread extends Thread {... @Override public void Run () {eventlog.writeevent (Eventlogtags.boo        T_progress_system_run, Systemclock.uptimemillis ());        Looper.preparemainlooper ();        ...        String factoryteststr = Systemproperties.get ("Ro.factorytest"); int factorytest = "". Equals (FACTORYTESTSTR)?        SystemServer.FACTORY_TEST_OFF:Integer.parseInt (FACTORYTESTSTR); Final Boolean headless = "1". Equals (Systemproperties.get ("ro.config.headless", "0"));//define variables, initialize services, create various service instances such as: power, network,        Wifi, Bluetooth, USB, etc...       Context context = NULL;        ...//Create a shared handler thread for UI within the system server. This thread was used by at least the following components://-windowmanagerpolicy//-Keyguardviewmanag        ER//-displaymanagerservice handlerthread uihandlerthread = new Handlerthread ("UI");        Uihandlerthread.start (); Handler Uihandler = new Handler (uihAndlerthread.getlooper ()); Uihandler.post (New Runnable () {@Override public void run () {//looper.mylooper (). Set                Messagelogging (New Logprinter (//Log.verbose, "Windowmanagerpolicy", Log.log_id_system));                Android.os.Process.setThreadPriority (Android.os.Process.THREAD_PRIORITY_FOREGROUND);                Android.os.Process.setCanSelfBackground (FALSE);                For debug builds, the log event loop stalls to the Dropbox for analysis. if (strictmode.conditionallyenabledebuglogging ()) {slog.i (TAG, "Enabled strictmode logging for UI loop                Er ");        }            }        });        Create a handler thread just for the Windows Manager to enjoy.        Handlerthread wmhandlerthread = new Handlerthread ("WindowManager");        Wmhandlerthread.start ();        Handler Wmhandler = new Handler (Wmhandlerthread.getlooper ()); Wmhandler.post (New RunNable () {@Override public void run () {//looper.mylooper (). setmessagelogging (New Log                Printer (//Android.util.Log.DEBUG, TAG, Android.util.Log.LOG_ID_SYSTEM));                Android.os.Process.setThreadPriority (Android.os.Process.THREAD_PRIORITY_DISPLAY);                Android.os.Process.setCanSelfBackground (FALSE);                For debug builds, the log event loop stalls to the Dropbox for analysis. if (strictmode.conditionallyenabledebuglogging ()) {slog.i (TAG, "Enabled strictmode logging for WM Loop                Er ");        }            }        });        Critical Services ... boolean onlycore = false; try {//Wait for INSTALLD-finished starting up so that it had a chance to//create critical Dir  Ectories such as/data/user with the appropriate//permissions. We need this to complete before we initialize other services.            SLOG.I (TAG, "Waiting for Installd");            Installer = new Installer ();         Installer.ping ();            The original entropyservice, entropy confusion, increases the unpredictability of the random number slog.i (TAG, "Entropy Mixer"); Servicemanager.addservice ("Entropy", New Entropymixer ()), or//with Context.getsystemservice (String name) to obtain the appropriate service//            Add a power Management service to ServiceManager SLOG.I (TAG, "Power Manager");            Power = new Powermanagerservice ();    Servicemanager.addservice (Context.power_service, POWER);            Start Activitymanagerservice, notice that a context slog.i (TAG, "Activity Manager") is returned;        Context = Activitymanagerservice.main (factorytest);            Use Uihandler, Wmhandler slog.i (TAG, "Display Manager");            display = new Displaymanagerservice (context, Wmhandler, Uihandler);        Servicemanager.addservice (Context.display_service, DISPLAY, true);            ...//using Wmhandler slog.i (TAG, "Input Manager"); InputManager = new InputmanagersErvice (context, Wmhandler);            Using Uihandler, Wmhandler slog.i (TAG, "window Manager");                    WM = Windowmanagerservice.main (context, power, display, InputManager, Uihandler, Wmhandler,            Factorytest! = Systemserver.factory_test_low_level,!firstboot, Onlycore);            Servicemanager.addservice (Context.window_service, WM);            Servicemanager.addservice (Context.input_service, InputManager); Activitymanagerservice.setsystemprocess ();            ...            SLOG.I (TAG, "System Content Providers"); Activitymanagerservice.installsystemproviders (), ....//Initialize the Power service after we have started            The lights service, content providers and the battery service. Power.init (context, lights, activitymanagerservice.self (), Battery, Batterystatsservice.getservice (), D Isplay);            ...            SLOG.I (TAG, "Init Watchdog"); Watchdog.getinstance (). Init (COntext, battery, power, Alarm, activitymanagerservice.self ());            ...                    Activitymanagerservice.self (). Setwindowmanager (WM);..//Use Wmhandler if (Context.getresources (). Getboolean ( com.android.internal.r.bool.config_dreamssupported) {try {slog.i (TAG,                    "Dreams Service"); Dreams (interactive idle-time views, a/k/a screen savers) dreamy = new Dreammanagerservice (context,                    Wmhandler);                Servicemanager.addservice (Dreamservice.dream_service, dreamy);                } catch (Throwable e) {reportwtf ("Starting Dreammanagerservice", e); }}} catch (RuntimeException e) {slog.e ("System", "****************************************            **");        SLOG.E ("System", "************ Failure starting Core service", E); } ... try {slog.i (TAG, "Networkpolicy Service");                Networkpolicy = new Networkpolicymanagerservice (context, activitymanagerservice.se                LF (), power, Networkstats, networkmanagement);            Servicemanager.addservice (Context.network_policy_service, Networkpolicy);            } catch (Throwable e) {reportwtf ("Starting Networkpolicy Service", e);  } ...        }        ... if (safemode) {activitymanagerservice.self (). Showsafemodeoverlay (); } ...//system service initialization is ready to notify each module activitymanagerservice.self (). Systemready (New Runnable () {public void                Run () {slog.i (TAG, "Making services Ready");                if (!headless) Startsystemui (CONTEXTF);                try {if (MOUNTSERVICEF! = null) Mountservicef.systemready ();                } catch (Throwable e) {reportwtf ("Making Mount Service Ready", E);    } ... try {                if (TELEPHONYREGISTRYF! = null) Telephonyregistryf.systemready ();                } catch (Throwable e) {reportwtf ("Making telephonyregistry Ready", E);        }            }        });        For debug builds, the log event loop stalls to the Dropbox for analysis. if (strictmode.conditionallyenabledebuglogging ()) {slog.i (TAG, "Enabled Strictmode for System server main thre AD. ");}        Start processing the message loop Looper.loop ();    SLOG.D (TAG, "System Serverthread is exiting!");        } static final void Startsystemui (context context) {Intent Intent = new Intent ();         Intent.setcomponent (New ComponentName ("Com.android.systemui", "Com.android.systemui.SystemUIService"));        SLOG.D (TAG, "Starting service:" + intent);    Context.startserviceasuser (Intent, Userhandle.owner); }}

Here, the Xxxservicemanager of the system Applicationframework layer is ready.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.