Android启动流程源码分析

114 阅读11分钟

一、Android启动流程分析

Init进程分析

1. 创建和挂载所需要的文件目录

2. 初始化和启动属性服务

3. 解析init.rc配置文件,并启动zygote进程

 

二、zygote分析

Zygote: (Zygote通过socket与其他进程通讯,主要是与systemserver系统进程通讯) 这里看下init.zygote64.rc的文件信息

service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
    class main
    priority -20
    user root
    group root readproc reserved_disk
    socket zygote stream 660 root system
    onrestart write /sys/android_power/request_state wake
    onrestart write /sys/power/state on
    onrestart restart audioserver
    onrestart restart cameraserver
    onrestart restart media
    onrestart restart netd
    onrestart restart wificond
    writepid /dev/cpuset/foreground/tasks

这里主要是执行app_process64的可执行文件,并传入一些参数"--zygote" , "--start-system-server"

app_process64的可执行文件是由对应的c代码编译过来的,这个代码的主函数在这里: 看下这个文件的main函数

//frameworks\base\cmds\app_process\app_main.cpp

int main(int argc, char* const argv[])
{
    
    //创建 AppRuntime对象;
    AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
   
    bool zygote = false;
    bool startSystemServer = false;
    bool application = false;
    String8 niceName;
    String8 className;

    ++i; 
    //解析参数
    while (i < argc) {
        const char* arg = argv[i++];
        if (strcmp(arg, "--zygote") == 0) {
            zygote = true;
            niceName = ZYGOTE_NICE_NAME;
        } else if (strcmp(arg, "--start-system-server") == 0) {
            startSystemServer = true;
        } else if (strcmp(arg, "--application") == 0) {
            application = true;
        } else if (strncmp(arg, "--nice-name=", 12) == 0) {
            niceName = (arg + 12);
        } else if (strncmp(arg, "--", 2) != 0) {
            className = arg;
            break;
        } else {
            --i;
            break;
        }
    }


    //这里zygote = true;
    //niceName=ZYGOTE_NICE_NAME="zygote64";
    //className="start-system-server"
    //args是一个Vector<String8>;参数有start-system-server
    if (!niceName.empty()) {
        runtime.setArgv0(niceName.c_str(), true /* setProcName */);
    }

    //这里通过AppRuntime(AndroidRuntime)启动
    if (zygote) {
        runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
    } else if (!className.empty()) {
        runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
    } else {
        fprintf(stderr, "Error: no class name or --zygote supplied.\n");
        app_usage();
        LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
    }
}

接着看下AndroidRuntime的start方法

\frameworks\base\core\jni\AndroidRuntime.cpp

void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
{

    JniInvocation jni_invocation;
    jni_invocation.Init(NULL);
    JNIEnv* env;
    //startVm这个方法比较重要,主要功能就是启动java虚拟机,并获取mJavaVM,env对象
    if (startVm(&mJavaVM, &env, zygote, primary_zygote) != 0) {
        return;
    }
    onVmCreated(env);
    if (startReg(env) < 0) {
        ALOGE("Unable to register all android natives\n");
        return;
    }


    jclass stringClass;
    jobjectArray strArray;
    jstring classNameStr;

    stringClass = env->FindClass("java/lang/String");
    assert(stringClass != NULL);
    strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
    assert(strArray != NULL);
    classNameStr = env->NewStringUTF(className);
    assert(classNameStr != NULL);
    env->SetObjectArrayElement(strArray, 0, classNameStr);

    for (size_t i = 0; i < options.size(); ++i) {
        jstring optionsStr = env->NewStringUTF(options.itemAt(i).c_str());
        assert(optionsStr != NULL);
        env->SetObjectArrayElement(strArray, i + 1, optionsStr);
    }

    /*
     * Start VM.  This thread becomes the main thread of the VM, and will
     * not return until the VM exits.
     */
     //找到className对应的类,通过env去执行其java中类的main方法;
     //从app_main.cpp可以知道这里是执行ZygoteInit和RuntimeInit
    char* slashClassName = toSlashClassName(className != NULL ? className : "");
    jclass startClass = env->FindClass(slashClassName);
    
        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
            "([Ljava/lang/String;)V");
        if (startMeth == NULL) {
            ALOGE("JavaVM unable to find main() in '%s'\n", className);
        } else {
            env->CallStaticVoidMethod(startClass, startMeth, strArray);
        }
    
    free(slashClassName);

}
\frameworks\base\core\jni\AndroidRuntime.cpp

