Jimmy Chen

A Programmer

(原创)Android SystemServer分析

一.Zygote到SystemServer

  SystemServer是由Zygote fork生成的,进程名为system_server,这个进程包含里framework中的核心服务,在Zygote的分析中有提到,SystemServer是在zygote中通过startSystemServer来调用起来

1.1 ZygoteInit.java中的startSystemServer函数

private static boolean startSystemServer(String abiList, String socketName)
        throws MethodAndArgsCaller, RuntimeException {
    …………..
    /* Hardcoded command line to start the system server */
    // 启动参数设置
    String args[] = {
        "--setuid=1000",
        "--setgid=1000",
        "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007",
        "--capabilities=" + capabilities + "," + capabilities,
        "--nice-name=system_server",
        "--runtime-args",
        "com.android.server.SystemServer",
    };
    ZygoteConnection.Arguments parsedArgs = null;

    int pid;

    try {
        // 解析参数,将上面的字符串数据转换成Arguments对象
        parsedArgs = new ZygoteConnection.Arguments(args);
        ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
        ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

        /* Request to fork the system server process */
        // fork一个子进程,子进程就是system_server进程
        pid = Zygote.forkSystemServer(
                parsedArgs.uid, parsedArgs.gid,
                parsedArgs.gids,
                parsedArgs.debugFlags,
                null,
                parsedArgs.permittedCapabilities,
                parsedArgs.effectiveCapabilities);
    } catch (IllegalArgumentException ex) {
        throw new RuntimeException(ex);
    }

    /* For child process */
    // ford返回值等于0,表明是子进程即system_server所在分支代码
    if (pid == 0) {
        if (hasSecondZygote(abiList)) {
            waitForSecondaryZygote(socketName);
        }

        // system_server进程所做的工作,在这里会启动各种支撑系统运行的System server
        handleSystemServerProcess(parsedArgs);
    }

    return true;
}

1.2 Zygote.java中的forSystemServer函数

public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,
        int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
    VM_HOOKS.preFork();
    int pid = nativeForkSystemServer(
            uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
    // Enable tracing as soon as we enter the system_server.
    if (pid == 0) {
        Trace.setTracingEnabled(true);
    }
    VM_HOOKS.postForkCommon();
    return pid;
}

  nativeForkSystemServer会通过JNI调用com_android_internal_os_Zygote.cpp中的com_
android_internal_os_Zygote_nativeForkSystemServer方法。

1.3 Com_android_internal_os_Zygote.cpp中com_internal_os_Zygote_nativeForkSystemServer方法

static jint com_android_internal_os_Zygote_nativeForkSystemServer(
        JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
        jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
        jlong effectiveCapabilities) {
  // 下面的调用会fork一个子进程
  pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
                                      debug_flags, rlimits,
                                      permittedCapabilities, effectiveCapabilities,
                                      MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
                                      NULL, NULL);
  if (pid > 0) {
      // pid>0 代表在Zygote进程内,下面检测system_server进程是否已经创建
      // The zygote process checks whether the child process has died or not.
      ALOGI("System server process %d has been created", pid);
      gSystemServerPid = pid;
      // 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.
      int status;
      // 等待子进程退出,WNOHANG表示非阻塞
      if (waitpid(pid, &status, WNOHANG) == pid) {
          // 如果system_server刚刚创建就crash,重启zygote
          ALOGE("System server process %d has died. Restarting Zygote!", pid);
          RuntimeAbort(env);
      }
  }
  return pid;
}

  当system_server进程创建失败时,将会重启zygote进程。这里需要注意,对于Android 5.0以上系统,有两个zygote进程,分别是zygote、zygote64两个进程,system_server的父进程,一般来说64位系统其父进程是zygote64进程。

  1. 当kill system_server进程后,只重启zygote64和system_server,不重启zygote;
  2. 当kill zygote64进程后,只重启zygote64和system_server,也不重启zygote;
  3. 当kill zygote进程,则重启zygote、zygote64以及system_server。

1.4 com_android_internal_os_Zygote.cpp中ForkAndSpecializeCommon函数

  这个函数有点复杂,设置处理信号这边大家还是看原生注释吧,有些地方我这边也不是看得特别明白。

