SystemServer进程启动过程源码分析

来源:互联网 发布:python爬虫实例 编辑:程序博客网 时间:2024/05/16 08:12

http://blog.csdn.net/yangwen123/article/details/17258089


目录(?)[+]

在上一篇文中介绍了Zygote进程的启动过程,我们知道,Zygote进程是Android Java世界的开创者,所有的Java应用程序进程都由Zygote进程创建。Zygote创建应用程序进程过程其实就是复制自身进程地址空间作为应用程序进程的地址空间,因此在Zygote进程中加载的类和资源都可以共享给所有由Zygote进程孵化的应用程序,应用程序进程只需加载自身私有资源就可以正常运行,Zygote进程是所有Android Java应用程序进程的父进程,Zygote进程和普通应用程序进程之间的关系正是面向对象编程语言中的继承关系,应用程序进程继承Zygote进程的所有资源,Zygote进程在启动时加载所有应用程序进程运行所需的公共资源,即应用程序运行的共性资源;由于普通应用程序有自己的特性资源,因此普通应用程序在启动时,只需要加载自身特性资源就可以了。Linux进程间这种继承关系加快了普通应用程序启动的速度,也简化了应用程序进程的创建过程。既然所有Java应用程序进程都是由Zygote进程创建,那么Android系统是如何请求Zygote进程创建一个新的应用程序进程的呢?在Zygote进程启动过程的源代码分析中,我们介绍了Zygote进程在启动过程中,会根据启动参数创建第一Java进程,它就是SystemServer进程,它是Android系统至关重要的进程,运行中Android系统的绝大部分服务。普通应用程序进程是无法直接请求Zygote进程孵化新进程的,所有的进程创建请求都是由SystemServer进程发出的。本文依据源码,详细分析SystemServer进程的启动过程。在Zygote进程进入循环监听Socket模式前,会根据Zygote启动参数来选择是否启动SystemServer进程,而Zygote进程的启动是在Android的启动脚本init.rc文件中配置的:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server  
由于配置了参数--start-system-server,因此SystemServer进程会伴随Zygote进程的启动而启动:
frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. if (argv[1].equals("start-system-server")) {  
  2.     startSystemServer();  
  3. else if (!argv[1].equals("")) {  
  4.     throw new RuntimeException(argv[0] + USAGE_STRING);  
  5. }  
SystemServer虽然也是又Zygote进程孵化出来,但和普通的应用程序进程的启动方式有所不同,这里是通过调用startSystemServer()函数来启动SystemServer进程的。
frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private static boolean startSystemServer()  
  2.         throws MethodAndArgsCaller, RuntimeException {  
  3.     /* Hardcoded command line to start the system server */  
  4.     String args[] = {  
  5.         "--setuid=1000",  
  6.         "--setgid=1000",  
  7.         "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006,3007",  
  8.         "--capabilities=130104352,130104352",  
  9.         "--runtime-init",  
  10.         "--nice-name=system_server",  
  11.         "com.android.server.SystemServer",  
  12.     };  
  13.     ZygoteConnection.Arguments parsedArgs = null;  
  14.     int pid;  
  15.     try {  
  16.         //参数解析  
  17.         parsedArgs = new ZygoteConnection.Arguments(args);  
  18.         //打开系统调试属性  
  19.         ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);  
  20.         ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);  
  21.   
  22.         /* 请求fork SystemServer进程*/  
  23.         pid = Zygote.forkSystemServer(  
  24.                 parsedArgs.uid, parsedArgs.gid,  
  25.                 parsedArgs.gids,  
  26.                 parsedArgs.debugFlags,  
  27.                 null,  
  28.                 parsedArgs.permittedCapabilities,  
  29.                 parsedArgs.effectiveCapabilities);  
  30.     } catch (IllegalArgumentException ex) {  
  31.         throw new RuntimeException(ex);  
  32.     }  
  33.   
  34.     /* pid为0表示子进程,即SystemServer进程,从此SystemServer进程与Zygote进程分道扬镳*/  
  35.     if (pid == 0) {  
  36.         handleSystemServerProcess(parsedArgs);  
  37.     }  
  38.     return true;  
  39. }  

在该函数中首先根据SystemServer进程启动参数args构造一个Arguments对象,然后调用forkSystemServer()函数创建SystemServer进程,最后调用函数handleSystemServerProcess()启动SystemServer进程,SystemServer启动参数如下:

