Android情景分析之深入解析system_server

来源:互联网 发布:2016淘宝详情页尺寸 编辑:程序博客网 时间:2024/05/21 22:27

from :http://blog.csdn.net/hu3167343/article/details/38375167


system_server进程作为zygote的嫡长子,其重要性是不言而喻的。下面我们通过代码来深入分析下system_server的实现。

system_server的诞生

在深入解析zygote的时候,我们看过system_server的启动过程,这里我们再来回顾下:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /* Hardcoded command line to start the system server */  
  2. String args[] = {  
  3.     "--setuid=1000",  
  4.     "--setgid=1000",  
  5.     "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1032,3001,3002,3003,3006,3007",  
  6.     "--capabilities=" + capabilities + "," + capabilities,  
  7.     "--runtime-init",  
  8.     "--nice-name=system_server",  
  9.     "com.android.server.SystemServer",  
  10. };  
  11. ZygoteConnection.Arguments parsedArgs = null;  
  12.   
  13. int pid;  
  14.   
  15. try {  
  16.     parsedArgs = new ZygoteConnection.Arguments(args);  
  17.     ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);  
  18.     ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);  
  19.   
  20.     /* Request to fork the system server process */  
  21.     pid = Zygote.forkSystemServer(  
  22.             parsedArgs.uid, parsedArgs.gid,  
  23.             parsedArgs.gids,  
  24.             parsedArgs.debugFlags,  
  25.             null,  
  26.             parsedArgs.permittedCapabilities,  
  27.             parsedArgs.effectiveCapabilities);  
  28. catch (IllegalArgumentException ex) {  
  29.     throw new RuntimeException(ex);  
  30. }  
  31.   
  32. /* For child process */  
  33. if (pid == 0) {  
  34.     handleSystemServerProcess(parsedArgs);  
  35. }  

从上面的代码中,我们可以看出system_server是zygote通过调用Zygote.forkSystemServer函数来创建的。先来看看forkSystemServer的实现:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,  
  2.             int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {  
  3.     preFork();  
  4.     int pid = nativeForkSystemServer(  
  5.             uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);  
  6.     postFork();  
  7.     return pid;  
  8. }  

该函数主要通过native函数nativeForkSystemServer来完成主要功能,对应文件为dalvik\vm\native\dalvik_system_Zygote.cpp:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * native public static int nativeForkSystemServer(int uid, int gid, 
  3.  *     int[] gids, int debugFlags, int[][] rlimits, 
  4.  *     long permittedCapabilities, long effectiveCapabilities); 
  5.  */  
  6. static void Dalvik_dalvik_system_Zygote_forkSystemServer(  
  7.         const u4* args, JValue* pResult)  
  8. {  
  9.     pid_t pid;  
  10.     pid = forkAndSpecializeCommon(args, true);  
  11.   
  12.     /* The zygote process checks whether the child process has died or not. */  
  13.     if (pid > 0) {  
  14.         int status;  
  15.         gDvm.systemServerPid = pid; // 赋值system_server pid  
  16.         /* There is a slight window that the system server process has crashed 
  17.          * but it went unnoticed because we haven't published its pid yet. So 
  18.          * we recheck here just to make sure that all is well. 
  19.          */  
  20.         if (waitpid(pid, &status, WNOHANG) == pid) {  
  21.             ALOGE("System server process %d has died. Restarting Zygote!", pid);  
  22.   
  23.             // 如果system_server进程在fork完毕,执行的过程中挂了,那么  
  24.             // Zygote就把自己给杀了,简直就是同生共死啊。  
  25.             kill(getpid(), SIGKILL);  
  26.         }  
  27.     }  
  28.     RETURN_INT(pid);  
  29. }  

最后通过forkAndSpecializeCommon函数fork出system_server进程,接着来看:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * Utility routine to fork zygote and specialize the child process. 
  3.  */  
  4. static pid_t forkAndSpecializeCommon(const u4* args, bool isSystemServer)  
  5. {  
  6.     …….  
  7.       
  8.     if (!gDvm.zygote) {  
  9.         dvmThrowIllegalStateException(  
  10.             "VM instance not started with -Xzygote");  
  11.   
  12.         return -1;  
  13.     }  
  14.   
  15.     if (!dvmGcPreZygoteFork()) {  
  16.         ALOGE("pre-fork heap failed");  
  17.         dvmAbort();  
  18.     }  
  19.       
  20.     /* 
  21. 设置子进程的信号处理函数,子进程system_server如果挂了,那么, 
  22. Zygote会调用kill函数把自己给杀了。 
  23.     */  
  24.     setSignalHandler();  
  25.   
  26.     dvmDumpLoaderStats("zygote");  
  27.     pid = fork();   // fork分裂出子进程  
  28.   
  29. if (pid == 0) {  
  30. // …. 根据传进来的参数设置子进程相关属性  
  31. }  
  32. ….  
  33. }  