int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv, bool zygote, bool primary_zygote)
{
    JavaVMInitArgs initArgs;
    ......
    
    initArgs.version = JNI_VERSION_1_4;
    initArgs.options = mOptions.editArray();
    initArgs.nOptions = mOptions.size();
    initArgs.ignoreUnrecognized = JNI_FALSE;

    //这个前面把虚拟机的启动参数放到mOptions中并调用libart.so提供的接口JNI_CreateJavaVM
    if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
        ALOGE("JNI_CreateJavaVM failed\n");
        return -1;
    }

    return 0;
}

/art/runtime/java_vm_ext.cc

extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
      ScopedTrace trace(__FUNCTION__);
      const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
      //判断版本是否正确
      if (JavaVMExt::IsBadJniVersion(args->version)) {
        LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
        return JNI_EVERSION;
      }
      RuntimeOptions options;
      for (int i = 0; i < args->nOptions; ++i) {
        JavaVMOption* option = &args->options[i];
        options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
      }
      bool ignore_unrecognized = args->ignoreUnrecognized;
      //创建Runtime对象
      if (!Runtime::Create(options, ignore_unrecognized)) {
        return JNI_ERR;
      }

      // Initialize native loader. This step makes sure we have
      // everything set up before we start using JNI.
      android::InitializeNativeLoader();

      Runtime* runtime = Runtime::Current();
      bool started = runtime->Start();
      if (!started) {
        delete Thread::Current()->GetJniEnv();
        delete runtime->GetJavaVM();
        LOG(WARNING) << "CreateJavaVM failed";
        return JNI_ERR;
      }

       //创建完成后,返回java虚拟机对象
      *p_env = Thread::Current()->GetJniEnv();
      *p_vm = runtime->GetJavaVM();
     
      return JNI_OK;
}

从上面的逻辑中,知道了startVM创建java虚拟机,并获取env对象,用于执行java类中的逻辑;也就是执行ZygoteInit和RuntimeInit的main方法; 接下来看下RuntimeInit

\frameworks\base\core\java\com\android\internal\os\RuntimeInit.java
    public static final void main(String[] argv) {
        preForkInit();
        if (argv.length == 2 && argv[1].equals("application")) {
            if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application");
            redirectLogStreams();
        } else {
            if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting tool");
        }

        commonInit();

       //初始化完成。里面会有一些onStarted的回调函数
        nativeFinishInit();
    }
    
    
    public static void preForkInit() {
    //enableDdms; ddms :Android开发很熟悉的工具,
        RuntimeInit.enableDdms();
        MimeMap.setDefaultSupplier(DefaultMimeMapFactory::create);
    }
    
    protected static final void commonInit() {

        /*
         * set handlers; these apply to all threads in the VM. Apps can replace
         * the default handler, but not the pre handler.
         */
        LoggingHandler loggingHandler = new LoggingHandler();
        RuntimeHooks.setUncaughtExceptionPreHandler(loggingHandler);
        //设置一个不捕获异常的handler:FATAL EXCEPTION:
        Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler));

        //设置时区?
        RuntimeHooks.setTimeZoneIdSupplier(() -> SystemProperties.get("persist.sys.timezone"));


        LogManager.getLogManager().reset();
        new AndroidConfig();


        initialized = true;
    }

再看下ZygoteInit


