Series index

Android startup process

  1. Source code download and compilation
  2. Overview of the Android system startup process
  3. Init process source parsing
  4. Zygote process source code analysis
  5. SystemServer source code parsing

preface

Android source launcher finally arrived at the last important content -SystemServer (system services), next we will look at SystemServer why so important

The body of the

All services run in a process called system_server. The system_server process is the first process in the Java VIRTUAL machine in Android. It can be said that the business of the entire Android system is around system_server

Antecedents feed

SystemServer is the first process from ZygoteInit, which was mentioned in the previous article. As a review, the ZygoteInit class uses forkSystemServer() to create hard-coded arguments internally. Start SystemServer to enter the SystemServer service logic

ZygoteInit.java

private static Runnable forkSystemServer(String abiList, String socketName, ZygoteServer zygoteServer) { ... /* Hardcoded command line to start the system server */ * Hardcoded command line to start the system server */ / "String args[] = {"--setuid=1000" / / user id "-- setgid = 1000", / / the user group id "- setgroups = 1001100 2100 3100 4100 5100 6100 7100 8100 9101 0101 8102 1102 3," + "1024103 2106 5300 1300 2300 3300 6300 7300 9301 0" and "-" capabilities = "+ +", "+" capabilities "capabilities, // Process name "--nice-name=system_server", // process name "--runtime-args", "-- target - SDK version =" + VMRuntime. SDK_VERSION_CUR_DEVELOPMENT, "com. Android. Server. SystemServer", / / need to start the class}; ZygoteArguments parsedArgs = null; int pid; //processId, processId try {parsedArgs = new ZygoteArguments(args); / / "create ZygoteArguments object, take the args resolved as the parameters of the need to" Zygote. ApplyDebuggerSystemProperty (parsedArgs); Zygote.applyInvokeWithSystemProperty(parsedArgs); boolean profileSystemServer = SystemProperties.getBoolean( "dalvik.vm.profilesystemserver", false); if (profileSystemServer) { parsedArgs.mRuntimeFlags |= Zygote.PROFILE_SYSTEM_SERVER; } /* Request to fork the system server process */ pid = zygote. forkSystemServer() parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids, parsedArgs.mRuntimeFlags, null, parsedArgs.mPermittedCapabilities, parsedArgs.mEffectiveCapabilities); } catch (IllegalArgumentException ex) { throw new RuntimeException(ex); }... }Copy the code

SystemServer’s main processes

Let’s look at the overall groomingAs you can see from the above flow chart, SystemServer’s main processes are relatively simple:

  1. Set system properties and do some preparatory work

  2. Configure the Vm

  3. Create the main thread Looper

  4. Create SystemServiceManager

  5. Create ActivityThread and system Context

  6. Open various services

    StartBootstrapServices (); // Start services with ServiceManger and manage them. // startCoreServices(); // startOtherServices(); // Other servicesCopy the code
  7. Enter the infinite loop of looper. loop

Let’s take a look at what services SystemServer has enabled

You can see that a lot of services are enabled, so there are three function classes that are enabled.

  1. Guide services
  2. Core services
  3. Other services

These services, it is by calling SystemServiceManger. StartServeice (), access to the parameters of Class object, using reflection, access to the Class constructor, create an instance of this Class object, Add the service object to an ArrayList for maintenance, and finally call service.onstart() to complete the task of starting the service

All services are subclasses of SystemService. SystemService is an abstract class. The internal onstart() method is an abstract method

If we want to add a custom system service, how should we do it? I’m not going to go into that

Specific source

“SSM” creates the specified Service object based on Class object reflection

public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {
            final String name = serviceClass.getName();
            Slog.i(TAG, "Starting " + name);
            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

            // Create the service.
            if (!SystemService.class.isAssignableFrom(serviceClass)) {
                throw new RuntimeException("Failed to create " + name
                        + ": service must extend " + SystemService.class.getName());
            }
            final T service;
            try {
                Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);
            } catch (InstantiationException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service could not be instantiated", ex);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (NoSuchMethodException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (InvocationTargetException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service constructor threw an exception", ex);
            }

            startService(service);
            return service;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }
Copy the code

Add to the list of mServices for maintenance and maintain lifecycle events for those services, executing the onStart() function for that service

// Services that should receive lifecycle events.
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();