// Utility routine to fork zygote and specialize the child process.
static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
                                     jint debug_flags, jobjectArray javaRlimits,
                                     jlong permittedCapabilities, jlong effectiveCapabilities,
                                     jint mount_external,
                                     jstring java_se_info, jstring java_se_name,
                                     bool is_system_server, jintArray fdsToClose,
                                     jstring instructionSet, jstring dataDir) {
  // 设置子进程的signal信号处理函数
  SetSigChldHandler();

  sigset_t sigchld;
  sigemptyset(&sigchld);
  sigaddset(&sigchld, SIGCHLD);

  // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
  // log, which would result in the logging FDs we close being reopened.
  // This would cause failures because the FDs are not whitelisted.
  //
  // Note that the zygote process is single threaded at this point.
  // 大概意思是暂时屏蔽SIGCHLD信号,不然SIGCHLD会产生log,而被我们关闭掉的
  // logging文件描述符会对这个信号进行相应,所以会报错
  if (sigprocmask(SIG_BLOCK, &sigchld, NULL) == -1) {
    ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno));
    RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_BLOCK, { SIGCHLD }) failed.");
  }

  // Close any logging related FDs before we start evaluating the list of
  // file descriptors.
  __android_log_close();

  // If this is the first fork for this zygote, create the open FD table.
  // If it isn't, we just need to check whether the list of open files has
  // changed (and it shouldn't in the normal case).
  if (gOpenFdTable == NULL) {
    gOpenFdTable = FileDescriptorTable::Create();
    if (gOpenFdTable == NULL) {
      RuntimeAbort(env, __LINE__, "Unable to construct file descriptor table.");
    }
  } else if (!gOpenFdTable->Restat()) {
    RuntimeAbort(env, __LINE__, "Unable to restat file descriptor table.");
  }

  // Linux fork调用,创建子进程
  pid_t pid = fork();

  if (pid == 0) {
    // The child process.
    gMallocLeakZygoteChild = 1;

    // Clean up any descriptors which must be closed immediately
    // 清除一部分文件描述符
    DetachDescriptors(env, fdsToClose);

    // Re-open all remaining open file descriptors so that they aren't shared
    // with the zygote across a fork.
    if (!gOpenFdTable->ReopenOrDetach()) {
      RuntimeAbort(env, __LINE__, "Unable to reopen whitelisted descriptors.");
    }

    if (sigprocmask(SIG_UNBLOCK, &sigchld, NULL) == -1) {
      ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno));
      RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_UNBLOCK, { SIGCHLD }) failed.");
    }

    // Keep capabilities across UID change, unless we're staying root.
    // 非root,禁止动态改变进程权限
    if (uid != 0) {
      EnableKeepCapabilities(env);
    }

    // 取消进程已有的Capabilities权限
    DropCapabilitiesBoundingSet(env);

    bool use_native_bridge = !is_system_server && (instructionSet != NULL)
        && android::NativeBridgeAvailable();
    if (use_native_bridge) {
      ScopedUtfChars isa_string(env, instructionSet);
      use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
    }
    if (use_native_bridge && dataDir == NULL) {
      // dataDir should never be null if we need to use a native bridge.
      // In general, dataDir will never be null for normal applications. It can only happen in
      // special cases (for isolated processes which are not associated with any app). These are
      // launched by the framework and should not be emulated anyway.
      use_native_bridge = false;
      ALOGW("Native bridge will not be used because dataDir == NULL.");
    }

    if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) {
      ALOGW("Failed to mount emulated storage: %s", strerror(errno));
      if (errno == ENOTCONN || errno == EROFS) {
        // When device is actively encrypting, we get ENOTCONN here
        // since FUSE was mounted before the framework restarted.
        // When encrypted device is booting, we get EROFS since
        // FUSE hasn't been created yet by init.
        // In either case, continue without external storage.
      } else {
        ALOGE("Cannot continue without emulated storage");
        RuntimeAbort(env);
      }
    }

    if (!is_system_server) {
        // 对于非system_server,创建进程组
        int rc = createProcessGroup(uid, getpid());
        if (rc != 0) {
            if (rc == -EROFS) {
                ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
            } else {
                ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
            }
        }
    }

    // 设置组代码
    SetGids(env, javaGids);

    // 设置资源限制
    SetRLimits(env, javaRlimits);

    if (use_native_bridge) {
      ScopedUtfChars isa_string(env, instructionSet);
      ScopedUtfChars data_dir(env, dataDir);
      android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
    }

    // 设置真实的、有效的和保存过的组ID
    int rc = setresgid(gid, gid, gid);
    if (rc == -1) {
      ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
      RuntimeAbort(env);
    }

    // 设置真实的、有效的和保存过的用户ID
    rc = setresuid(uid, uid, uid);
    if (rc == -1) {
      ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
      RuntimeAbort(env);
    }

    if (NeedsNoRandomizeWorkaround()) {
        // Work around ARM kernel ASLR lossage (http://b/5817320).
        int old_personality = personality(0xffffffff);
        int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
        if (new_personality == -1) {
            ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
        }
    }

    // 设置新的capabilities权限
    SetCapabilities(env, permittedCapabilities, effectiveCapabilities);

    // 设置调度策略
    SetSchedulerPolicy(env);

    const char* se_info_c_str = NULL;
    ScopedUtfChars* se_info = NULL;
    if (java_se_info != NULL) {
        se_info = new ScopedUtfChars(env, java_se_info);
        se_info_c_str = se_info->c_str();
        if (se_info_c_str == NULL) {
          ALOGE("se_info_c_str == NULL");
          RuntimeAbort(env);
        }
    }
    const char* se_name_c_str = NULL;
    ScopedUtfChars* se_name = NULL;
    if (java_se_name != NULL) {
        se_name = new ScopedUtfChars(env, java_se_name);
        se_name_c_str = se_name->c_str();
        if (se_name_c_str == NULL) {
          ALOGE("se_name_c_str == NULL");
          RuntimeAbort(env);
        }
    }
    // 设置selinux domain上下文
    rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
    if (rc == -1) {
      ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
            is_system_server, se_info_c_str, se_name_c_str);
      RuntimeAbort(env);
    }

    // Make it easier to debug audit logs by setting the main thread's name to the
    // nice name rather than "app_process".
    if (se_info_c_str == NULL && is_system_server) {
      se_name_c_str = "system_server";
    }
    if (se_info_c_str != NULL) {
      SetThreadName(se_name_c_str);
    }

    delete se_info;
    delete se_name;

    // 将子进程system_server的SIGCHLD信号的处理函数修改回系统默认函数
    UnsetSigChldHandler();

    // JNI调,相当于zygote.callPostForkChildHooks()
    env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
                              is_system_server ? NULL : instructionSet);
    if (env->ExceptionCheck()) {
      ALOGE("Error calling post fork hooks.");
      RuntimeAbort(env);
    }
  } else if (pid > 0) {
    // 父进程中取消上面被屏蔽的SIGCHLD信号处理
    // the parent process

    // We blocked SIGCHLD prior to a fork, we unblock it here.
    if (sigprocmask(SIG_UNBLOCK, &sigchld, NULL) == -1) {
      ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno));
      RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_UNBLOCK, { SIGCHLD }) failed.");
    }
  }
  return pid;
}

  至此,fork的工作就基本做完了,剩下的就是在handleSystemServerProcess中对SystemServer的剩余工作进行处理了。

