Systemserver is at the heart of the Android system, and most of the system services that can interact directly in the APK app are executed in this process, common analogy 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 ",//finally 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 a number of parameters to set a new process of information, such as UID, GID, etc., after the function is returned, it is assumed that the child process pid= 0, enter the Handlesystemserverprocess function, for example:
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 performed here */}
The first call to Closeserversocket () in this function is to close the socket service that is copied from the parent process zygote, since it is sufficient to only zygote to listen for the socket request. 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 runs 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 main function of Systemserver.java, 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, finally invokes the System_init () function in System_init.cpp, which 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); }//Basic system services are all completed in the Init2 () function. public static final void Init2 () {slog.i (TAG, "entered the Android system server!"); The function first createsA 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 runs the init1 () function, and the init1 () function is a native function that finally invokes 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; }//execute 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 initiates Serverthread thread to join various services and some other initialization work, Serverthread is an internal class, the gross code such as the following;
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, add the random number of non-SLOG.I (TAG, "Entropy Mixer"); Servicemanager.addservice ("Entropy", New Entropymixer ()),/////with Context.getsystemservice (String name) to obtain the corresponding service// Add power Management Services 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.
Android Boot Systemserver Boot