public static void main(String[] argv) {
        ZygoteServer zygoteServer = null;

        // Mark zygote start. This ensures that thread creation will throw
        // an error.
        ZygoteHooks.startZygoteNoThreadCreation();

        Runnable caller;
        try {
            
            RuntimeInit.preForkInit();

            boolean startSystemServer = false;
            String zygoteSocketName = "zygote";
            String abiList = null;
            boolean enableLazyPreload = false;
            for (int i = 1; i < argv.length; i++) {
                if ("start-system-server".equals(argv[i])) {
                    startSystemServer = true;
                } else if ("--enable-lazy-preload".equals(argv[i])) {
                    enableLazyPreload = true;
                } else if (argv[i].startsWith(ABI_LIST_ARG)) {
                    abiList = argv[i].substring(ABI_LIST_ARG.length());
                } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
                    zygoteSocketName = argv[i].substring(SOCKET_NAME_ARG.length());
                } else {
                    throw new RuntimeException("Unknown command line argument: " + argv[i]);
                }
            }
            //很明显这里enableLazyPreload为false;因为没有--enable-lazy-preload
            if (!enableLazyPreload) {
                bootTimingsTraceLog.traceBegin("ZygotePreload");
                //五星,预加载资源;这个一般有trace跟踪,因为比较耗时,手机开启启动耗时的原因
                preload(bootTimingsTraceLog);
                bootTimingsTraceLog.traceEnd(); // ZygotePreload
            }
            //五星:这里创建socketServer,循环监听socket的客户端
            zygoteServer = new ZygoteServer(isPrimaryZygote);
            //很明显这里startSystemServer为true;从init.zygote64.rc中传入的参数在这里用到了
            if (startSystemServer) {
                Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
the
                // child (system_server) process.
                if (r != null) {
                    r.run();
                    return;
                }
            }


            // The select loop returns early in the child process after a fork and
            // loops forever in the zygote.
            / /继续五星:循环监听,源码的英文注释我也不删了,
            // 但是runSelectLoop这个是接收客户端的连接,不属于启动流程,先放在这里后续再说
            caller = zygoteServer.runSelectLoop(abiList);
        } catch (Throwable ex) {
            throw ex;
        } finally {
            if (zygoteServer != null) {
                zygoteServer.closeServerSocket();
            }
        }

        // We're in the child process and have exited the select loop. Proceed to execute the
        // command.
        if (caller != null) {
            caller.run();
        }
    }

先看第一个五星:preload:预加载

    static void preload(TimingsTraceLog bootTimingsTraceLog) {
        Log.d(TAG, "begin preload");
        beginPreload();
        //源码中这里几乎每个方法前后都有trace,记录加载消耗的时间
        preloadClasses();
        cacheNonBootClasspathClassLoaders();
        //资源加载
        Resources.preloadResources();
        
        nativePreloadAppProcessHALs();
        //加载openGL
        maybePreloadGraphicsDriver();
        //共享库的加载
        preloadSharedLibraries();
        //文字,字体加载
        preloadTextResources();
        // Ask the WebViewFactory to do any initialization that must run in the zygote process,
        // for memory sharing purposes.
        WebViewFactory.prepareWebViewInZygote();
        endPreload();
        warmUpJcaProviders();
        Log.d(TAG, "end preload");

        sPreloadComplete = true;
    }
    
    private static void beginPreload() {
        Log.i(TAG, "Calling ZygoteHooks.beginPreload()");

        ZygoteHooks.onBeginPreload();
    }

    private static void endPreload() {
        ZygoteHooks.onEndPreload();

        Log.i(TAG, "Called ZygoteHooks.endPreload()");
    }

zygote预加载的优点:将资源preload预加载到zygote进程后,所有从zygote进程fork的子进程将共享这份空间,无需重新加载,大大减少app的启动时间,只是增加的系统的启动时间(开机时间)

