Android-Framework 学习笔记(三)SystemServer 进程启动过程
{gCurRuntime->onZygoteInit();}
这里 gCurRuntime 是 AndroidRuntime 类型的指针,AndroidRuntime 的子类 AppRuntime 在 app_main.cpp 中定义,我们来查看 AppRuntime 的 onZygoteInit 函数
frameworks/base/cmds/app_process/app_main.cpp
AppRuntime#onZygoteInit()
virtual void onZygoteInit(){sp<ProcessState> proc = ProcessState::self();ALOGV("App process: starting thread pool.\n");proc->startThreadPool();//1}
注释 1 处会调用 ProcessState 的 startThreadPool 函数。
frameworks/native/libs/binder/ProcessState.cpp
ProcessState#startThreadPool()
void ProcessState::startThreadPool(){AutoMutex _l(mLock);//1if (!mThreadPoolStarted) {
mThreadPoolStarted = true;spawnPooledThread(true);}}
支持 Binder 通信的进程中都有一个 ProcessState 类,它里面有一个 mThreadPoolStarted 变量,来表示 Binder 线程池是否已经被启动过,默认值为 false。在每次调用这个函数时都会先去检查这个标记,从而确保 Binder 线程池只会被启动一次。注释 1 如果 Binder 线程池未被启动则设置 mThreadPoolStarted 为 true,最后调用 spawnPooledThread 函数来创建线程池中的第一个线程,也就是线程池的 main 线程。
ProcessState#spawnPooledThread()
void ProcessState::spawnPooledThread(bool isMain){if (mThreadPoolStarted) {String8 name = makeBinderThreadName();ALOGV("Spawning new pooled thread, name=%s\n", name.string());sp<Thread> t = new PoolThread(isMain);t->run(name.string());//1}}
可以看到 Binder 线程为一个 PoolThread。注释 1 调用 PoolThread 的 run 函数来启动一个新的线程。
PoolThread
class PoolThread : public Thread{..protected:virtual bool threadLoop(){IPCThreadState::self()->joinThreadPool(mIsMain);//1return false;}const bool mIsMain;};
PoolThread 类继承了 Thread 类。注释 1 处会将调用 IPCThreadState 的 joinThreadPool 函数,将当前线程注册到 Binder 驱动程序中,这样我们创建的线程就加入了 Binder 线程池中,这样新创建的 SyetemServer 进程就支持 Binder 进程间通信了。
回到 RuntimeInit#zygoteInit()的注释 2。
RuntimeInit#applicationInit()
private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)throws ZygoteInit.MethodAndArgsCaller {...
// 初始化虚拟机环境 VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
final Arguments args;try {args = new Arguments(argv);} catch (IllegalArgumentException ex) {Slog.e(TAG, ex.getMessage());// let the process exitreturn;}
// Remaining arguments are passed to the start class's static maininvokeStaticMain(args.startClass, args.startArgs, classLoader); //1}
注释 1 处 applicationInit 函数中主要调用了 invokeStaticMain 函数。
RuntimeInit#invokeStaticMain()
private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader) throws ZygoteInit.MethodAndArgsCaller {Class<?> cl;
try {cl = Class.forName(className, true, classLoader); //1} 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 }); //2} 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(); //3if (! (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.*/throw new ZygoteInit.MethodAndArgsCaller(m, argv); //4}
注释 1 处传入的 className 就是 com.android.server.SystemServer ,因此通过反射返回的 cl 为 SystemServer 类。注释 2 获取 main 方法 。注释 3 判断修饰符,必须是 static 而且必须是 public 类型。注释 4 有点意思,做完这一切之后,将找到的 main 函数传入到 MethodAndArgsCaller 异常中并抛出该异常。辛苦辛苦各种初始化,各种变着法的调用,最后你居然给我抛个异常!先别急,这个异常在 ZygoteInit#main()方法中捕获。这么做的作用是清除应用程序进程创建过程的调用栈。
ZygoteInit#main()函数见上一篇文章,我们这里再看一下框架:
public static void main(String argv[]) {try {...startSystemServer(abiList, socketName);...} catch (MethodAndArgsCaller caller) {caller.run(); //1}}
在注释 1 处调用了 MethodAndArgsCaller 的 run 函数。
MethodAndArgsCaller
public static class MethodAndArgsCaller extends Exceptionimplements 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 {mMethod.invoke(null, new Object[] { mArgs }); //1} 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);}}}
注释 1 处通过反射调用了 com.android.server.SystemServer#main(String[] args)。至此,Zygote 进程 fork 出 SystemServer 进程,并成功调用 SystemServer#main()。
解析 SyetemServer 进程我们先来查看 SystemServer 的 main 函数:
frameworks/base/services/java/com/android/server/SystemServer.java
SystemServer#main()
public static void main(String[] args) {new SystemServer().run(); //1}
注释 1 处 main 函数中只调用了 SystemServer 的 run 函数。
SystemServer#run()
private void run() {...System.loadLibrary("android_servers");//1...mSystemServiceManager = new SystemServiceManager(mSystemContext);//2LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);...
try {Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");startBootstrapServices();//3startCoreServices();//4startOtherServices();//5} catch (Throwable ex) {Slog.e("System", "******************************");Slog.e("System", " Failure starting system services", ex);throw ex;} finally {Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}...}
注释 1 处加载了 libandroid_servers.so。注释 2 处创建 SystemServiceManager,它会对系统的服务进行创建、启动和生命周期管理。启动系统的各种服务。注释 3 中的 startBootstrapServices 函数中用 SystemServiceManager 启动了 ActivityManagerService、PowerManagerService、PackageManagerService 等服务。注释 4 处的函数中则启动了 BatteryService、UsageStatsService 和 WebViewUpdateService。注释 5 处的 startOtherServices 函数中则启动了 CameraService、AlarmManagerService、VrManagerService 等服务,这些服务的父类为 SystemService。
从注释 3、4、5 的函数可以看出,官方把系统服务分为了三种类型,分别是引导服务、核心服务和其他服务,其中其他服务为一些非紧要和一些不需要立即启动的服务。系统服务大约有 80 多个,这里列出部分系统服务以及它们的作用:
继续往下看,我们这里只看看注释 3 如何启动引导服务,注释 4、5 类似。
SystemServer#startBootstrapServices()
private void startBootstrapServices() {...mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);...
mPackageManagerService = PackageManagerService.main(mSystemContext, installer, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);...}
这里面要启动的引导服务很多,我们来看看 PowerManagerService 和 PackageManagerService 吧。
首先是 PowerManagerService,它是通过 SystemServiceManager.startService()来启动的:
frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
**SystemServiceMana
ger#startService()**
public <T extends SystemService> T startService(Class<T> serviceClass) {try {final String name = serviceClass.getName();...
final T service;try {Constructor<T> constructor = serviceClass.getConstructor(Context.class);service = constructor.newInstance(mContext); //1} 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);}
// Register it.mServices.add(service); //2
// Start it.try {service.onStart(); //3} catch (RuntimeException ex) {throw new RuntimeException("Failed to start service " + name + ": onStart threw an exception", ex);}return service;} finally {Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}}
评论