SystemServer 进程启动过程

2023-12-13 04:43:52

首语

SystemServer进程主要用于启动系统服务,诸如AMS、WMS、PMS都是由它来创建的。在系统的名称为"system_server",Android核心服务都是它启动,它是非常重要。

Zygote处理SystemServer进程

Zygote启动过程 文章中分析我们知道,调用Zygote的forkSystemServer方法启动SystemServer进程。

调用nativeZygoteInit方法,它是Native层的代码,用来启动Binder线程池,这样SystemServer进程就可以使用Binder与其它进程进行通信。

调用applicationInit方法,通过反射得到SystemServer类,className为com.android.server.SystemServer,然后找到SystemServer类 的main方法。传入MethodAndArgsCaller类并返回给ZygoteInit类的main方法。调用MethodAndArgsCaller类的run方法,MethodAndArgsCaller类是RuntimeInit类的静态类。最后动态调用SystemServer的main方法。

源码路径:frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

private static Runnable forkSystemServer(String abiList, String socketName,
            ZygoteServer zygoteServer) {
    ...
    if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }

            zygoteServer.closeServerSocket();
            //处理SystemServer进程
            return handleSystemServerProcess(parsedArgs);
        }
}
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
    ...
	 ClassLoader cl = getOrCreateSystemServerClassLoader();
            if (cl != null) {
                Thread.currentThread().setContextClassLoader(cl);
            }
      //Pass the remaining arguments to SystemServer.
     return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
                    parsedArgs.mDisabledCompatChanges,
                    parsedArgs.mRemainingArgs, cl);    
}
 public static Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
            String[] argv, ClassLoader classLoader) {
        if (RuntimeInit.DEBUG) {
            Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
        }

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
        RuntimeInit.redirectLogStreams();

        RuntimeInit.commonInit();
     	//启动Binder线程池
        ZygoteInit.nativeZygoteInit();
     	//进入SystemServer的main方法
        return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
                classLoader);
}
public static void main(String[] argv) {
    ...
    
    if (startSystemServer) {
          Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
         // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
         // child (system_server) process.
         //MethodAndArgsCaller.run方法
         if (r != null) {
               r.run();
               return;
         }
  }  
}

源码路径:frameworks/base/core/java/com/android/internal/os/RuntimeInit.java

protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
            String[] argv, ClassLoader classLoader) {
       	...
        // Remaining arguments are passed to the start class's static main
        return findStaticMain(args.startClass, args.startArgs, classLoader);
}
protected static Runnable findStaticMain(String className, String[] argv,
            ClassLoader classLoader) {
        Class<?> cl;

        try {
            //反射得到SystemServer类
            cl = Class.forName(className, true, classLoader);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Missing class when invoking static main " + className,
                    ex);
        }

        Method m;
        try {
            //知道main方法
            m = cl.getMethod("main", new Class[] { String[].class });
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException(
                    "Missing static main on " + className, ex);
        } catch (SecurityException ex) {
            throw new RuntimeException(
                    "Problem getting static main on " + className, ex);
        }

        int modifiers = m.getModifiers();
        if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
            throw new RuntimeException(
                    "Main method is not public and static on " + className);
        }

        /*
         * This throw gets caught in ZygoteInit.main(), which responds
         * by invoking the exception's run() method. This arrangement
         * clears up all the stack frames that were required in setting
         * up the process.
         */
        return new MethodAndArgsCaller(m, argv);
}
static class MethodAndArgsCaller implements Runnable {
        /** method to call */
        private final Method mMethod;

        /** argument array */
        private final String[] mArgs;

        public MethodAndArgsCaller(Method method, String[] args) {
            mMethod = method;
            mArgs = args;
        }

        public void run() {
            try {
                //动态调用SystemServer的main方法
                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);
            }
        }
}

解析SystemServer进程