1.5 ZygoteInit.java中的handleSystemServerProcess函数

/**
 * Finish remaining work for the newly forked system server process.
 */
private static void handleSystemServerProcess(
        ZygoteConnection.Arguments parsedArgs)
        throws ZygoteInit.MethodAndArgsCaller {

    // 关闭从父进程Zygote中继承得来的sServersocket
    closeServerSocket();

    // set umask to 0077 so new files and directories will default to owner-only permissions.
    Os.umask(S_IRWXG | S_IRWXO);

    // 设置进程名为system_server
    if (parsedArgs.niceName != null) {
        Process.setArgV0(parsedArgs.niceName);
    }

    // SYSTEMSERVERCLASSPATH=/system/framework/services.jar:/system/framework/ethernet-service.jar:/system/framework/wifi-service.jar
    final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
    if (systemServerClasspath != null) {
        // 进行dexopt优化
        performSystemServerDexOpt(systemServerClasspath);
    }

    // system_server的invokeWith为null
    if (parsedArgs.invokeWith != null) {
        String[] args = parsedArgs.remainingArgs;
        // If we have a non-null system server class path, we'll have to duplicate the
        // existing arguments and append the classpath to it. ART will handle the classpath
        // correctly when we exec a new process.
        if (systemServerClasspath != null) {
            String[] amendedArgs = new String[args.length + 2];
            amendedArgs[0] = "-cp";
            amendedArgs[1] = systemServerClasspath;
            System.arraycopy(parsedArgs.remainingArgs, 0, amendedArgs, 2, parsedArgs.remainingArgs.length);
        }

        // 启动应用程序
        WrapperInit.execApplication(parsedArgs.invokeWith,
                parsedArgs.niceName, parsedArgs.targetSdkVersion,
                VMRuntime.getCurrentInstructionSet(), null, args);
    } else {
        // system_server走该分支
        ClassLoader cl = null;
        if (systemServerClasspath != null) {
            // 创建类加载器
            cl = new PathClassLoader(systemServerClasspath, ClassLoader.getSystemClassLoader());
            // 设置当前进程即system_server的类加载器
            Thread.currentThread().setContextClassLoader(cl);
        }

        /*
         * Pass the remaining arguments to SystemServer.
         */
        // 最后调用zygoteinit
        RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
    }

    /* should never reach here */
}