private static void preloadClasses() {
        final VMRuntime runtime = VMRuntime.getRuntime();

//获取文件流,肯定是为了加载文件PRELOADED_CLASSES;
//private static final String PRELOADED_CLASSES = "/system/etc/preloaded-classes";
//下面有个图,可以大致看下这个文件是啥样的
        InputStream is;
        try {
            is = new FileInputStream(PRELOADED_CLASSES);
        } catch (FileNotFoundException e) {
            Log.e(TAG, "Couldn't find " + PRELOADED_CLASSES + ".");
            return;
        }



        try {
            BufferedReader br =
                    new BufferedReader(new InputStreamReader(is), Zygote.SOCKET_BUFFER_SIZE);

            int count = 0;
            int missingLambdaCount = 0;
            String line;
            while ((line = br.readLine()) != null) {
                // Skip comments and blank lines.
                line = line.trim();
                if (line.startsWith("#") || line.equals("")) {
                    continue;
                }
                    //按行将对应的类加载到内存
                    Class.forName(line, true, null);
                    count++;
                
            }

        } catch (IOException e) {
            Log.e(TAG, "Error reading " + PRELOADED_CLASSES + ".", e);
        } finally {
            IoUtils.closeQuietly(is);

            runtime.preloadDexCaches();
            Trace.traceEnd(Trace.TRACE_TAG_DALVIK);

            
            if (isExperimentEnabled("profilebootclasspath")) {
                Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "ResetJitCounters");
                VMRuntime.resetJitCounters();
            }

        }
    }

屏幕截图 2024-11-12 114521.png