"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006,3007",
"--capabilities=130104352,130104352",
"--runtime-init",
"--nice-name=system_server",
"com.android.server.SystemServer",

参数解析

frameworks\base\core\java\com\android\internal\os\ZygoteConnection.java
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Arguments(String args[]) throws IllegalArgumentException {  
  2.     parseArgs(args);  
  3. }  
在Arguments构造函数中直接调用parseArgs函数来解析SystemServer启动参数
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private void parseArgs(String args[])  
  2.         throws IllegalArgumentException {  
  3.     int curArg = 0;  
  4.     for ( /* curArg */ ; curArg < args.length; curArg++) {  
  5.         String arg = args[curArg];  
  6.         if (arg.equals("--")) {  
  7.             curArg++;  
  8.             break;  
  9.         } else if (arg.startsWith("--setuid=")) {  
  10.             if (uidSpecified) {  
  11.                 throw new IllegalArgumentException("Duplicate arg specified");  
  12.             }  
  13.             uidSpecified = true;  
  14.             //解析setuid参数,将进程uid保存到变量uid中  
  15.             uid = Integer.parseInt(arg.substring(arg.indexOf('=') + 1));  
  16.         } else if (arg.startsWith("--setgid=")) {  
  17.             if (gidSpecified) {  
  18.                 throw new IllegalArgumentException("Duplicate arg specified");  
  19.             }  
  20.             gidSpecified = true;  
  21.             //解析setgid参数,将进程gid保存到变量gid中  
  22.             gid = Integer.parseInt(arg.substring(arg.indexOf('=') + 1));  
  23.         } else if (arg.startsWith("--target-sdk-version=")) {  
  24.             if (targetSdkVersionSpecified) {  
  25.                 throw new IllegalArgumentException("Duplicate target-sdk-version specified");  
  26.             }  
  27.             targetSdkVersionSpecified = true;  
  28.             targetSdkVersion = Integer.parseInt(arg.substring(arg.indexOf('=') + 1));  
  29.         //根据参数设置debugFlags标志位  
  30.         } else if (arg.equals("--enable-debugger")) {  
  31.             debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;  
  32.         } else if (arg.equals("--enable-safemode")) {  
  33.             debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;  
  34.         } else if (arg.equals("--enable-checkjni")) {  
  35.             debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;  
  36.         } else if (arg.equals("--enable-jni-logging")) {  
  37.             debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;  
  38.         } else if (arg.equals("--enable-assert")) {  
  39.             debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;  
  40.         } else if (arg.equals("--peer-wait")) {  
  41.             peerWait = true;  
  42.         } else if (arg.equals("--runtime-init")) {  
  43.             runtimeInit = true;  
  44.         } else if (arg.startsWith("--capabilities=")) {  
  45.             if (capabilitiesSpecified) {  
  46.                 throw new IllegalArgumentException("Duplicate arg specified");  
  47.             }  
  48.             capabilitiesSpecified = true;  
  49.             String capString = arg.substring(arg.indexOf('=')+1);  
  50.             String[] capStrings = capString.split(","2);  
  51.             if (capStrings.length == 1) {  
  52.                 effectiveCapabilities = Long.decode(capStrings[0]);  
  53.                 permittedCapabilities = effectiveCapabilities;  
  54.             } else {  
  55.                 permittedCapabilities = Long.decode(capStrings[0]);  
  56.                 effectiveCapabilities = Long.decode(capStrings[1]);  
  57.             }  
  58.         } else if (arg.startsWith("--rlimit=")) {  
  59.             // Duplicate --rlimit arguments are specifically allowed.  
  60.             String[] limitStrings= arg.substring(arg.indexOf('=')+1).split(",");  
  61.             if (limitStrings.length != 3) {  
  62.                 throw new IllegalArgumentException("--rlimit= should have 3 comma-delimited ints");  
  63.             }  
  64.             int[] rlimitTuple = new int[limitStrings.length];  
  65.             for(int i=0; i < limitStrings.length; i++) {  
  66.                 rlimitTuple[i] = Integer.parseInt(limitStrings[i]);  
  67.             }  
  68.             if (rlimits == null) {  
  69.                 rlimits = new ArrayList();  
  70.             }  
  71.             rlimits.add(rlimitTuple);  
  72.         } else if (arg.equals("-classpath")) {  
  73.             if (classpath != null) {  
  74.                 throw new IllegalArgumentException("Duplicate arg specified");  
  75.             }  
  76.             try {  
  77.                 classpath = args[++curArg];  
  78.             } catch (IndexOutOfBoundsException ex) {  
  79.                 throw new IllegalArgumentException("-classpath requires argument");  
  80.             }  
  81.         } else if (arg.startsWith("--setgroups=")) {  
  82.             if (gids != null) {  
  83.                 throw new IllegalArgumentException("Duplicate arg specified");  
  84.             }  
  85.             String[] params = arg.substring(arg.indexOf('=') + 1).split(",");  
  86.             gids = new int[params.length];  
  87.             for (int i = params.length - 1; i >= 0 ; i--) {  
  88.                 gids[i] = Integer.parseInt(params[i]);  
  89.             }  
  90.         } else if (arg.equals("--invoke-with")) {  
  91.             if (invokeWith != null) {  
  92.                 throw new IllegalArgumentException("Duplicate arg specified");  
  93.             }  
  94.             try {  
  95.                 invokeWith = args[++curArg];  
  96.             } catch (IndexOutOfBoundsException ex) {  
  97.                 throw new IllegalArgumentException("--invoke-with requires argument");  
  98.             }  
  99.         } else if (arg.startsWith("--nice-name=")) {  
  100.             if (niceName != null) {  
  101.                 throw new IllegalArgumentException("Duplicate arg specified");  
  102.             }  
  103.             niceName = arg.substring(arg.indexOf('=') + 1);  
  104.         } else {  
  105.             break;  
  106.         }  
  107.     }  
  108.     //参数-classpath 和 --runtime-init 不能同时设置  
  109.     if (runtimeInit && classpath != null) {  
  110.         throw new IllegalArgumentException("--runtime-init and -classpath are incompatible");  
  111.     }  
  112.     //保存剩余参数  
  113.     remainingArgs = new String[args.length - curArg];  
  114.     System.arraycopy(args, curArg, remainingArgs, 0,remainingArgs.length);  
  115. }  