public void startService(@NonNull final SystemService service) {
        // Register it.
        mServices.add(service);
        // Start it.
        long time = SystemClock.elapsedRealtime();
        try {
            service.onStart();
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
        warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
    }
Copy the code

Systemserver-related major system services

How is ActivityManagerService started

ActivityManagerService is a service started in the startBootstrapServices function. How is it created and started

Here mainly involves three classes, ActivityTaskManagerService, ActivityManagerService, SystemServiceManager

private void startBootstrapServices() { ... // Here is a static inner class object created by "SSM" reflection, And through the "Lifecycle" provide "getService ()" get to "ATM" ActivityTaskManagerService ATM = mSystemServiceManager instance objects. StartService ( ActivityTaskManagerService.Lifecycle.class).getService(); // call the static method "startService" of the static inner class of "ams", Passed on "SSM" and "ATM" mActivityManagerService = ActivityManagerService. Lifecycle. StartService (mSystemServiceManager, ATM); // create ams with "SSM"... }Copy the code

ATM and AMS have a similar design that Lifecycle will be created and acquired by a static internal class that will serve the current system. AMS and Lifecycle will be discussed at a later opportunity

How does Windows ManagerServices start

WMS is enabled by calling startOtherServices in other services. It is not enabled by using the StartService() function of the SSM. WMS objects are first created through the static factory function main() of WMS, and then the addService() function of ServiceManager is used to communicate with the Binder mechanism to register WMS in the service table of the system

Create the WMS object and add it to the ServiceManger

private void startOtherServices() { // WMS needs sensor service ready ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE); mSensorServiceStart = null; wm = WindowManagerService.main(context, inputManager, ! mFirstBoot, mOnlyCore, new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager); ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO); ServiceManager.addService(Context.INPUT_SERVICE, inputManager, /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL); }Copy the code

Add to the ServiceManager by addServcie

public static void addService(String name, IBinder service, boolean allowIsolated, int dumpPriority) { try { getIServiceManager().addService(name, service, allowIsolated, dumpPriority); } catch (RemoteException e) {log. e(TAG, "error in addService", e); }Copy the code

snacks

Through the above source analysis, we know that there are two ways to open the service, let’s go to the specific analysis

SystemServiceManager,

SSM this class, the purpose is to service “. Com. Android. Server SystemService “life cycle events (create, open, and other events)

SystemServiceThe life cycle

As Activty’s lifecycle is the same, SystemService’s lifecycle is also named after onxxx() function

  • onStart()
  • onBootPhase()
  • onStartUser()
  • onUnlockUser()
  • onSwitchUser()
  • onStopUser()
  • OnCleanupUser () life cycle functions are not analyzed here, you can go to see the specific source code, the source code comments are also written very clearly

throughSystemServiceManagermanagementSystemServiceLife cycle of

AMS system service is created and enabled by SystemServiceManager’s startService() function, specifying className system service, let’s look at the specific code

** * Starts a service by class name. ** @return The service instance. */ @suppressWarnings ("unchecked") Public SystemService startService(String className) {// Reflection creates system services final Class<SystemService> serviceClass; try { serviceClass = (Class<SystemService>)Class.forName(className); } catch (ClassNotFoundException ex) { Slog.i(TAG, "Starting " + className); throw new RuntimeException("Failed to create service " + className + ": service class not found, usually indicates that the caller should " + "have called PackageManager.hasSystemFeature() to check whether the " + "feature is available on this device before trying to start the " + "services that implement it", ex); } return startService(serviceClass); // Start the created system service}Copy the code

Start the service and invoke the onStart() lifecycle method of the system service

public void startService(@NonNull final SystemService service) { // Register it. mServices.add(service); // Start it. long time = SystemClock.elapsedRealtime(); try { service.onStart(); // Call the onStart method of the created system service, } catch (RuntimeException ex) {throw new RuntimeException("Failed to start service "+ service.getClass().getName() + ": onStart threw an exception", ex); } warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart"); }Copy the code

Other lifecycle method calls are also made in SystemServiceManager and are not covered here

ServiceManger,

The overall analysis

The main functions in ServiceManger are

  • addService() Adding System Services
  • getServerce() Obtaining System Services
  • checkService() Retrieves the existence of the system service with the specified name from the Service Manager
  • listServices() Returns all running services

Using these functions, you can see that The ServiceManger manages all system services, while the SystemServiceManager manages the creation and life cycle of a single system service

thinking

Why AMS is added through a SystemServiceManager and WMS through a ServiceManger? Keep it in suspense and feel free to comment in the comments

Write in the last

The source code analysis of the launcher has been done intermittently for more than a month. Here we have finished the Android source code analysis of the launcher. We can finish it first, and then we will conduct a detailed source code analysis of AMS,WMS, and Binder related content. Because the level is limited, write wrong also please give advice

Originality is hard, persistence is harder

If you want to continue to see my next share, please let me know by liking, your encouragement is the biggest motivation for me to continue to create!