SystemServer

概述

  • SystemServer的进程名实际上叫做“system_server”,通常简称为SS。
  • SS是由Zygote通过Zygote.forkSystemServer函数fork诞生出来的
  • 与Zygote生死与共.SS诞生后,便和生父Zygote分道扬镳,它有了自己的历史使命

诞生

image.png
  • ZygoteInit.java frameworks/base/core/com/android/internal/os/ZygoteInit.java
// frameworks/base/core/com/android/internal/os/Zygote.java
pid = Zygote.forkSystemServer(
                    parsedArgs.uid, parsedArgs.gid,
                    parsedArgs.gids,
                    parsedArgs.debugFlags,
                    null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }
//
/* dalvik/vm/native/dalvik_system_Zygote
 *
 * native public static int nativeForkSystemServer(int uid, int gid,
 *     int[] gids, int debugFlags, int[][] rlimits,
 *     long permittedCapabilities, long effectiveCapabilities);
 */
static void Dalvik_dalvik_system_Zygote_forkSystemServer(
        const u4* args, JValue* pResult)
{
    pid_t pid;
    // 根据参数fork一个子进程
    pid = forkAndSpecializeCommon(args, true);

    /* The zygote process checks whether the child process has died or not. */
    if (pid > 0) {
        int status;

        ALOGI("System server process %d has been created", pid);
        gDvm.systemServerPid = pid;  //保存system_server的进程id
        /* There is a slight window that the system server process has crashed
         * but it went unnoticed because we haven't published its pid yet. So
         * we recheck here just to make sure that all is well.
         */
         //函数推出前需要却确认刚创建的子进程是否退出
        if (waitpid(pid, &status, WNOHANG) == pid) {
            ALOGE("System server process %d has died. Restarting Zygote!", pid);
            //如果system_server 退出,    zygote 自杀
            kill(getpid(), SIGKILL);
        }
    }
    RETURN_INT(pid);
}
  • 由此可见,作为Zygote的嫡长子,竟然到了影响到Zygote

使命

image.png
  • SS 调用 handleSystemServerProcess 来承担自己的责任
  • SS 调用 zygoteInitNative后,在 onZygote中,执行了 proc->startThreadPool(); ,这一句会启动一个线程,用于Binder线。即,将与Binder通信系统建立联系,这样就能够使用Binder。
  • invokeStaticMain 会抛出一个异常,会在ZygoteInit的main方法中被截获。而最后在caller.run() 方法中,会执行 mMethod.invoke(null, new Object[] { mArgs }); ,这个mMethod为 com.android.server.SystemServer 的main函数被调用。

真面目

  • ZygoteInit分裂产生的SS,其实就是为了调用com.android.server.SystemServer的main函数。

     public static void main(String[] args) {
    
            /*
             * In case the runtime switched since last boot (such as when
             * the old runtime was removed in an OTA), set the system
             * property so that it is in sync. We can't do this in
             * libnativehelper's JniInvocation::Init code where we already
             * had to fallback to a different runtime because it is
             * running as root and we need to be the system user to set
             * the property. http://b/11463182
             */
            SystemProperties.set("persist.sys.dalvik.vm.lib",
                                 VMRuntime.getRuntime().vmLibrary());
    
            if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
                // If a device's clock is before 1970 (before 0), a lot of
                // APIs crash dealing with negative numbers, notably
                // java.io.File#setLastModified, so instead we fake it and
                // hope that time from cell towers or NTP fixes it
                // shortly.
                Slog.w(TAG, "System clock is before 1970; setting to 1970.");
                SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
            }
    
            if (SamplingProfilerIntegration.isEnabled()) {
                SamplingProfilerIntegration.start();
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        SamplingProfilerIntegration.writeSnapshot("system_server", null);
                    }
                }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
            }
    
            // Mmmmmm... more memory!
            dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
    
            // The system server has to run all of the time, so it needs to be
            // as efficient as possible with its memory usage.
            VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
    
            Environment.setUserRequired(true);
    
            System.loadLibrary("android_servers");  //加载库
    
            Slog.i(TAG, "Entered the Android system server!");
    
            // Initialize native services.
            nativeInit();  //在 /base/services/jni/com_android_server_SystemServer.cpp
    
            // This used to be its own separate thread, but now it is
            // just the loop we run on the main thread.
            ServerThread thr = new ServerThread();
            thr.initAndLoop();
        }
    
    //  frameworks/base/services/jni/com_android_server_SystemServer.cpp
    static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz) {
        char propBuf[PROPERTY_VALUE_MAX];
        property_get("system_init.startsensorservice", propBuf, "1");
        if (strcmp(propBuf, "1") == 0) {
            // Start the sensor service
            SensorService::instantiate();
        }
    }
    
    
  • 没看懂这波操作

zygote 分裂

  • zygote 分裂出 system_server 之后,通过 runSelectLoopMode 等待并处理来自客户的消息
ActivityManagerService 发送请求
image.png
  • ActivityManagerService.java /framewroks/base/services/java/com.android.services/am/ActivityManangerService.java
  • Process /frameworks/base/core/java/android/os/Prcoess.java
  • zygoteSendArgsAndGetResult

    • openZygoteSocketIfNeeded
    • 把请求的参数发到 Zygote
  • openZygoteSocketIfNeeded

            try {
                    sZygoteSocket = new LocalSocket();
                    // 链接 Zygote
                    sZygoteSocket.connect(new LocalSocketAddress(ZYGOTE_SOCKET, 
                            LocalSocketAddress.Namespace.RESERVED));
                    sZygoteInputStream
                            = new DataInputStream(sZygoteSocket.getInputStream());
                    sZygoteWriter =
                        new BufferedWriter(
                                new OutputStreamWriter(
                                        sZygoteSocket.getOutputStream()),
                                256);
                    Log.i("Zygote", "Process: zygote socket opened");
                    sPreviousZygoteOpenFailed = false;
            ......
            }
    
  • ActicityManagerService 终于向 zygote 发送请求了。

    • 请求的参数中有一个字符串,它的值是 "android.app.ActicityThread"
响应请求
  • 请求之后,会回到 ZygoteInit 之中
image.png
  • ZygoteConnection.java frameworks/base/core/com/android/internal/os/ZygoteConnection.java
  if (parsedArgs.runtimeInit) {
            if (parsedArgs.invokeWith != null) {
                WrapperInit.execApplication(parsedArgs.invokeWith,
                        parsedArgs.niceName, parsedArgs.targetSdkVersion,
                        pipeFd, parsedArgs.remainingArgs);
            } else {
                //此时,会调用这里
                RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion,
                        parsedArgs.remainingArgs);
            }
        } else {
            ......
                try {
                    ZygoteInit.invokeStaticMain(cloader, className, mainArgs);
                } catch (RuntimeException ex) {
                    logAndPrintError(newStderr, "Error starting.", ex);
                }
            }
        }
    }
  • 而 RuntimeInit.zygoteInit 方法中,nativeZygoteInit这个jni函数,最终实现的是 proc->startThreadPool() 即:建立了Binder服务。

你可能感兴趣的:(SystemServer)