forkSystemServer
 private static Runnable forkSystemServer(String abiList, String socketName,
            ZygoteServer zygoteServer) {
        long capabilities =
                (1L << OsConstants.CAP_IPC_LOCK) |
                (1L << OsConstants.CAP_KILL) |
                (1L << OsConstants.CAP_NET_ADMIN) |
                (1L << OsConstants.CAP_NET_BIND_SERVICE) |
                (1L << OsConstants.CAP_NET_BROADCAST) |
                (1L << OsConstants.CAP_NET_RAW) |
                (1L << OsConstants.CAP_SYS_MODULE) |
                (1L << OsConstants.CAP_SYS_NICE) |
                (1L << OsConstants.CAP_SYS_PTRACE) |
                (1L << OsConstants.CAP_SYS_TIME) |
                (1L << OsConstants.CAP_SYS_TTY_CONFIG) |
                (1L << OsConstants.CAP_WAKE_ALARM) |
                (1L << OsConstants.CAP_BLOCK_SUSPEND);
        /* Containers run without some capabilities, so drop any caps that are not available. */
        StructCapUserHeader header = new StructCapUserHeader(
                OsConstants._LINUX_CAPABILITY_VERSION_3, 0);
        StructCapUserData[] data;
        try {
            data = Os.capget(header);
        } catch (ErrnoException ex) {
            throw new RuntimeException("Failed to capget()", ex);
        }
        capabilities &= Integer.toUnsignedLong(data[0].effective) |
                (Integer.toUnsignedLong(data[1].effective) << 32);

        /* Hardcoded command line to start the system server */
        //启动systemserver的命令行
        String[] args = {
                "--setuid=1000",
                "--setgid=1000",
                "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,"
                        + "1024,1032,1065,3001,3002,3003,3005,3006,3007,3009,3010,3011,3012",
                "--capabilities=" + capabilities + "," + capabilities,
                "--nice-name=system_server",
                "--runtime-args",
                "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
                "com.android.server.SystemServer",
        };
        ZygoteArguments parsedArgs;

        int pid;

        try {
            ZygoteCommandBuffer commandBuffer = new ZygoteCommandBuffer(args);
            try {
                parsedArgs = ZygoteArguments.getInstance(commandBuffer);
            } catch (EOFException e) {
                throw new AssertionError("Unexpected argument error for forking system server", e);
            }
            commandBuffer.close();
            Zygote.applyDebuggerSystemProperty(parsedArgs);
            Zygote.applyInvokeWithSystemProperty(parsedArgs);

            if (Zygote.nativeSupportsMemoryTagging()) {
                String mode = SystemProperties.get("persist.arm64.memtag.system_server", "");
                if (mode.isEmpty()) {
                  /* The system server has ASYNC MTE by default, in order to allow
                   * system services to specify their own MTE level later, as you
                   * can't re-enable MTE once it's disabled. */
                  mode = SystemProperties.get("persist.arm64.memtag.default", "async");
                }
                if (mode.equals("async")) {
                    parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_ASYNC;
                } else if (mode.equals("sync")) {
                    parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_SYNC;
                } else if (!mode.equals("off")) {
                    parsedArgs.mRuntimeFlags |= Zygote.nativeCurrentTaggingLevel();

                }
            } else if (Zygote.nativeSupportsTaggedPointers()) {
                parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_TBI;
            }
            parsedArgs.mRuntimeFlags |= Zygote.GWP_ASAN_LEVEL_LOTTERY;

            if (shouldProfileSystemServer()) {
                parsedArgs.mRuntimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
            }

            /* Request to fork the system server process */
            //fork出systemserver进程;parsedArgs由上面args解析出来的
            //parsedArgs.mUid=1000, parsedArgs.mGid=1000
            pid = Zygote.forkSystemServer(
                    parsedArgs.mUid, parsedArgs.mGid,
                    parsedArgs.mGids,
                    parsedArgs.mRuntimeFlags,
                    null,
                    parsedArgs.mPermittedCapabilities,
                    parsedArgs.mEffectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }

        /* For child process */
        if (pid == 0) {//systemserver进程,
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
            // systemserver进程中关闭zygoteServer
            zygoteServer.closeServerSocket();
            // 初始化systemserver相关
            return handleSystemServerProcess(parsedArgs);
        }

        return null;
    }

//fork出systemserver进程,返回pid
static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
            int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {

    int pid = nativeForkSystemServer(uid, gid, gids, runtimeFlags, rlimits,
            permittedCapabilities, effectiveCapabilities);

    // Set the Java Language thread priority to the default value for new apps.
    Thread.currentThread().setPriority(Thread.NORM_PRIORITY);

    return pid;
}
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
        Os.umask(S_IRWXG | S_IRWXO);

        if (parsedArgs.mNiceName != null) {
            Process.setArgV0(parsedArgs.mNiceName);
        }

        //系统环境变量,在device/google/cuttlefish/shared/config/profile.root中
        //export SYSTEMSERVERCLASSPATH = system/framework/services.jar:/system/framework/ethernet-service.jar:/system/framework/wifi-service.jar
        final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
        if (systemServerClasspath != null) {
            // Capturing profiles is only supported for debug or eng builds since selinux normally
            // prevents it.
            if (shouldProfileSystemServer() && (Build.IS_USERDEBUG || Build.IS_ENG)) {
                try {
                    Log.d(TAG, "Preparing system server profile");
                    final String standaloneSystemServerJars =
                            Os.getenv("STANDALONE_SYSTEMSERVER_JARS");
                    final String systemServerPaths = standaloneSystemServerJars != null
                            ? String.join(":", systemServerClasspath, standaloneSystemServerJars)
                            : systemServerClasspath;
                    //将SYSTEMSERVERCLASSPATH中的AppInfo加载到VM中
                    prepareSystemServerProfile(systemServerPaths);
                } catch (Exception e) {
                    Log.wtf(TAG, "Failed to set up system server profile", e);
                }
            }
        }
        //判断parsedArgs 为空
        if (parsedArgs.mInvokeWith != null) {
            
            WrapperInit.execApplication(parsedArgs.mInvokeWith,
                    parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion,
                    VMRuntime.getCurrentInstructionSet(), null, args);
        } else {
        //systemserver对应的路径构建出类加载器
            ClassLoader cl = getOrCreateSystemServerClassLoader();
            if (cl != null) {
                Thread.currentThread().setContextClassLoader(cl);
            }

            /*
             * Pass the remaining arguments to SystemServer.
             */
             //将保存的参数以及类加载器 传递到ZygoteInit中
             //parsedArgs.mRemainingArgs是forkSystemServer中args的参数
             //比较重要的是com.android.server.SystemServer
            return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
                    parsedArgs.mDisabledCompatChanges,
                    parsedArgs.mRemainingArgs, cl);
        }

    }
    
    
    
    
    public static Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
            String[] argv, ClassLoader classLoader) {
        //初始化
        RuntimeInit.commonInit();
        ZygoteInit.nativeZygoteInit();
        //又到RuntimeInit的applicationInit中
        return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
                classLoader);
    }
    
    
    protected static Runnable applicationInit(int targetSdkVersion, 
            long[] disabledCompatChanges,
            String[] argv, ClassLoader classLoader) {
        final Arguments args = new Arguments(argv);
        return findStaticMain(args.startClass, args.startArgs, classLoader);
    }
    
    
    
    protected static Runnable findStaticMain(String className, String[] argv,
            ClassLoader classLoader) {
        Class<?> cl;

        try {
            //className这个是forkSystemServer()方法中的字符串硬编码而来;
            //就是前面说的 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 {
            //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);
        }

         MethodAndArgsCaller 通过抛出异常来清空堆栈,
         并调用com.android.server.SystemServer的main方法
         */
        return new MethodAndArgsCaller(m, argv);
    }
    
    
    static class MethodAndArgsCaller implements Runnable {
        /** method to call */
        private final Method mMethod;

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

        public MethodAndArgsCaller(Method method, String[] args) {
            mMethod = method;
            mArgs = args;
        }

        public void run() {
            try {
                //这里调用的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);
            }
        }
    }