main方法调用了SystemServer的run方法,在run方法里,首先进行了一些系统属性的设置、加载动态库及创建系统的Context。然后创建了SystemServiceManager,它会对系统服务进行创建、管理和生命周期管理。接下来有四个关键方法。

  • startBootstrapServices(t)。启动引导服务。共启动了约25个引导服务。例如我们熟知的AMS、PMS等服务。其中主要创建引导服务及作用如下(所有服务查看对应方法):
引导服务作用
Installer系统安装APK时候的一个服务类,启用完成Installer服务后才能启动其它的系统服务
ActivityManagerService负责四大组件的启动、切换、调度
PowerManagerServiceAndroid系统中和Power相关的计算,决策系统电影策略
LightService管理和显示背光LED
DisplayManagerService管理所有显示设备
PackageManagerService对APK进行安装、解析、验签、卸载等操作
UserManagerService多用户模式管理服务
SensorServiceAndroid各种感应器服务
  • startCoreServices(t)。启动核心服务。共启动了约11个核心服务。主要核心服务及作用如下(所有服务查看对应方法):
核心服务作用
BatteryService管理电池相关服务
UsageStatsService收集用户使用App的频率、使用时长
WebViewUpdateServiceWebview更新服务
BugreportManagerServicebugreport的管理服务
GpuService管理GPU资源的服务
  • startOtherServices(t)。启动其它服务。它启动了多达几十种服务。大多是我们使用设备功能息息相关的服务。主要其它服务及作用如下(所有服务查看对应方法):
其它服务作用
AlarmManagerService定时器管理服务
InputManagerService输入事件管理服务
CameraServiceProxy摄像相关服务
WindowManagerService窗口管理服务
VrManagerServiceVR模式管理服务
BluetoothService蓝牙管理服务
NotificationManagerService通知管理服务
StorageManagerService存储管理服务
LocationManagerService定位管理服务
AudioService音频管理服务

在这个方法里,可以看到服务启动的多个阶段标志,如PHASE_SYSTEM_SERVICES_READY/PHASE_DEVICE_SPECIFIC_SERVICES_READY等。其中PHASE_BOOT_COMPLETED=1000;标志着完成了Android开机启动流程。系统服务更倾向于监听该阶段,而不是注册广播BOOT_COMPLETED,从而降低系统延迟。

  • startApexServices(t)。启动Apex服务。

Apex服务是指Android操作系统中的一种应用程序启动方式,它允许应用程序在设备启动时以系统服务的形式自动运行。这些服务通常包括系统应用、框架服务和系统UI等。它们在设备启动时会自动运行,并为用户提供各种基础功能和界面。

startApexServices方法会遍历所有已安装的Apex服务,并调用它们的启动方法,使它们在系统启动时自动运行。该方法在系统启动过程中被调用,是Android操作系统启动过程中的一部分。

从这里我们也能看出来,官方将系统服务分为了以上四种。它们启动方法相似。通过SystemServiceManager类的startService方法启动。我们以PowerManagerService为例进行分析如何启动。

startService中调用PowerManagerService类的onStart方法完成启动PowerManagerService。

除了通过SystemServiceManager类的startService方法启动外,还有通过对应Service的main方法启动,例如PackageManagerService。

由源码可知,PackageManagerService被注册到ServiceManager中。ServiceManager用来管理系统的各种Service,这些服务通过Binder通信机制与应用程序进行通信。

源码路径:frameworks/base/services/java/com/android/server/SystemServer.java