OK,至此,system_server作为zygote的嫡长子,已经被创建出来了。并且,它的地位也是非常高的,和zygote同生共死。它那么重要,具体承担了什么工作呢?下面我们来继续分析。


system_server的使命

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /* For child process */  
  2. if (pid == 0) {  
  3.      handleSystemServerProcess(parsedArgs);  
  4. }  

Zygote fork出了system_server之后,后者便调用handleSystemServerProcess开始了自己的使命。

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * Finish remaining work for the newly forked system server process. 
  3.      */  
  4.     private static void handleSystemServerProcess(  
  5.             ZygoteConnection.Arguments parsedArgs)  
  6.             throws ZygoteInit.MethodAndArgsCaller {  
  7.           
  8.         // 关闭从zygote那里继承下来的socket  
  9.         closeServerSocket();  
  10.           
  11.         // set umask to 0077 so new files and directories will default to owner-only permissions.  
  12.         Libcore.os.umask(S_IRWXG | S_IRWXO);  
  13.           
  14.         // 修改进程名为system_server  
  15.         if (parsedArgs.niceName != null) {  
  16.             Process.setArgV0(parsedArgs.niceName);  
  17.         }  
  18.   
  19.         if (parsedArgs.invokeWith != null) {  
  20.             ……  
  21.         } else {  
  22.             /* 
  23.              * Pass the remaining arguments to SystemServer. 
  24.              */  
  25.             RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs);  
  26.         }  
  27. }  

继续来看RuntimeInit.zygoteInit:

[cpp] view plaincopy在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.   
  5.         redirectLogStreams();  
  6.         // 做一些常规初始化  
  7.         commonInit();  
  8.   
  9.         // native层的初始化  
  10.         nativeZygoteInit();  
  11.   
  12.         // 调用应用程序java层的main 方法  
  13.         applicationInit(targetSdkVersion, argv);  
  14. }  

Native层的初始化 – nativeZygoteInit

对应native层函数如下:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz)  
  2. {  
  3.     gCurRuntime->onZygoteInit();  
  4. }  

这里的gCurRuntime是什么?还记得app_process(zygote)的main函数嘛?

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. int main(…)  
  2. {  
  3.     …  
  4.     AppRuntime runtime; // 其实就是这个  
  5.     …  
  6. }  

AppRuntime是继承自AndroidRuntime的类:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. static AndroidRuntime* gCurRuntime = NULL;  // AndroidRuntime类的全局变量  
  2. AndroidRuntime::AndroidRuntime() :  
  3.         mExitWithoutCleanup(false)  
  4. {  
  5.     …….  
  6. assert(gCurRuntime == NULL);  
  7. gCurRuntime = this;     // 开始赋值  
  8. }  

因为system_server是zygote通过fork分裂出来的,所以system_server进程本身也拥有gCurRuntime这个对象。再回过头来看onZygoteInit的处理,AppRuntime中重写了onZygoteInit函数:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. virtual void onZygoteInit()  
  2. {  
  3. ……  
  4.     sp<ProcessState> proc = ProcessState::self();  
  5.     proc->startThreadPool(); // 启动一个线程,用于Binder通信。  
  6. }  

上述内容和Binder通信相关,我们现在还不必深究。简而言之,system_server调用完nativeZygoteInit之后,便于Binder通信系统建立了联系,这样system_server就能使用Binder通信了。


进入java层– applicationInit

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. private static void applicationInit(int targetSdkVersion, String[] argv)  
  2.             throws ZygoteInit.MethodAndArgsCaller {  
  3.         nativeSetExitWithoutCleanup(true);  
  4.   
  5.         VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);  
  6.         VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);  
  7.   
  8.         final Arguments args;  
  9.         try {  
  10.             args = new Arguments(argv);  
  11.         } catch (IllegalArgumentException ex) {  
  12.             Slog.e(TAG, ex.getMessage());  
  13.             return;  
  14.         }  
  15.   
  16.         // Remaining arguments are passed to the start class's static main  
  17.         invokeStaticMain(args.startClass, args.startArgs);  
  18. }  