1.6 ZygoteInit.java中的performSystemServerDexOpt函数

/**
 * Performs dex-opt on the elements of {@code classPath}, if needed. We
 * choose the instruction set of the current runtime.
 */
private static void performSystemServerDexOpt(String classPath) {
    final String[] classPathElements = classPath.split(":");
    // 创建一个InstallerConnection对象
    final InstallerConnection installer = new InstallerConnection();
    // 等待,直到与installed服务端连通为止
    installer.waitForConnection();
    final String instructionSet = VMRuntime.getRuntime().vmInstructionSet();

    try {
        for (String classPathElement : classPathElements) {
            final int dexoptNeeded = DexFile.getDexOptNeeded(
                    classPathElement, "*", instructionSet, false /* defer */);
            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
                // 以system身份,执行dex优化
                installer.dexopt(classPathElement, Process.SYSTEM_UID, false,
                        instructionSet, dexoptNeeded);
            }
        }
    } catch (IOException ioe) {
        throw new RuntimeException("Error starting system_server", ioe);
    } finally {
        // 断开与installed的socket连接
        installer.disconnect();
    }
}

1.7 RuntimeInit.java中的ZygoteInit函数

public static final void zygoteInit(int targetSdkVersion, String[] argv) throws MethodAndArgsCaller {
    redirectLogStreams();    // 重定向Log输出
    commonInit();            // 通用初始化
    nativeZygoteInit();      // Zygote初始化
    applicationInit(targetSdkVersion, argv);  // 应用初始化
}

1.8 RuntimeInit.java中的commonInit函数

private static final void commonInit() {
    // 设置当前线程的未捕获异常处设置为默认处理方法
    Thread.setDefaultUncaughtExceptionHandler(new RuntimeInit.UncaughtHandler(null));
    // 设置时区
    TimezoneGetter.setInstance(new TimezoneGetter() {
        public String getId() {
            return SystemProperties.get("persist.sys.timezone");
        }
    });
    TimeZone.setDefault((TimeZone)null);
    // 重置Log设置
    LogManager.getLogManager().reset();
    // 设置Android Log
    new AndroidConfig();
    // 获取默认的userAgent
    String userAgent = getDefaultUserAgent();
    // 获取默认的HTTP user-agent,用于HttpURLConnection连接
    System.setProperty("http.agent", userAgent);
    // 设置网络流量统计
    NetworkManagementSocketTagger.install();
    // 如果是通过模拟器启动Android,可以通过F9/F10随时追踪kernel运行情况
    String trace = SystemProperties.get("ro.kernel.android.tracing");
    if(trace.equals("1")) {
        Slog.i("AndroidRuntime", "NOTE: emulator trace profiling enabled");
        Debug.enableEmulatorTraceOutput();
    }

    initialized = true;
}

1.9 AndroidRuntime.cpp中的com_android_internal_os_RuntimeInit_nativeZygoteInit方法

static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
    gCurRuntime->onZygoteInit();
}

  onZygote的代码在app_main.cpp中,代码如下:

virtual void onZygoteInit()
{
    // 获取ProcessState对象
    sp proc = ProcessState::self();
    ALOGV("App process: starting thread pool.\n");
    // 启动线程池
    proc->startThreadPool();
}

1.10 RuntimeInit.java中的applicationInit方法

private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
        throws ZygoteInit.MethodAndArgsCaller {
    // If the application calls System.exit(), terminate the process
    // immediately without running any shutdown hooks.  It is not possible to
    // shutdown an Android application gracefully.  Among other things, the
    // Android runtime shutdown hooks close the Binder driver, which can cause
    // leftover running threads to crash before the process actually exits.
    // true代表在退出的时候不调用AppRuntime.onExit()
    nativeSetExitWithoutCleanup(true);

    // We want to be fairly aggressive about heap utilization, to avoid
    // holding on to a lot of memory that isn't needed.
    // 设置虚拟机内存堆利用率为%75
    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 exit
        return;
    }

    // The end of of the RuntimeInit event (see #zygoteInit).
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

    // Remaining arguments are passed to the start class's static main
    // 调用startClass=“com.android.server.Systemserver”的static main方法
    invokeStaticMain(args.startClass, args.startArgs, classLoader);
}

1.11 RuntimeInit.java中的invokeStaticMain方法

/**
 * Invokes a static "main(argv[]) method on class "className".
 * Converts various failing exceptions into RuntimeExceptions, with
 * the assumption that they will then cause the VM instance to exit.
 *
 * @param className Fully-qualified class name
 * @param argv Argument vector for main()
 * @param classLoader the classLoader to load {@className} with
 */
// 用于启动className指向的类的static main(argv[])方法
private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
        throws ZygoteInit.MethodAndArgsCaller {
    Class<?> cl;

    try {
        // 装载className=”com.android.server.Systemserver”类,并初始化
        cl = Class.forName(className, true, classLoader);
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException(
                "Missing class when invoking static main " + className,
                ex);
    }

    Method m;
    try {
        // 获取className=”com.android.server.Systemserver”中的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);
    }

    // 获取main方法的修饰符
    int modifiers = m.getModifiers();
    // main方法的修饰符需要是public static
    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.
     */
    // 通过抛出异常的方式,将调用返回到ZygoteInit.main函数中
    throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}

  上面的函数调用最后是通过抛出ZygoteInit.MethodAndArgsCaller异常的方法,将方法的调用栈返回到ZygoteInit.main()函数中,下面我们在重新看看ZygoteInit的main函数是怎么处理这个异常的。

1.12 ZygoteInit.java中的main函数

public static void main(String argv[]) {
      // 前面的代码在前面分析了,这里就省略不贴出来
      ………………

        /// M: Added for BOOTPROF
        addBootEvent(new String("Zygote:Preload End"));

        if (startSystemServer) {
            startSystemServer(abiList, socketName);
        }

        Log.i(TAG, "Accepting command socket connections");
        runSelectLoop(abiList);

        closeServerSocket();
    } catch (MethodAndArgsCaller caller) {
        // 在RuntimeInit.java的invokeStaticMain方法中抛出的异常在这里捕获
        // 然后调用MethodAndArgsCaller的run方法
        caller.run();
    } catch (RuntimeException ex) {
        Log.e(TAG, "Zygote died with exception", ex);
        closeServerSocket();
        throw ex;
    }
}

1.13 ZygoteInit.java中的MethodAndArgsCaller类

/**
 * Helper exception class which holds a method and arguments and
 * can call them. This is used as part of a trampoline to get rid of
 * the initial process setup stack frames.
 */
public static class MethodAndArgsCaller extends Exception
        implements Runnable {
    /** method to call */
    private final Method mMethod;

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

    public MethodAndArgsCaller(Method method, String[] args) {
        // com.android.server.SystemServer类的main方法
        mMethod = method;
        // 传给main方法的参数
        mArgs = args;
    }

    public void run() {
        try {
            // 调用com.android.server.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);
        }
    }
}

2. SystemServer的实际内容

  第一部分介绍到Zygote最后会执行com.android.server.Systemserver的main函数,那程序就会直接跳转到main函数。

2.1 SystemServer.java中的main函数

/**
 * The main entry point from zygote.
 */
