Android开机启动流程3_zygote



zygote

zygote进程启动

@init.rc

service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server

app_process的源码

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

 int main(int argc, const char* const argv[])

{

    // These are global variables in ProcessState.cpp

    mArgC = argc;

    mArgV = argv;

 

    mArgLen = 0;

    for (int i=0; i<argc; i++) {

        mArgLen += strlen(argv[i]) + 1;

    }

    mArgLen--;

 

    AppRuntime runtime;

    const char* argv0 = argv[0];

 

    // Process command line arguments

    // ignore argv[0]

    argc--;

    argv++;

 

    // Everything up to '--' or first non '-' arg goes to the vm

 

    int i = runtime.addVmArguments(argc, argv);

 

    // Parse runtime arguments.  Stop at first unrecognized option.

    bool zygote = false;

    bool startSystemServer = false;

    bool application = false;

    const char* parentDir = NULL;

    const char* niceName = NULL;

    const char* className = NULL;

    while (i < argc) {

        const char* arg = argv[i++];

        if (!parentDir) {

            parentDir = arg;

        } else if (strcmp(arg, "--zygote") == 0) {

            zygote = true;

            niceName = "zygote";

        } 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 {

            className = arg;

            break;

        }

    }

 

    if (niceName && *niceName) {

        setArgv0(argv0, niceName);

        set_process_name(niceName);

    }

 

    runtime.mParentDir = parentDir;

 

    if (zygote) {

        runtime.start("com.android.internal.os.ZygoteInit",

                startSystemServer ? "start-system-server" : "");

    } else if (className) {

        // Remainder of args get passed to startup class main()

        runtime.mClassName = className;

        runtime.mArgC = argc - i;

        runtime.mArgV = argv + i;

        runtime.start("com.android.internal.os.RuntimeInit",

                application ? "application" : "tool");

    } else {

        fprintf(stderr, "Error: no class name or --zygote supplied.\n");

        app_usage();

        LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");

        return 10;

    }

            

注:这里传入的参数:-Xzygote /system/bin --zygote --start-system-server所以 

1.zygote = true;niceName = "zygote";startSystemServer = true;

2.set_process_name(niceName);进程的名字改成了zygote

3.runtime.start();传入的参数是"com.android.internal.os.ZygoteInit""start-system-server" 

AppRuntime::start()

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

 void AndroidRuntime::start(const char* className, const char* options)

{

    LOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n",

            className != NULL ? className : "(unknown)");

 

    blockSigpipe();

 

    /*

     * 'startSystemServer == true' means runtime is obsolete and not run from

     * init.rc anymore, so we print out the boot start event here.

     */

    if (strcmp(options, "start-system-server") == 0) {

        /* track our progress through the boot sequence */

        const int LOG_BOOT_PROGRESS_START = 3000;

        LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,

                       ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));

    }

 

    const char* rootDir = getenv("ANDROID_ROOT");

    if (rootDir == NULL) {

        rootDir = "/system";

        if (!hasDir("/system")) {

            LOG_FATAL("No root directory specified, and /android does not exist.");

            return;

        }

        setenv("ANDROID_ROOT", rootDir, 1);

    }

 

    //const char* kernelHack = getenv("LD_ASSUME_KERNEL");

    //LOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);

 

    /* start the virtual machine */

    JNIEnv* env;

    if (startVm(&mJavaVM, &env) != 0) {

        return;

    }

    onVmCreated(env);

 

    /*

     * Register android functions.

     */

    if (startReg(env) < 0) {

        LOGE("Unable to register all android natives\n");

        return;

    }

 

    /*

     * We want to call main() with a String array with arguments in it.

     * At present we have two arguments, the class name and an option string.

     * Create an array to hold them.

     */

    jclass stringClass;

    jobjectArray strArray;

    jstring classNameStr;

    jstring optionsStr;

 

    stringClass = env->FindClass("java/lang/String");

    assert(stringClass != NULL);

    strArray = env->NewObjectArray(2, stringClass, NULL);

    assert(strArray != NULL);

    classNameStr = env->NewStringUTF(className);

    assert(classNameStr != NULL);

    env->SetObjectArrayElement(strArray, 0, classNameStr);

    optionsStr = env->NewStringUTF(options);

    env->SetObjectArrayElement(strArray, 1, optionsStr);

 

    /*

     * Start VM.  This thread becomes the main thread of the VM, and will

     * not return until the VM exits.

     */

    char* slashClassName = toSlashClassName(className);

    jclass startClass = env->FindClass(slashClassName);

    if (startClass == NULL) {

        LOGE("JavaVM unable to locate class '%s'\n", slashClassName);

        /* keep going */

    } else {

        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",

            "([Ljava/lang/String;)V");

        if (startMeth == NULL) {

            LOGE("JavaVM unable to find main() in '%s'\n", className);

            /* keep going */

        } else {

            env->CallStaticVoidMethod(startClass, startMeth, strArray);

 

#if 0

            if (env->ExceptionCheck())

                threadExitUncaughtException(env);

#endif

        }

    }

    free(slashClassName);

 

    LOGD("Shutting down VM\n");

    if (mJavaVM->DetachCurrentThread() != JNI_OK)

        LOGW("Warning: unable to detach main thread\n");

    if (mJavaVM->DestroyJavaVM() != 0)

        LOGW("Warning: VM did not shut down cleanly\n");

}

            

注:

1. startVm(&mJavaVM, &env),启动java虚拟机

2. startReg(env),注册android jni函数

3. env->CallStaticVoidMethod(startClass, startMeth, strArray); jni 调用 java 方法,startClass 为参数className转化而来startMethmain方法,strArray为:env->SetObjectArrayElement(strArray, 0, classNameStr); env->SetObjectArrayElement(strArray, 1, optionsStr);

4. CallStaticVoidMethod就启动了com.android.internal.os.ZygoteInit中的main

ZygoteInit.main

@frameworks\base\core\java\com\android\internal\os\ZygoteInit.java

 public static void main(String argv[]) {

        try {

            // Start profiling the zygote initialization.

            SamplingProfilerIntegration.start();

 

            registerZygoteSocket();

            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,

                SystemClock.uptimeMillis());

            preload();

            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,

                SystemClock.uptimeMillis());

 

            // Finish profiling the zygote initialization.

            SamplingProfilerIntegration.writeZygoteSnapshot();

 

            // Do an initial gc to clean up after startup

            gc();

 

            // If requested, start system server directly from Zygote

            if (argv.length != 2) {

                throw new RuntimeException(argv[0] + USAGE_STRING);

            }

 

            if (argv[1].equals("start-system-server")) {

                startSystemServer();

            } else if (!argv[1].equals("")) {

                 startSystemServer();

            }else{

                throw new RuntimeException(argv[0] + USAGE_STRING);

            }

 

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

 

            if (ZYGOTE_FORK_MODE) {

                runForkMode();

            } else {

                runSelectLoopMode();

            }

 

            closeServerSocket();

        } catch (MethodAndArgsCaller caller) {

            caller.run();

        } catch (RuntimeException ex) {

            Log.e(TAG, "Zygote died with exception", ex);

            closeServerSocket();

            throw ex;

        }

    }

注:

1.传入的参数任然为app_main 传入runtime.start()的参数"com.android.internal.os.ZygoteInit""start-system-server"

2. preload();要预加载preloadClasses() 和 preloadResources()

3. startSystemServer();中会启动一个新的进程:system_server

4.最后会调用runSelectLoopMode(),进入while循环,由peers创建新的进程。

 

fork进程systemserver

@frameworks\base\core\java\com\android\internal\os\ZygoteInit.java

  /**

     * Prepare the arguments and fork for the system server process.

     */

    private static boolean startSystemServer()

            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,3001,3002,3003,3006,3007",

            "--capabilities=130104352,130104352",

            "--runtime-init",

            "--nice-name=system_server",

            "com.android.server.SystemServer",

        };

        ZygoteConnection.Arguments parsedArgs = null;

 

        int pid;

 

        try {

            parsedArgs = new ZygoteConnection.Arguments(args);

            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);

            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

 

            /* Request to fork the system server process */

            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 */

        if (pid == 0) {

            handleSystemServerProcess(parsedArgs);

        }

 

        return true;

    }

注:args命令行参数,包括:uid,gid,group,process_name,process class

Zygote.forkSystemServer返回的子进程 pid非0,在子进程中返回0

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android开机服务启动流程主要包括以下几个步骤: 1. 开机引导:当用户按下电源键开机后,硬件会首先进行自检,然后加载引导程序Bootloader。Bootloader负责加载Android系统的内核。 2. 内核启动:引导程序加载完毕后,会启动Android系统的内核(Linux内核)。内核负责初始化硬件设备、创建第一个用户进程init,并启动init进程。 3. init进程启动:init进程是整个Android系统的第一个用户进程,它是所有其他进程的祖先进程。init进程会读取系统配置文件(如init.rc),根据配置文件启动各种系统服务和应用程序。 4. 启动Zygote进程:init进程会启动Zygote进程,Zygote进程是一个特殊的进程,它作为所有Java应用程序的父进程。Zygote进程会预加载常用的系统类和资源,以提高应用程序的启动速度。 5. 启动系统服务:Zygote进程会通过SystemServer类启动系统服务。系统服务包括Activity Manager、Window Manager、PackageManager等,它们负责管理Android系统的各个方面。 6. 应用程序启动:当系统服务启动完成后,Zygote进程会等待应用程序的请求。当用户点击应用程序图标或通过其他方式启动应用程序时,Zygote进程会创建一个新的应用程序进程,并加载应用程序的代码和资源,最终启动应用程序。 以上是Android开机服务启动流程的基本步骤,具体的实现细节可能会根据不同的Android版本和设备厂商有所差异。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值