VMRuntime进行简单的初始化之后,invokeStaticMain函数就开始进入system_server的java层main函数中开始执行。其中,根据前面硬编码的启动参数可知,system_server java层的类为com.android.server.SystemServer。

invokeStaticMain函数的调用很有意思,我们接着往下看:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. private static void invokeStaticMain(String className, String[] argv)  
  2.             throws ZygoteInit.MethodAndArgsCaller {  
  3.         Class<?> cl;  
  4.   
  5.         try {  
  6.             // 加载com.android.server.SystemServer这个类  
  7.             cl = Class.forName(className);  
  8.         } catch (ClassNotFoundException ex) {  
  9.             throw new RuntimeException(  
  10.                     "Missing class when invoking static main " + className,  
  11.                     ex);  
  12.         }  
  13.   
  14.         Method m;  
  15.         try {  
  16.             // 获得main方法  
  17.             m = cl.getMethod("main"new Class[] { String[].class });  
  18.         } catch (NoSuchMethodException ex) {  
  19.             throw new RuntimeException(  
  20.                     "Missing static main on " + className, ex);  
  21.         } catch (SecurityException ex) {  
  22.             throw new RuntimeException(  
  23.                     "Problem getting static main on " + className, ex);  
  24.         }  
  25.   
  26.         int modifiers = m.getModifiers();  
  27.         // 判断main函数的类型  
  28.         if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {  
  29.             throw new RuntimeException(  
  30.                     "Main method is not public and static on " + className);  
  31.         }  
  32.   
  33.         /* 
  34.          * This throw gets caught in ZygoteInit.main(), which responds 
  35.          * by invoking the exception's run() method. This arrangement 
  36.          * clears up all the stack frames that were required in setting 
  37.          * up the process. 
  38.          */  
  39.         throw new ZygoteInit.MethodAndArgsCaller(m, argv);  
  40. }  

ZygoteInit.MethodAndArgsCaller是一个继承自Exception的类,invokeStaticMain最后并没有直接调用com.android.server.SystemServer的main 方法,而是抛出了一个ZygoteInit.MethodAndArgsCalle类型的异常。

那么这个异常是在哪里被捕获的呢?上述代码的注释其实也已经解释的很清楚了,在ZygoteInit.main()中,我们回过头来看看:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1.     public static void main(String argv[]) {  
  2.         try {  
  3.             ……  
  4.   
  5.             if (argv[1].equals("start-system-server")) {  
  6.                 startSystemServer();  
  7.             }   
  8.             ……  
  9.         } catch (MethodAndArgsCaller caller) {  
  10.             caller.run();  
  11.         } catch (RuntimeException ex) {  
  12.             ……  
  13.         }  
  14. }  

main函数中通过try-catch最终捕获到了MethodAndArgsCaller异常,并通过异常类的run函数来处理。

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static class MethodAndArgsCaller extends Exception  
  2.             implements Runnable {  
  3.         /** method to call */  
  4.         private final Method mMethod;  
  5.   
  6.         /** argument array */  
  7.         private final String[] mArgs;  
  8.   
  9.         // 构造函数将参数保存下来      
  10. public MethodAndArgsCaller(Method method, String[] args) {  
  11.             mMethod = method;  
  12.             mArgs = args;  
  13.         }  
  14.           
  15.         // run函数调用main函数  
  16.         public void run() {  
  17.             try {  
  18.                 mMethod.invoke(null, new Object[] { mArgs });  
  19.             } catch (IllegalAccessException ex) {  
  20.                 throw new RuntimeException(ex);  
  21.             } catch (InvocationTargetException ex) {  
  22.                 ……  
  23.             }  
  24.         }  
  25.     }  
  26. }  

至此,system_server进入java世界开始执行。


system_server的真面目

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static void main(String[] args) {  
  2.         ……  
  3.         System.loadLibrary("android_servers");  
  4.         Slog.i(TAG, "Entered the Android system server!");  
  5.   
  6.         // Initialize native services.  
  7.         nativeInit();  
  8.   
  9.         // This used to be its own separate thread, but now it is  
  10.         // just the loop we run on the main thread.  
  11.         ServerThread thr = new ServerThread();  
  12.         thr.initAndLoop();  
  13. }  