public static void main(String[] args) {
   new SystemServer().run();
}
private void run() {
        TimingsTraceAndSlog t = new TimingsTraceAndSlog();
        try {
            ...
            //创建消息Looper
            Looper.prepareMainLooper();
            Looper.getMainLooper().setSlowLogThresholdMs(
                    SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

            SystemServiceRegistry.sEnableServiceNotFoundWtf = true;

            // 加载动态库libandroid_servers.so
            System.loadLibrary("android_servers");

            // Allow heap / perf profiling.
            initZygoteChildHeapProfiling();

            // Debug builds - spawn a thread to monitor for fd leaks.
            if (Build.IS_DEBUGGABLE) {
                spawnFdLeakCheckThread();
            }

            // Check whether we failed to shut down last time we tried.
            // This call may not return.
            performPendingShutdown();

            // 创建系统Context
            createSystemContext();

            // Call per-process mainline module initialization.
            ActivityThread.initializeMainlineModules();

            // Sets the dumper service
            ServiceManager.addService("system_server_dumper", mDumper);
            mDumper.addDumpable(this);
            // 创建SystemServiceManager,对系统服务进行创建、启动和生命周期管理
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            mSystemServiceManager.setStartInfo(mRuntimeRestart,
                    mRuntimeStartElapsedTime, mRuntimeStartUptime);
            mDumper.addDumpable(mSystemServiceManager);

            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
            // Prepare the thread pool for init tasks that can be parallelized
            SystemServerInitThreadPool tp = SystemServerInitThreadPool.start();
            mDumper.addDumpable(tp);
			...
        } finally {
            t.traceEnd();  // InitBeforeStartServices
        }

        // Setup the default WTF handler
        RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);

        // Start services.
        try {
            t.traceBegin("StartServices");
            //启动引导服务
            startBootstrapServices(t);
            //启动核心服务
            startCoreServices(t);
            //启动其它服务
            startOtherServices(t);
            //启动Apex服务
            startApexServices(t);
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            t.traceEnd(); // StartServices
        }
		...
    }
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
     ...
     //启动AMS,ActivityTaskManagerService->ActivityManagerService
     t.traceBegin("StartActivityManager");
     ActivityTaskManagerService atm = mSystemServiceManager.startService(
         ActivityTaskManagerService.Lifecycle.class).getService();
     mActivityManagerService = ActivityManagerService.Lifecycle.startService(
        mSystemServiceManager, atm);
     mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
     mActivityManagerService.setInstaller(installer);
     mWindowManagerGlobalLock = atm.getGlobalLock();
     t.traceEnd();
     t.traceBegin("StartPowerManager");
     mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
     t.traceEnd();
     t.traceBegin("StartPackageManagerService");
     try {
          Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
          Pair<PackageManagerService, IPackageManager> pmsPair = PackageManagerService.main(
                  mSystemContext, installer, domainVerificationService,
                  mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
          mPackageManagerService = pmsPair.first;
          iPackageManager = pmsPair.second;
     } finally {
          Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
     }
     ...
     mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
     ...
}
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
      ...
      // WMS needs sensor service ready
      mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_SENSOR_SERVICE);
      ...
      mSystemServiceManager.startBootPhase(t, SystemService.PHASE_LOCK_SETTINGS_READY);
      ...
      mSystemServiceManager.startBootPhase(t, SystemService.PHASE_SYSTEM_SERVICES_READY);
      ...
      mSystemServiceManager.startBootPhase(t, SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);
      ...
      mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
      ...
      mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
    
}
private void startApexServices(@NonNull TimingsTraceAndSlog t) {
     List<ApexSystemServiceInfo> services = ApexManager.getInstance().getApexSystemServices();
        for (ApexSystemServiceInfo info : services) {
            String name = info.getName();
            String jarPath = info.getJarPath();
            t.traceBegin("starting " + name);
            if (TextUtils.isEmpty(jarPath)) {
                mSystemServiceManager.startService(name);
            } else {
                mSystemServiceManager.startServiceFromJar(name, jarPath);
            }
            t.traceEnd();
        }
}

源码路径:frameworks/base/services/core/java/com/android/server/SystemServiceManager.java