属性配置

frameworks\base\core\java\com\android\internal\os\ZygoteConnection.java
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static void applyDebuggerSystemProperty(Arguments args) {  
  2.     if ("1".equals(SystemProperties.get("ro.debuggable"))) {  
  3.         args.debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;  
  4.     }  
  5. }  
  6.   
  7. public static void applyInvokeWithSystemProperty(Arguments args) {  
  8.     if (args.invokeWith == null && args.niceName != null) { //true  
  9.         if (args.niceName != null) {  
  10.             String property = "wrap." + args.niceName; //wrap.system_server  
  11.             if (property.length() > 31) {  
  12.                 property = property.substring(031);  
  13.             }  
  14.             args.invokeWith = SystemProperties.get(property);  
  15.             if (args.invokeWith != null && args.invokeWith.length() == 0) {  
  16.                 args.invokeWith = null;  
  17.             }  
  18.         }  
  19.     }  
  20. }  

创建SystemServer进程

通过调用forkSystemServer函数来创建SystemServer进程

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static int forkSystemServer(int uid, int gid, int[] gids,  
  2.         int debugFlags, int[][] rlimits,  
  3.         long permittedCapabilities, long effectiveCapabilities) {  
  4.     //停止Zygote进程中的其他线程,保证单线程  
  5.     preFork();  
  6.     int pid = nativeForkSystemServer(uid, gid, gids, debugFlags, rlimits,permittedCapabilities,effectiveCapabilities);  
  7.     //启动垃圾回收后台线程  
  8.     postFork();  
  9.     return pid;  
  10. }  

该函数调用native函数nativeForkAndSpecialize来fork出systemserver进程

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. native public static int nativeForkSystemServer(int uid, int gid,int[] gids, int debugFlags, int[][] rlimits,  
  2.             long permittedCapabilities, long effectiveCapabilities);  
  3. "nativeForkSystemServer""(II[II[[IJJ)I", Dalvik_dalvik_system_Zygote_forkSystemServer },  