函数首先加载了libandroid_servers.so文件,之后调用nativeInit初始化,最后initAndLoop启动各种系统服务。


Native服务初始化 - nativeInit

nativeInit是一个native函数,代码在frameworks\base\services\jni\com_android_server_SystemServer.cpp中:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz) {  
  2.     char propBuf[PROPERTY_VALUE_MAX];  
  3.     property_get("system_init.startsensorservice", propBuf, "1");  
  4.     if (strcmp(propBuf, "1") == 0) {  
  5.         // Start the sensor service  
  6.         SensorService::instantiate();  
  7.     }  
  8. }  

这个函数主要是根据属性配置文件来确定是否需要初始化Sensor Service,这里就不多介绍了。


Java层服务初始化 – ServerThread类

启动一个ServerThread线程,其主要用来初始化Java层的各种服务,并且通过Binder接收各种服务消息。我们直接来看initAndLoop函数。这个函数比较长,大致看看它都干了些什么:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public void initAndLoop() {  
  2.         // 初始化Lopper  
  3.         Looper.prepareMainLooper();  
  4.       
  5.         // 设置线程优先级  
  6.         android.os.Process.setThreadPriority(  
  7.                 android.os.Process.THREAD_PRIORITY_FOREGROUND);  
  8.   
  9.         BinderInternal.disableBackgroundScheduling(true);  
  10.         android.os.Process.setCanSelfBackground(false);  
  11.   
  12.         ......  
  13.   
  14.         // bootstrap services  
  15.         boolean onlyCore = false;  
  16.         boolean firstBoot = false;  
  17.         try {  
  18.             .....  
  19.   
  20.             Slog.i(TAG, "Power Manager");  
  21.             power = new PowerManagerService();  
  22.             ServiceManager.addService(Context.POWER_SERVICE, power);  
  23.   
  24.             Slog.i(TAG, "Activity Manager");  
  25.             context = ActivityManagerService.main(factoryTest);  
  26.         } catch (RuntimeException e) {  
  27.             Slog.e("System""******************************************");  
  28.             Slog.e("System""************ Failure starting bootstrap service", e);  
  29.         }  
  30.   
  31.         boolean disableStorage = SystemProperties.getBoolean("config.disable_storage"false);  
  32.         boolean disableMedia = SystemProperties.getBoolean("config.disable_media"false);  
  33.         boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth"false);  
  34.         boolean disableTelephony = SystemProperties.getBoolean("config.disable_telephony"false);  
  35.         boolean disableLocation = SystemProperties.getBoolean("config.disable_location"false);  
  36.         boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui"false);  
  37.         boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore"false);  
  38.         boolean disableNetwork = SystemProperties.getBoolean("config.disable_network"false);  
  39.   
  40.         try {  
  41.             Slog.i(TAG, "Display Manager");  
  42.             display = new DisplayManagerService(context, wmHandler);  
  43.             ServiceManager.addService(Context.DISPLAY_SERVICE, display, true);  
  44.   
  45.             Slog.i(TAG, "Telephony Registry");  
  46.             telephonyRegistry = new TelephonyRegistry(context);  
  47.             ServiceManager.addService("telephony.registry", telephonyRegistry);  
  48.   
  49.             Slog.i(TAG, "Scheduling Policy");  
  50.             ServiceManager.addService("scheduling_policy"new SchedulingPolicyService());  
  51.   
  52.             AttributeCache.init(context);  
  53.   
  54.             if (!display.waitForDefaultDisplay()) {  
  55.                 reportWtf("Timeout waiting for default display to be initialized.",  
  56.                         new Throwable());  
  57.             }  
  58.   
  59.             Slog.i(TAG, "Package Manager");  
  60.             // Only run "core" apps if we're encrypting the device.  
  61.             String cryptState = SystemProperties.get("vold.decrypt");  
  62.             if (ENCRYPTING_STATE.equals(cryptState)) {  
  63.                 Slog.w(TAG, "Detected encryption in progress - only parsing core apps");  
  64.                 onlyCore = true;  
  65.             } else if (ENCRYPTED_STATE.equals(cryptState)) {  
  66.                 Slog.w(TAG, "Device encrypted - only parsing core apps");  
  67.                 onlyCore = true;  
  68.             }  
  69.   
  70.             pm = PackageManagerService.main(context, installer,  
  71.                     factoryTest != SystemServer.FACTORY_TEST_OFF,  
  72.                     onlyCore);  
  73.             try {  
  74.                 firstBoot = pm.isFirstBoot();  
  75.             } catch (RemoteException e) {  
  76.             }  
  77.   
  78.             ActivityManagerService.setSystemProcess();  
  79.   
  80.             Slog.i(TAG, "Entropy Mixer");  
  81.             ServiceManager.addService("entropy"new EntropyMixer(context));  
  82.   
  83.             Slog.i(TAG, "User Service");  
  84.             ServiceManager.addService(Context.USER_SERVICE,  
  85.                     UserManagerService.getInstance());  
  86.   
  87.             mContentResolver = context.getContentResolver();  
  88.   
  89.             // The AccountManager must come before the ContentService  
  90.             try {  
  91.                 // TODO: seems like this should be disable-able, but req'd by ContentService  
  92.                 Slog.i(TAG, "Account Manager");  
  93.                 accountManager = new AccountManagerService(context);  
  94.                 ServiceManager.addService(Context.ACCOUNT_SERVICE, accountManager);  
  95.             } catch (Throwable e) {  
  96.                 Slog.e(TAG, "Failure starting Account Manager", e);  
  97.             }  
  98.   
  99.             Slog.i(TAG, "Content Manager");  
  100.             contentService = ContentService.main(context,  
  101.                     factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);  
  102.   
  103.             Slog.i(TAG, "System Content Providers");  
  104.             ActivityManagerService.installSystemProviders();  
  105.   
  106.             Slog.i(TAG, "Lights Service");  
  107.             lights = new LightsService(context);  
  108.   
  109.             Slog.i(TAG, "Battery Service");  
  110.             battery = new BatteryService(context, lights);  
  111.             ServiceManager.addService("battery", battery);  
  112.   
  113.             Slog.i(TAG, "Vibrator Service");  
  114.             vibrator = new VibratorService(context);  
  115.             ServiceManager.addService("vibrator", vibrator);  
  116.   
  117.             Slog.i(TAG, "Consumer IR Service");  
  118.             consumerIr = new ConsumerIrService(context);  
  119.             ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);  
  120.   
  121.             // only initialize the power service after we have started the  
  122.             // lights service, content providers and the battery service.  
  123.             power.init(context, lights, ActivityManagerService.self(), battery,  
  124.                     BatteryStatsService.getService(),  
  125.                     ActivityManagerService.self().getAppOpsService(), display);  
  126.   
  127.             Slog.i(TAG, "Alarm Manager");  
  128.             alarm = new AlarmManagerService(context);  
  129.             ServiceManager.addService(Context.ALARM_SERVICE, alarm);  
  130.   
  131.             Slog.i(TAG, "Init Watchdog");  
  132.             Watchdog.getInstance().init(context, battery, power, alarm,  
  133.                     ActivityManagerService.self());  
  134.             Watchdog.getInstance().addThread(wmHandler, "WindowManager thread");  
  135.   
  136.             Slog.i(TAG, "Input Manager");  
  137.             inputManager = new InputManagerService(context, wmHandler);  
  138.   
  139.             Slog.i(TAG, "Window Manager");  
  140.             wm = WindowManagerService.main(context, power, display, inputManager,  
  141.                     wmHandler, factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL,  
  142.                     !firstBoot, onlyCore);  
  143.             ServiceManager.addService(Context.WINDOW_SERVICE, wm);  
  144.             ServiceManager.addService(Context.INPUT_SERVICE, inputManager);  
  145.   
  146.             ActivityManagerService.self().setWindowManager(wm);  
  147.   
  148.             inputManager.setWindowManagerCallbacks(wm.getInputMonitor());  
  149.             inputManager.start();  
  150.   
  151.             display.setWindowManager(wm);  
  152.             display.setInputManager(inputManager);  
  153.     }  
  154.   
  155.     ......  
  156.   
  157.         Looper.loop();  
  158.         Slog.d(TAG, "System ServerThread is exiting!");  
  159. }  

以上代码省略了很多,大致就是ServerThread线程启动各种系统服务,最后通过Looper.loop()来进行消息循环,然后处理消息。


system_server总结


0 0
原创粉丝点击