public static void main(String[] args) {
    new SystemServer().run();
}

2.2 SystemServer.java中的run函数

private void run() {
    // 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.
    // 如果时间早于1970年,这里就将时间强制设置为1970年
    if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
        Slog.w(TAG, "System clock is before 1970; setting to 1970.");
        SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
    }

    // If the system has "persist.sys.language" and friends set, replace them with
    // "persist.sys.locale". Note that the default locale at this point is calculated
    // using the "-Duser.locale" command line flag. That flag is usually populated by
    // AndroidRuntime using the same set of system properties, but only the system_server
    // and system apps are allowed to set them.
    //
    // NOTE: Most changes made here will need an equivalent change to
    // core/jni/AndroidRuntime.cpp
    if (!SystemProperties.get("persist.sys.language").isEmpty()) {
        final String languageTag = Locale.getDefault().toLanguageTag();

        SystemProperties.set("persist.sys.locale", languageTag);
        SystemProperties.set("persist.sys.language", "");
        SystemProperties.set("persist.sys.country", "");
        SystemProperties.set("persist.sys.localevar", "");
    }

    // Here we go!
    Slog.i(TAG, "Entered the Android system server!");
    EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());

    /// M: BOOTPROF @{
    mMTPROF_disable = "1".equals(SystemProperties.get("ro.mtprof.disable"));
    addBootEvent(new String("Android:SysServerInit_START"));
    /// @}

    // 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.2", VMRuntime.getRuntime().vmLibrary());

    // Enable the sampling profiler.
    // 启动SampleingProfilerIntegration进行性能统计
    if (SamplingProfilerIntegration.isEnabled()) {
        SamplingProfilerIntegration.start();
        mProfilerSnapshotTimer = new Timer();
        mProfilerSnapshotTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                SamplingProfilerIntegration.writeSnapshot("system_server", null);
            }
        // SNAPSHOT_INTERVAL=60*60*1000,所以是一个小时进行一次性能统计
        // 保存的snapshot保存到/data/snapshots/system_server中
        }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
    }

    // Mmmmmm... more memory!
    // 清除虚拟机运行时内存增长上限
    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.
    // 设置虚拟机运行时内存堆利用率为80%
    VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

    // Some devices rely on runtime fingerprint generation, so make sure
    // we've defined it before booting further.
    // 确认ro.build.fingerprint属性值是否存在,如果不存在则设置该属性值
    Build.ensureFingerprintProperty();

    // Within the system server, it is an error to access Environment paths without
    // explicitly specifying a user.
    // 需要设置指定用户后才能够访问环境变量
    Environment.setUserRequired(true);

    // Ensure binder calls into the system always run at foreground priority.
// 确保binder系统调用运行在前台优先级
    BinderInternal.disableBackgroundScheduling(true);

    // Prepare the main looper thread (this thread).
    // 设置system_server的优先级为前台优先级
    android.os.Process.setThreadPriority(
            android.os.Process.THREAD_PRIORITY_FOREGROUND);
    // 禁止system_server将自身设置为后台优先级
    android.os.Process.setCanSelfBackground(false);
    // 创建主线程looper
    Looper.prepareMainLooper();

    // Initialize native services.
    // 加载android_servers.so库
    System.loadLibrary("android_servers");

    ///M:Add for low storage feature,to delete the reserver file.@{
    try {
        Runtime.getRuntime().exec("rm -r /data/piggybank");
    } catch (IOException e) {
        Slog.e(TAG, "system server init delete piggybank fail" + e);
    }
    ///@}

    // Check whether we failed to shut down last time we tried.
    // This call may not return.
    // 检查上次是否是正常关闭,该方法可能不会返回
    performPendingShutdown();

    // Initialize the system context.
    // 初始化系统上下文
    createSystemContext();

    // Create the system service manager.
    // 创建SystemServiceManager
    mSystemServiceManager = new SystemServiceManager(mSystemContext);
    // 将SystemServiceManager成员添加到本地service对象中
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

    // Start services.
    try {
        // 启动引导服务
        startBootstrapServices();
        // 启动核心服务
        startCoreServices();
        // 启动剩余的其他服务
        startOtherServices();
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);

        /// M: RecoveryManagerService  @{
        if (mRecoveryManagerService != null && ex instanceof RuntimeException) {
            mRecoveryManagerService.handleException((RuntimeException) ex, true);
        } else {
            throw ex;
        }
        /// @}
    }

    // For debug builds, log event loop stalls to dropbox for analysis.
    if (StrictMode.conditionallyEnableDebugLogging()) {
        Slog.i(TAG, "Enabled StrictMode for system server main thread.");
    }

    /// M: BOOTPROF
    addBootEvent(new String("Android:SysServerInit_END"));

    // Loop forever.
    // 进入消息处理循环
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