根据JNI函数映射关系,最终会调用C++的Dalvik_dalvik_system_Zygote_forkSystemServer函数,在dalvik_system_Zygote.c文件中实现:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. static void Dalvik_dalvik_system_Zygote_forkSystemServer(const u4* args, JValue* pResult)  
  2. {  
  3.     pid_t pid;  
  4.     //根据参数,fork一个子进程  
  5.     pid = forkAndSpecializeCommon(args, true);  
  6.   
  7.     /* The zygote process checks whether the child process has died or not. */  
  8.     if (pid > 0) {  
  9.         int status;  
  10.         ALOGI("System server process %d has been created", pid);  
  11.         gDvm.systemServerPid = pid;  
  12.         /* There is a slight window that the system server process has crashed 
  13.          * but it went unnoticed because we haven't published its pid yet. So 
  14.          * we recheck here just to make sure that all is well. 
  15.          */  
  16.         if (waitpid(pid, &status, WNOHANG) == pid) {  
  17.             ALOGE("System server process %d has died. Restarting Zygote!", pid);  
  18.             /*kill(getpid(), SIGKILL);*/  
  19.             sleep(15);  
  20.       //如果SystemServer进程退出,zygote将杀死自身进程  
  21. #ifdef HOST_DALVIK  
  22.             reboot(RB_AUTOBOOT);  
  23. #else  
  24.             android_reboot(ANDROID_RB_RESTART2, 0, (char *)"special-systemserver-died");  
  25. #endif  
  26.         }  
  27.     }  
  28.     RETURN_INT(pid);  
  29. }  

真正创建进程的核心函数:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. static pid_t forkAndSpecializeCommon(const u4* args, bool isSystemServer)  
  2. {  
  3.     ..........  
  4.     pid = fork(); //使用Linux 系统调用fork来创建进程  
  5.   
  6.     if (pid == 0) {  
  7.         //设置子进程的uid,gid等参数  
  8.   
  9.     } else if (pid > 0) {  
  10.         /* the parent process */  
  11.     }  
  12.     return pid;  
  13. }  

创建好SystemServer进程后,继续调用preFork()来启动后台线程

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private static void postFork() {  
  2.     Daemons.start(); //启动后台线程  
  3. }  
libcore\luni\src\main\java\java\lang\Daemons.java

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static void start() {  
  2.     //启动ReferenceQueueDaemon线程  
  3.     ReferenceQueueDaemon.INSTANCE.start();  
  4.     //启动FinalizerDaemon线程  
  5.     FinalizerDaemon.INSTANCE.start();  
  6.     //启动FinalizerWatchdogDaemon线程  
  7.     FinalizerWatchdogDaemon.INSTANCE.start();  
  8. }  

运行SystemServer进程


新创建的SystemServer进程会执行handleSystemServerProcess函数,来完成自己的使命。

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private static void handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs)  
  2.         throws ZygoteInit.MethodAndArgsCaller {  
  3.           //因为SystemServer是从Zygote进程中复制过来的,所有需要关闭从zygote继承下来的socket  
  4.     closeServerSocket();  
  5.     // set umask to 0077 so new files and directories will default to owner-only permissions.  
  6.     FileUtils.setUMask(FileUtils.S_IRWXG | FileUtils.S_IRWXO);  
  7.           //设置进程名称  
  8.     if (parsedArgs.niceName != null) {  
  9.         Process.setArgV0(parsedArgs.niceName);  
  10.     }  
  11.     if (parsedArgs.invokeWith != null) {  
  12.         WrapperInit.execApplication(parsedArgs.invokeWith,  
  13.                 parsedArgs.niceName, parsedArgs.targetSdkVersion,  
  14.                 null, parsedArgs.remainingArgs);  
  15.     } else {  
  16.                 //传递剩余参数给SystemServer并调用zygoteInit函数  
  17.             // "--nice-name=system_server com.android.server.SystemServer"  
  18.         RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs);  
  19.     }  
  20. }  
由于由Zygote进程创建的子进程都会继承Zygote进程在前面创建的Socket文件描述符,而这里的SystemServer进程又不会用到它,因此,这里就调用closeServerSocket函数来关闭它。这个函数接着调用RuntimeInit.zygoteInit函数来进一步执行启动SystemServer
frameworks\base\core\java\com\android\internal\os\RuntimeInit.java

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static final void zygoteInit(int targetSdkVersion, String[] argv)  
  2.         throws ZygoteInit.MethodAndArgsCaller {  
  3.     if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote");  
  4.     //重定向Log输出流  
  5.     redirectLogStreams();  
  6.     //初始化运行环境  
  7.     commonInit();  
  8.     //启动Binder线程池  
  9.     nativeZygoteInit();  
  10.     //调用程序入口函数  
  11.     applicationInit(targetSdkVersion, argv);  
  12. }  

1. 初始化Log输出流

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * Redirect System.out and System.err to the Android log. 
  3.  */  
  4. public static void redirectLogStreams() {  
  5.     System.out.close();  
  6.     System.setOut(new AndroidPrintStream(Log.INFO, "System.out"));  
  7.     System.err.close();  
  8.     System.setErr(new AndroidPrintStream(Log.WARN, "System.err"));  
  9. }  

2.初始化运行环境

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private static final void commonInit() {  
  2.     if (DEBUG) Slog.d(TAG, "Entered RuntimeInit!");  
  3.   
  4.     /* set default handler; this applies to all threads in the VM */  
  5.     Thread.setDefaultUncaughtExceptionHandler(new UncaughtHandler());  
  6.   
  7.     /* 
  8.      * Install a TimezoneGetter subclass for ZoneInfo.db 
  9.      */  
  10.     TimezoneGetter.setInstance(new TimezoneGetter() {  
  11.         @Override  
  12.         public String getId() {  
  13.             return SystemProperties.get("persist.sys.timezone");  
  14.         }  
  15.     });  
  16.     TimeZone.setDefault(null);  
  17.   
  18.     /* 
  19.      * Sets handler for java.util.logging to use Android log facilities. 
  20.      * The odd "new instance-and-then-throw-away" is a mirror of how 
  21.      * the "java.util.logging.config.class" system property works. We 
  22.      * can't use the system property here since the logger has almost 
  23.      * certainly already been initialized. 
  24.      */  
  25.     LogManager.getLogManager().reset();  
  26.     new AndroidConfig();  
  27.   
  28.     /* 
  29.      * Sets the default HTTP User-Agent used by HttpURLConnection. 
  30.      */  
  31.     String userAgent = getDefaultUserAgent();  
  32.     System.setProperty("http.agent", userAgent);  
  33.   
  34.     /* 
  35.      * Wire socket tagging to traffic stats. 
  36.      */  
  37.     NetworkManagementSocketTagger.install();  
  38.   
  39.     /* 
  40.      * If we're running in an emulator launched with "-trace", put the 
  41.      * VM into emulator trace profiling mode so that the user can hit 
  42.      * F9/F10 at any time to capture traces.  This has performance 
  43.      * consequences, so it's not something you want to do always. 
  44.      */  
  45.     String trace = SystemProperties.get("ro.kernel.android.tracing");  
  46.     if (trace.equals("1")) {  
  47.         Slog.i(TAG, "NOTE: emulator trace profiling enabled");  
  48.         Debug.enableEmulatorTraceOutput();  
  49.     }  
  50.   
  51.     initialized = true;  
  52. }  

3.启动Binder线程池

frameworks\base\core\jni\AndroidRuntime.cpp 
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz)  
  2. {  
  3.     gCurRuntime->onZygoteInit();  
  4. }  
frameworks\base\cmds\app_process\App_main.cpp 
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. virtual void onZygoteInit()  
  2. {  
  3.     sp<ProcessState> proc = ProcessState::self();  
  4.     ALOGV("App process: starting thread pool.\n");  
  5.     proc->startThreadPool();  
  6. }  
关于Binder线程池的启动过程请参考Android应用程序启动Binder线程源码分析

4.调用进程入口函数

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. static void invokeStaticMain(ClassLoader loader,  
  2.         String className, String[] argv)  
  3.         throws ZygoteInit.MethodAndArgsCaller {  
  4.     //加载"com.android.server.SystemServer"类  
  5.     Class<?> cl;  
  6.     try {  
  7.         cl = loader.loadClass(className);  
  8.     } catch (ClassNotFoundException ex) {  
  9.         throw new RuntimeException("Missing class when invoking static main " + className,  
  10.                 ex);  
  11.     }  
  12.     //通过类反射机制查找SystemServer类中的main函数  
  13.     Method m;  
  14.     try {  
  15.         m = cl.getMethod("main"new Class[] { String[].class });  
  16.     } catch (NoSuchMethodException ex) {  
  17.         throw new RuntimeException("Missing static main on " + className, ex);  
  18.     } catch (SecurityException ex) {  
  19.         throw new RuntimeException("Problem getting static main on " + className, ex);  
  20.     }  
  21.     //获取main函数的修饰符  
  22.     int modifiers = m.getModifiers();  
  23.     //进程入口函数必须为静态Public类型  
  24.     if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {  
  25.         throw new RuntimeException("Main method is not public and static on " + className);  
  26.     }  
  27.     /* 
  28.      * This throw gets caught in ZygoteInit.main(), which responds 
  29.      * by invoking the exception's run() method. This arrangement 
  30.      * clears up all the stack frames that were required in setting 
  31.      * up the process. 
  32.      */  
  33.     throw new ZygoteInit.MethodAndArgsCaller(m, argv);  
  34. }  
抛出MethodAndArgsCaller异常,并在ZygoteInit.main()函数中捕获该异常,这样就可以清除应用程序进程创建过程的调用栈,将应用程序启动的入口函数设置为SystemServer.main()
frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static void main(String argv[]) {  
  2.     try {  
  3.         ...  
  4.     //捕获MethodAndArgsCaller异常  
  5.     } catch (MethodAndArgsCaller caller) {  
  6.         caller.run();  
  7.     } catch (RuntimeException ex) {  
  8.         Log.e(TAG, "Zygote died with exception", ex);  
  9.         closeServerSocket();  
  10.         throw ex;  
  11.     }  
  12. }  
在该函数里,捕获了MethodAndArgsCaller异常,并调用MethodAndArgsCaller类的run()方法来处理异常
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static class MethodAndArgsCaller extends Exception implements Runnable {  
  2.     public void run() {  
  3.         try {  
  4.             mMethod.invoke(nullnew Object[] { mArgs });  
  5.         } catch (IllegalAccessException ex) {  
  6.             throw new RuntimeException(ex);  
  7.         } catch (InvocationTargetException ex) {  
  8.             Throwable cause = ex.getCause();  
  9.             if (cause instanceof RuntimeException) {  
  10.                 throw (RuntimeException) cause;  
  11.             } else if (cause instanceof Error) {  
  12.                 throw (Error) cause;  
  13.             }  
  14.             throw new RuntimeException(ex);  
  15.         }  
  16.     }  
  17. }  
这里通过反射机制调用SystemServer类的main函数
frameworks\base\services\java\com\android\server\SystemServer.java
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static void main(String[] args) {  
  2.     if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {  
  3.         // If a device's clock is before 1970 (before 0), a lot of  
  4.         // APIs crash dealing with negative numbers, notably  
  5.         // java.io.File#setLastModified, so instead we fake it and  
  6.         // hope that time from cell towers or NTP fixes it  
  7.         // shortly.  
  8.         Slog.w(TAG, "System clock is before 1970; setting to 1970.");  
  9.         SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);  
  10.     }  
  11.     //启动SamplingProfilerIntegration线程,并且每隔1小时写一次快照  
  12.     if (SamplingProfilerIntegration.isEnabled()) {  
  13.         SamplingProfilerIntegration.start();  
  14.         timer = new Timer();  
  15.         timer.schedule(new TimerTask() {  
  16.             @Override  
  17.             public void run() {  
  18.                 SamplingProfilerIntegration.writeSnapshot("system_server"null);  
  19.             }  
  20.         }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);  
  21.     }  
  22.     // Mmmmmm... more memory!  
  23.     dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();  
  24.     // The system server has to run all of the time, so it needs to be  
  25.     // as efficient as possible with its memory usage.  
  26.     VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);  
  27.     //加载libandroid_servers.so库  
  28.     System.loadLibrary("android_servers");  
  29.     //进入服务启动第一阶段:启动native服务  
  30.     init1(args);  
  31. }  
SystemServer类的main函数是SystemServer进程的入口函数,在该函数里,首先加载libandroid_servers.so库,然后调用init1启动native相关服务
frameworks\base\services\jni\com_android_server_SystemServer.cpp 
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)  
  2. {  
  3.     system_init();  
  4. }  
frameworks\base\cmds\system_server\library\system_init.cpp
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. extern "C" status_t system_init()  
  2. {  
  3.     ALOGI("Entered system_init()");  
  4.     sp<ProcessState> proc(ProcessState::self());  
  5.     sp<IServiceManager> sm = defaultServiceManager();  
  6.     ALOGI("ServiceManager: %p\n", sm.get());  
  7.   
  8.     sp<GrimReaper> grim = new GrimReaper();  
  9.     sm->asBinder()->linkToDeath(grim, grim.get(), 0);  
  10.   
  11.     char propBuf[PROPERTY_VALUE_MAX];  
  12.     property_get("system_init.startsurfaceflinger", propBuf, "1");  
  13.     if (strcmp(propBuf, "1") == 0) {  
  14.         // Start the SurfaceFlinger  
  15.         SurfaceFlinger::instantiate();  
  16.     }  
  17.   
  18.     property_get("system_init.startsensorservice", propBuf, "1");  
  19.     if (strcmp(propBuf, "1") == 0) {  
  20.         // Start the sensor service  
  21.         SensorService::instantiate();  
  22.     }  
  23.   
  24.     // And now start the Android runtime.  We have to do this bit  
  25.     // of nastiness because the Android runtime initialization requires  
  26.     // some of the core system services to already be started.  
  27.     // All other servers should just start the Android runtime at  
  28.     // the beginning of their processes's main(), before calling  
  29.     // the init function.  
  30.     ALOGI("System server: starting Android runtime.\n");  
  31.     AndroidRuntime* runtime = AndroidRuntime::getRuntime();  
  32.   
  33.     ALOGI("System server: starting Android services.\n");  
  34.     JNIEnv* env = runtime->getJNIEnv();  
  35.     if (env == NULL) {  
  36.         return UNKNOWN_ERROR;  
  37.     }  
  38.     //通过JNI调用SystemServer类的init2()函数,启动Java服务  
  39.     jclass clazz = env->FindClass("com/android/server/SystemServer");  
  40.     if (clazz == NULL) {  
  41.         return UNKNOWN_ERROR;  
  42.     }  
  43.     jmethodID methodId = env->GetStaticMethodID(clazz, "init2""()V");  
  44.     if (methodId == NULL) {  
  45.         return UNKNOWN_ERROR;  
  46.     }  
  47.     env->CallStaticVoidMethod(clazz, methodId);  
  48.     //启动Binder线程池  
  49.     ALOGI("System server: entering thread pool.\n");  
  50.     ProcessState::self()->startThreadPool();  
  51.     IPCThreadState::self()->joinThreadPool();  
  52.     ALOGI("System server: exiting thread pool.\n");  
  53.     return NO_ERROR;  
  54. }  
在该函数里,通过JNI调用SystemServer类中的init2函数进一步启动Android系统中的Java服务,然后将SystemServer进程的主线程注册到Binder线程池中
frameworks\base\services\java\com\android\server\SystemServer.java
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static final void init2() {  
  2.     Slog.i(TAG, "Entered the Android system server!");  
  3.     //通过启动ServerThread线程来启动Java服务  
  4.     Thread thr = new ServerThread();  
  5.     thr.setName("android.server.ServerThread");  
  6.     thr.start();  
  7. }  
这里通过启动一个名为android.server.ServerThread的线程来启动Android系统服务
frameworks\base\services\java\com\android\server\SystemServer$ServerThread
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public void run() {  
  2.     EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,SystemClock.uptimeMillis());  
  3.     Looper.prepare();  
  4.   
  5.     android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);  
  6.     BinderInternal.disableBackgroundScheduling(true);  
  7.     android.os.Process.setCanSelfBackground(false);  
  8.     ....  
  9.     ServiceManager.addService("entropy"new EntropyMixer());  
  10.     ServiceManager.addService(Context.POWER_SERVICE, power);  
  11.     ServiceManager.addService("security", security);  
  12.     ServiceManager.addService("telephony.registry",new TelephonyRegistry(context, 0));  
  13.     ServiceManager.addService(Context.SCHEDULING_POLICY_SERVICE,new SchedulingPolicyService());  
  14.     ....  
  15.     //PowerManagerServer WakeLock dump thread  
  16.     (new Thread(new WakelockMonitor(power))).start();  
  17.   
  18.     // For debug builds, log event loop stalls to dropbox for analysis.  
  19.     if (StrictMode.conditionallyEnableDebugLogging()) {  
  20.         Slog.i(TAG, "Enabled StrictMode for system server main thread.");  
  21.     }  
  22.     Looper.loop();  
  23.     Slog.d(TAG, "System ServerThread is exiting!");  
  24. }  

在run函数中启动并注册Java中的各种Service。至此SystemServer进程启动过程分析完毕!启动过程序列图如下所示:


1

0 0
原创粉丝点击