public void startService(@NonNull final SystemService service) {
        // Check if already started
        String className = service.getClass().getName();
        if (mServiceClassnames.contains(className)) {
            Slog.i(TAG, "Not starting an already started service " + className);
            return;
        }
        mServiceClassnames.add(className);

        // Register it.
        mServices.add(service);

        // Start it.
        long time = SystemClock.elapsedRealtime();
        try {
            //启动service
            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");
}
//系统服务启动指定的启动阶段
public void startBootPhase(@NonNull TimingsTraceAndSlog t, int phase) {
        if (phase <= mCurrentPhase) {
            throw new IllegalArgumentException("Next phase must be larger than previous");
        }
        mCurrentPhase = phase;

        Slog.i(TAG, "Starting phase " + mCurrentPhase);
        try {
            t.traceBegin("OnBootPhase_" + phase);
            final int serviceLen = mServices.size();
            for (int i = 0; i < serviceLen; i++) {
                final SystemService service = mServices.get(i);
                long time = SystemClock.elapsedRealtime();
                t.traceBegin("OnBootPhase_" + phase + "_" + service.getClass().getName());
                try {
                    //系统服务的onBootPhase方法
                    service.onBootPhase(mCurrentPhase);
                } catch (Exception ex) {
                    throw new RuntimeException("Failed to boot service "
                            + service.getClass().getName()
                            + ": onBootPhase threw an exception during phase "
                            + mCurrentPhase, ex);
                }
                warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onBootPhase");
                t.traceEnd();
            }
        } finally {
            t.traceEnd();
        }
		//开机阶段
        if (phase == SystemService.PHASE_BOOT_COMPLETED) {
            final long totalBootTime = SystemClock.uptimeMillis() - mRuntimeStartUptime;
            t.logDuration("TotalBootTime", totalBootTime);
            SystemServerInitThreadPool.shutdown();
        }
}
public boolean isBootCompleted() {
   return mCurrentPhase >= SystemService.PHASE_BOOT_COMPLETED;
}

源码路径:frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java

public static Pair<PackageManagerService, IPackageManager> main(Context context,
            Installer installer, @NonNull DomainVerificationService domainVerificationService,
            boolean factoryTest, boolean onlyCore) {
    ...
    PackageManagerService m = new PackageManagerService(injector, onlyCore, factoryTest,
                PackagePartitions.FINGERPRINT, Build.IS_ENG, Build.IS_USERDEBUG,
                Build.VERSION.SDK_INT, Build.VERSION.INCREMENTAL);
    ...
    IPackageManagerImpl iPackageManager = m.new IPackageManagerImpl();
    ServiceManager.addService("package", iPackageManager);
    ...
}

SystemServer在启动系统服务存在多个阶段,如下所示:
源码路径:frameworks/base/services/core/java/com/android/server/SystemService.java

    /**
     * 系统在引导时向系统服务发送的最早引导阶段。
     */
    public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100;

    /**
     * 在SensorService可用性上阻塞的引导阶段。该服务是异步启动的,因为它可能需要一段时间才能完成初始化。
     * @hide
     */
    public static final int PHASE_WAIT_FOR_SENSOR_SERVICE = 200;

    /**
     * 在接收这个启动阶段后,服务可以获取锁设置数据。
     */
    public static final int PHASE_LOCK_SETTINGS_READY = 480;

    /**
     * 在收到此启动阶段后,服务可以安全地调用核心系统服务
     */
    public static final int PHASE_SYSTEM_SERVICES_READY = 500;

    /**
     * 在收到此启动阶段后,服务可以安全地调用设备特定的服务。
     */
    public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY = 520;

    /**
     * 在收到此启动阶段后,服务可以广播意图。
     */
    public static final int PHASE_ACTIVITY_MANAGER_READY = 550;

    /**
     * 在收到此启动阶段后,服务可以启动/绑定到第三方应用程序。应用程序将能够在此处对服务进行 Binder 调用。
     */
    public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;

    /**
     * 在收到此启动阶段后,服务允许用户与设备进行交互。此阶段发生在启动完成且主应用程序已启动时。系统服务可能更倾向于监听此阶	   * 段,而不是注册ACTION_LOCKED_BOOT_COMPLETED减少整体延迟。
     */
    public static final int PHASE_BOOT_COMPLETED = 1000;

总结

Zygote调用startSystemServer创建SystemServer进程。SystemServer进程启动了各种系统服务(四种),并且SystemServer在启动系统服务有定义多个阶段。SystemServiceManager对系统服务进行管理。

文章来源:https://blog.csdn.net/yang_study_first/article/details/134959725
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。