2.3 SystemServer.java中的performPendingShutdown函数

private void performPendingShutdown() {
    // SHUTDOWN_ACTION_PROPERTY=”sys.shutdown.requested”
    final String shutdownAction = SystemProperties.get(
            ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
    if (shutdownAction != null && shutdownAction.length() > 0) {
        boolean reboot = (shutdownAction.charAt(0) == '1');

        final String reason;
        if (shutdownAction.length() > 1) {
            reason = shutdownAction.substring(1, shutdownAction.length());
        } else {
            reason = null;
        }
        // 如果sys.shutdown.requested的值不为空,就会重启或者关机
        ShutdownThread.rebootOrShutdown(null, reboot, reason);
    }
}

2.4 SystemServer.java中的createSystemcontext函数

private void createSystemContext() {
    // 获取ActivityThread对象
    ActivityThread activityThread = ActivityThread.systemMain();
    // 创建并获取ContextImpl对象
    mSystemContext = activityThread.getSystemContext();
    // 设置系统主题    
    mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
}

2.5 SystemServer.java中的startBootstrapServices函数

/**
 * Starts the small tangle of critical services that are needed to get
 * the system off the ground.  These services have complex mutual dependencies
 * which is why we initialize them all in one place here.  Unless your service
 * is also entwined in these dependencies, it should be initialized in one of
 * the other functions.
 */
private void startBootstrapServices() {
    // Wait for installd to finish starting up so that it has a chance to
    // create critical directories such as /data/user with the appropriate
    // permissions.  We need this to complete before we initialize other services.
    // 启动Installer系统服务
    Installer installer = mSystemServiceManager.startService(Installer.class);

    /// M: MSG Logger Manager @{
    if (!IS_USER_BUILD) {
        try {
            MessageMonitorService msgMonitorService = null;
            msgMonitorService = new MessageMonitorService();
            Slog.e(TAG, "Create message monitor service successfully .");

            // Add this service to service manager
            ServiceManager.addService(Context.MESSAGE_MONITOR_SERVICE,
                    msgMonitorService.asBinder());
        } catch (Throwable e) {
            Slog.e(TAG, "Starting message monitor service exception ", e);
        }
    }
    /// MSG Logger Manager @}

    // Activity manager runs the show.
    // 启动AMS,同时设置AMS的SystemServiceManager和Installer
    mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);

    // Power manager needs to be started early because other services need it.
    // Native daemons may be watching for it to be registered so it must be ready
    // to handle incoming binder calls immediately (including being able to verify
    // the permissions for those calls).
    // 启动PowerManagerService
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

    // Now that the power manager has been started, let the activity manager
    // initialize power management features.
    // 初始化PowerManagerService
    mActivityManagerService.initPowerManagement();

    // Manages LEDs and display backlight so we need it to bring up the display.
    // 启动LightService
    mSystemServiceManager.startService(LightsService.class);

    // Display manager is needed to provide display metrics before package manager
    // starts up.
    // 启动DisplayManagerService
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

    // We need the default display before we can initialize the package manager.
    // 等待Display默认显示
    mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

    // Only run "core" apps if we're encrypting the device.
    // 当设备处于加密过程中,则只运行核心应用程序
    String cryptState = SystemProperties.get("vold.decrypt");
    if (ENCRYPTING_STATE.equals(cryptState)) {
        Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
        mOnlyCore = true;
    } else if (ENCRYPTED_STATE.equals(cryptState)) {
        Slog.w(TAG, "Device encrypted - only parsing core apps");
        mOnlyCore = true;
    }

    // Start the package manager.
    Slog.i(TAG, "Package Manager");
    // 启动PackageManagerService
    mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
            mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    // 判断手机是否是第一次启动
    mFirstBoot = mPackageManagerService.isFirstBoot();
    // 获取PakcageManager对象
    mPackageManager = mSystemContext.getPackageManager();

    Slog.i(TAG, "User Service");
    // 启动UserManagerService,并添加到ServiceManager中
    ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());

    // Initialize attribute cache used to cache resources from packages.
    // 初始化属性缓存
    AttributeCache.init(mSystemContext);

    // Set up the Application instance for the system process and get started.
    // 设置AMS
    mActivityManagerService.setSystemProcess();

    // The sensor service needs access to package manager service, app ops
    // service, and permissions service, therefore we start it after them.
    // 启动SensorService
    startSensorService();
}

