Online learning courses, course consultation and Q & A and new course information: QQ communication group: 422901085 for course discussion
Transferred from: https://blog.csdn.net/learnframework/article/details/116310690
Course Q & A and new course information: QQ communication group: 422901085 for course discussion
Video link of FrameWork introductory course: https://edu.csdn.net/course/detail/30298
Video link of FrameWork practical lesson 1: https://edu.csdn.net/course/detail/30275
Special blog series:
Android 8.1 zygote startup process source code
Android Framework combat video -- the fork process of Zygote
Android Framework combat video -- SystemServer startup
Android Framework combat video -- SystemServer startup FallbackHome
Android Framework combat video -- FallbackHome process startup and Activity startup
Android Framework combat video -- FallbackHome end launch Launcher
System server startup
As mentioned in the previous lecture, the system server process was fork ed out
Code in main method of ZygoteInit:
Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
After entering the forkSystemServer method, it has been analyzed that:
pid = Zygote.forkSystemServer
That is, the forkSystemServer method is called in Zygote, and the real linux fork () is not called until the native layer
After Zygote.forkSystemServer returns, the code is as follows:
if (pid == 0) { if (hasSecondZygote(abiList)) { waitForSecondaryZygote(socketName); } zygoteServer.closeServerSocket(); return handleSystemServerProcess(parsedArgs); }
Since SystemServer is a process that replicates Zygote, it will also contain Zygote server of Zygote. It has no other effect on SystemServer and needs to be shut down first; By calling handlesysterverprocess:
private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) { //Omit.. final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH"); //Omit.. if (parsedArgs.invokeWith != null) { //Omit.. } else { ClassLoader cl = null; if (systemServerClasspath != null) { //Create PathClassLoader cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion); Thread.currentThread().setContextClassLoader(cl); } /* * Pass the remaining arguments to SystemServer. */ return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl); } /* should never reach here */ }
Here you create a PathClassLoader and then call ZygoteInit.zygoteInit
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) { //ellipsis RuntimeInit.commonInit(); //Start the binder thread pool ZygoteInit.nativeZygoteInit(); return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader); }
Here we call ZygoteInit.nativeZygoteInit() first, which is a native method, implemented in AndroidRuntime, and finally transferred to app_. onZygoteInit of main.cpp to start the binder thread pool:
virtual void onZygoteInit() { sp<ProcessState> proc = ProcessState::self(); ALOGV("App process: starting thread pool.\n"); proc->startThreadPool(); }
Next, call RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
protected static Runnable applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) { //ellipsis return findStaticMain(args.startClass, args.startArgs, classLoader); }
applicationInit is mainly used to find the main method in startClass, and then construct a Runable. The corresponding run method is to call the main method:
private static Runnable findStaticMain(String className, String[] argv, ClassLoader classLoader) { //ellipsis cl = Class.forName(className, true, classLoader); //ellipsis m = cl.getMethod("main", new Class[] { String[].class }); //ellipsis return new MethodAndArgsCaller(m, argv); }
MethodAndArgsCaller:
static class MethodAndArgsCaller implements Runnable { //ellipsis public void run() { //ellipsis mMethod.invoke(null, new Object[] { mArgs }); //ellipsis } }
So here's the key to determining who startClass is
Here we have to go back to the forkSystemServer that started the ZygoteInit class:
There are the following parameters:
String args[] = { "--setuid=1000", "--setgid=1000", "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1032,3001,3002,3003,3006,3007,3009,3010", "--capabilities=" + capabilities + "," + capabilities, "--nice-name=system_server", "--runtime-args", "com.android.server.SystemServer", };
In fact, the statClass here is the last parameter: "com.android.server.SystemServer"
The above process completes the RuntimeInit from Zygote, and finally completes the main method of SystemServer. The following focuses on the main method of SystemServer:
public static void main(String[] args) { new SystemServer().run(); }
Call the run method directly:
private void run() { //Create Looper object Looper.prepareMainLooper(); // Loading system Android_ Libraries for servers System.loadLibrary("android_servers"); //Create system Context createSystemContext() mSystemServiceManager = new SystemServiceManager(mSystemContext); mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart); LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); //Omit.. //Start boot service startBootstrapServices(); //Start core services startCoreServices(); //Start other services startOtherServices(); //Omit.. Looper.loop(); }
There are also many contents in the run method. Here, we can analyze several important parts:
Looper.prepareMainLooper(); The main purpose is to create the Loop object, because the main thread of system server is a Loop managed message Loop like the main thread of ordinary app
createSystemContext() means to create a systemContext. Context is very important not only in ordinary app s, but also in system server. It is necessary to obtain the information environment of some processes through the link of context.
mSystemServiceManager = new SystemServiceManager(mSystemContext); A class object of systemservicemanager is created here and put into LocalServices. In fact, the systemservicemanager here is still different from the ServiceManager in common binders. Systemservicemanager is just an ordinary class in System Server. It is responsible for saving the global variable roles of each SystemService and does not involve cross processes, The ServiceManager can be strongly associated with binders, strides, and divisions
Next is the key point:
//Start boot service
startBootstrapServices();
//Start core services
startCoreServices();
//Start other services
startOtherServices();
system server divides all services of the system into three categories for startup
First: startBootstrapServices();
From the comments in this part, it can be roughly concluded that there are very complex dependencies between system services, so some important system services need to be started first
/** * Starts the small tangle of critical services that are needed to get * the system off the ground. These services have complex mutual dependencies * which is why we initialize them all in one place here. Unless your service * is also entwined in these dependencies, it should be initialized in one of * the other functions. */ private void startBootstrapServices() { //Omit.. Installer installer = mSystemServiceManager.startService(Installer.class); //Omit.. mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class); //Omit.. mActivityManagerService = mSystemServiceManager.startService( ActivityManagerService.Lifecycle.class).getService(); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); //Omit.. mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class); //Omit.. mActivityManagerService.initPowerManagement(); //Omit.. if (!SystemProperties.getBoolean("config.disable_noncore", false)) { traceBeginAndSlog("StartRecoverySystemService"); mSystemServiceManager.startService(RecoverySystemService.class); traceEnd(); } //Omit.. mSystemServiceManager.startService(LightsService.class); //Omit.. mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class); //Omit.. mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY); //Omit.. mPackageManagerService = PackageManagerService.main(mSystemContext, installer, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore); mFirstBoot = mPackageManagerService.isFirstBoot(); mPackageManager = mSystemContext.getPackageManager(); //Omit.. OtaDexoptService.main(mSystemContext, mPackageManagerService); //Omit.. mSystemServiceManager.startService(UserManagerService.LifeCycle.class); //Omit.. mActivityManagerService.setSystemProcess(); //Omit.. mDisplayManagerService.setupSchedulerPolicies(); //Omit.. mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer)); //Omit.. startSensorService(); //Omit.. }, START_SENSOR_SERVICE); }
This code mainly starts some services. These services need to be started first, because it is likely that later services have dependencies on these services.
Here, we only analyze the startup of ActivityManagerService as an example. Other services have the same idea and will not be analyzed separately:
mActivityManagerService = mSystemServiceManager.startService( ActivityManagerService.Lifecycle.class).getService();
Next, analyze the mSystemServiceManager.startService method:
public <T extends SystemService> T startService(Class<T> serviceClass) { //ellipsis Constructor<T> constructor = serviceClass.getConstructor(Context.class); service = constructor.newInstance(mContext); //ellipsis startService(service);//Call your own startService return service; //ellipsis } public void startService(@NonNull final SystemService service) { // Register it. mServices.add(service); //ellipsis service.onStart(); //ellipsis }
Finally, the analyst called the onStart method of serviceClass, which is ActivityManagerService.Lifecycle.class
public static final class Lifecycle extends SystemService { private final ActivityManagerService mService; public Lifecycle(Context context) { super(context); mService = new ActivityManagerService(context); } @Override public void onStart() { mService.start(); } @Override public void onCleanupUser(int userId) { mService.mBatteryStatsService.onCleanupUser(userId); } public ActivityManagerService getService() { return mService; } }
Here you can see that mService = new ActivityManagerService(context) during construction; The ActivityManagerService is constructed, getService() is also the directly returned ActivityManagerService object, and onStart also calls the start method of ActivityManagerService
The other two are the same as the first class. There are only slight differences in the method of constructing the service. We won't analyze them one by one here
//Start core services
startCoreServices();
//Start other services
startOtherServices();
In the last step, startOtherServices not only starts some services, but also calls the systemReady method of each Service after starting each Service:
// It is now time to start up the app processes... vibrator.systemReady(); lockSettings.systemReady(); wm.systemReady(); mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService()); mPackageManagerService.systemReady(); mDisplayManagerService.systemReady(safeMode, mOnlyCore); mActivityManagerService.systemReady(..)
Only the main systemReady methods are listed here