在ZygoteInit的main方法中又调用了

if (r != null) { 
    r.run(); 
    return; 
}

也就是调用了MethodAndArgsCaller的run方法,也就是执行了SystemServer的main方法,然后就return了;

注意,这里的return只是ZygoteInit的main方法return了;但是对于SystemServer进程会执行到SystemServer的main方法里面

三、systemserver启动流程

上面看到了forkSystemServer通过zygote fork出了systemserver进程,并调用了com.android.server.SystemServer的main方法

//frameworks\base\services\java\com\android\server\SystemServer.java
//终于看到了最简单的方法,就一行
    public static void main(String[] args) {
        new SystemServer().run();
    }
    //接着是run方法,好像不少
    private void run() {
        TimingsTraceAndSlog t = new TimingsTraceAndSlog();
        try {
            // Prepare the main looper thread (this thread).
            android.os.Process.setThreadPriority(
                    android.os.Process.THREAD_PRIORITY_FOREGROUND);
            android.os.Process.setCanSelfBackground(false);
            Looper.prepareMainLooper();
            Looper.getMainLooper().setSlowLogThresholdMs(
                    SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

            SystemServiceRegistry.sEnableServiceNotFoundWtf = true;

            // Initialize native services.
            System.loadLibrary("android_servers");


            // Initialize the system context.
            //系统上下文context,
            createSystemContext();

            // Call per-process mainline module initialization.
            ActivityThread.initializeMainlineModules();

            // Sets the dumper service
            ServiceManager.addService("system_server_dumper", mDumper);
            mDumper.addDumpable(this);

            // Create the system service manager.
            //五星:创建SystemServiceManager
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            mSystemServiceManager.setStartInfo(mRuntimeRestart,
                    mRuntimeStartElapsedTime, mRuntimeStartUptime);
            mDumper.addDumpable(mSystemServiceManager);

            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
            // Prepare the thread pool for init tasks that can be parallelized
            SystemServerInitThreadPool tp = SystemServerInitThreadPool.start();
            mDumper.addDumpable(tp);



            // Attach JVMTI agent if this is a debuggable build and the system property is set.
            if (Build.IS_DEBUGGABLE) {
                // Property is of the form "library_path=parameters".
                String jvmtiAgent = SystemProperties.get("persist.sys.dalvik.jvmtiagent");
                if (!jvmtiAgent.isEmpty()) {
                    int equalIndex = jvmtiAgent.indexOf('=');
                    String libraryPath = jvmtiAgent.substring(0, equalIndex);
                    String parameterList =
                            jvmtiAgent.substring(equalIndex + 1, jvmtiAgent.length());
                    // Attach the agent.
                    try {
                        Debug.attachJvmtiAgent(libraryPath, parameterList, null);
                    } catch (Exception e) {
                        Slog.e("System", "*************************************************");
                        Slog.e("System", "********** Failed to load jvmti plugin: " + jvmtiAgent);
                    }
                }
            }
        } finally {
            t.traceEnd();  // InitBeforeStartServices
        }

        // Setup the default WTF handler
        RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);

        // Start services.
        try {
            t.traceBegin("StartServices");
            //五星:启动相关service
            //启动BootstrapServices,就是系统必须需要的服务,
            //这些服务与其他服务相关性很高,所以干脆就放在一个方法里面一起启动,
            //如PowerManagerService,RecoverySvstemService、DisplaylanagerService、ActivityManagerService等等启动以基本的核心Service,很简单,只有三个BatteryService、比 如UsageStatsService、WebViewUpdateService启动其它需要用到的Service,NetworkScoreService、AlarmManagerservice

            startBootstrapServices(t);
            startCoreServices(t);
            startOtherServices(t);
            startApexServices(t);
            // Only update the timeout after starting all the services so that we use
            // the default timeout to start system server.
            updateWatchdogTimeout(t);
            CriticalEventLog.getInstance().logSystemServerStarted();
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            t.traceEnd(); // StartServices
        }



        // Loop forever.
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

创建系统上下文的代码逻辑

// \frameworks\base\services\java\com\android\server\SystemServer.java
    private void createSystemContext() {
        ActivityThread activityThread = ActivityThread.systemMain();
        mSystemContext = activityThread.getSystemContext();
        mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

        final Context systemUiContext = activityThread.getSystemUiContext();
        systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
        Trace.registerWithPerfetto();
    }
    
// \frameworks\base\core\java\android\app\ActivityThread.java
    public static ActivityThread systemMain() {
        ThreadedRenderer.initForSystemProcess();
        ActivityThread thread = new ActivityThread();
        thread.attach(true, 0);
        return thread;
    }
    在这里创建的context
    public ContextImpl getSystemContext() {
        synchronized (this) {
            if (mSystemContext == null) {
                mSystemContext = ContextImpl.createSystemContext(this);
            }
            return mSystemContext;
        }
    }
    
    //代码开始逐渐熟悉了
    static ContextImpl createSystemContext(ActivityThread mainThread) {
        LoadedApk packageInfo = new LoadedApk(mainThread);
        ContextImpl context = new ContextImpl(null, mainThread, packageInfo,
                ContextParams.EMPTY, null, null, null, null, null, 0, null, null,
                DEVICE_ID_DEFAULT, false);
        context.setResources(packageInfo.getResources());
        context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
                context.mResourcesManager.getDisplayMetrics());
        context.mContextType = CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI;
        return context;
    }
  1. init 根据init.rc 运行 app_process,并携带-zygote’和startsystemserver参数。
  2. AndroidRuntime.cpp: :start()里将启动JavaVM,并且注册所有framework相关的系统JNI接口。
  3. 第一次进入Java世界,运行ZygoteInit.java::main()函数初始化Zygote.Zygote 并创建Socket的 server 端。
  4. 然后fork一个新的进程并在新进程里初始化SystemServer.Fork之前,Zygote是preload常用的Java类库, 以及系统的resources, 同时GC()清理内存空间,为子进程省去重复的工作。
  5. SystemServer 里将所有的系统Service初始化,包括ActivityManager 和WindowManager,他们 是应用程序运行起来的前提。
  6. 依次同时,Zygote监听服务端Socket,等待新的应用启动请求。
  7. ActivityManager ready之后寻找系统的“Startup” Application,将请求发给Zygote。
  8. Zygote收到请求后,fork出一个新的进程。
  9. Zygote监听并处理SystemServer 的 SIGCHID 信号,一旦System Server崩溃,立即将自己杀死。 init会重启Zygote.