2.6 SystemServer.java中的startCoreServices函数

/**
 * Starts some essential services that are not tangled up in the bootstrap process.
 */
private void startCoreServices() {
    // Tracks the battery level.  Requires LightService.
    // 启动BatteryService,用于统计电池电量信息
    mSystemServiceManager.startService(BatteryService.class);

    // Tracks application usage stats.
    // 启动UsageStatsService,用于统计应用使用情况
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
            LocalServices.getService(UsageStatsManagerInternal.class));
    // Update after UsageStatsService is available, needed before performBootDexOpt.
    mPackageManagerService.getUsageStatsIfNoPackageUsageInfo();

    // Tracks whether the updatable WebView is in a ready state and watches for update installs.
    // 启动WebViewUpdateService
    mSystemServiceManager.startService(WebViewUpdateService.class);
}

2.7 其余Service

  最后就是通过SystemServer.java中的startOtherService方法启动的service了,因为start OtherService这个方法里面启动的service比较多,例如:AudioService、CameraService、AccountService等,而且方法内容长,所以就不贴出来了,各位有兴趣可以自己去看,后续如果有分析到具体的某一个service,到时候再拿出来看就好了。

2.8 小总结

  从代码中可以看到,System_server启动service的方法主要是通过两种方式:一种是通过SystemServiceManager的startService(),这个方法主要是用来启动继承于SystemService的服务。主要过程为,首先创建serviceClass类的对象,然后将刚刚创建的serviceClass类对象添加到SystemServiceManager的成员对象mServices(是一个Arraylist),然后再调用刚创建对象的onStart方法。对于那些启动到一定阶段的服务,进入到相应阶段的Phase后,还会调用到SystemServiceManager的startBootPhase()回掉方法,这个方法会循环遍历所有向SystemServiceManager注册过的service的onBootPhase()方法;另外一种就是通过ServiceManager的addService(String name, IBinder service),该方法用于初始化继承于IBinder的服务。

  启动过程中各个Phase所代表的阶段如下:

/*
 * Boot Phases
 */
// 该阶段需要等待Display有默认显示
public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100; // maybe should be a dependency?

/**
 * After receiving this boot phase, services can obtain lock settings data.
 */
// 该阶段后服务可以获取到锁屏设置的数据了
public static final int PHASE_LOCK_SETTINGS_READY = 480;

/**
 * After receiving this boot phase, services can safely call into core system services
 * such as the PowerManager or PackageManager.
 */
// 该阶段后,服务可以安全的调用核心系统服务了,例如Power Manager和PackageManager
public static final int PHASE_SYSTEM_SERVICES_READY = 500;

/**
 * After receiving this boot phase, services can broadcast Intents.
 */
// 该阶段后,服务可以接收到广播Intents
public static final int PHASE_ACTIVITY_MANAGER_READY = 550;

/**
 * After receiving this boot phase, services can start/bind to third party apps.
 * Apps will be able to make Binder calls into services at this point.
 */
// 该阶段后,服务可以启动/绑定到第三方的app了
public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;

/**
 * After receiving this boot phase, services can allow user interaction with the device.
 * This phase occurs when boot has completed and the home application has started.
 * System services may prefer to listen to this phase rather than registering a
 * broadcast receiver for ACTION_BOOT_COMPLETED to reduce overall latency.
 */
// 该阶段后,允许用户和设备进行交互了,该阶段发生再启动完成以及home ap已经启动了,系统的服务更倾向于注册监听该广播而非ACTION_BOOT_COMPLETED
public static final int PHASE_BOOT_COMPLETED = 1000;

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d 博主赞过: