zygote64位和system_server進程的啟動篇

備注:以下代碼均是基于Android8.0分析的,大部分都是精簡過的代碼,便于理解
先上個流程圖和時序圖
流程圖如下


zygote進程啟動過程.png

時序圖如下


zygote啟動時序圖.png

一. init進程以及init.rc解析

init進程是Android的的第一個進程,進程id是1,啟動時執(zhí)行入口main函數(shù),解析init.rc文件,并執(zhí)行相關的指令

1. init.rc語法和規(guī)則

init.rc:是由一種被稱為“Android初始化語言”(Android Init Language,這里簡稱為AIL)的腳本寫成的文件,它有自己語法和解析規(guī)則init.rc解析

下面看下init.rc的內(nèi)容,為了方便閱讀,給出一個精簡版的關鍵內(nèi)容

## Copyright (C) 2012 The Android Open Source Project
##
## IMPORTANT: Do not create world writable files or directories.
## This is a common source of Android security bugs.
##

import /init.environ.rc
import /init.usb.rc
import /init.${ro.hardware}.rc
import /vendor/etc/init/hw/init.${ro.hardware}.rc
import /init.usb.configfs.rc
##import /init.${ro.zygote}.rc

service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
    class main   //option
    priority -20 //option
    user root  //option
    group root readproc
    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、
    
on early-init //監(jiān)聽事件
    *************
on init //監(jiān)聽事件
    *************
on property:sys.boot_from_charger_mode=1 //監(jiān)聽事件
    class_stop charger
    trigger late-init

## Mount filesystems and start core system services.
on late-init //監(jiān)聽事件

    ## Now we can start zygote for devices with file based encryption
    trigger zygote-start  //command
    
on zygote-start && property:ro.crypto.state=unsupported
    ## A/B update verifier that marks a successful boot.
    exec_start update_verifier_nonencrypted //command
    start netd //command
    start zygote //command
    start zygote_secondary //command

說明
service關鍵字表示創(chuàng)建一個服務,
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
表示創(chuàng)建一個名為zygote的服務,其實就是進程,執(zhí)行文件是/system/bin/app_process64,后面的就是執(zhí)行時攜帶參數(shù),這個后續(xù)再解析中再講,注意這只是創(chuàng)建服務,但是還沒啟動

on是表示監(jiān)聽某些事件,當事件發(fā)生觸發(fā)時,執(zhí)行下面的指令
比如
on late-init
## Now we can start zygote for devices with file based encryption
trigger zygote-start
表示late-init觸發(fā)時,觸發(fā)zygote-start事件

trigger:顧名思義,表示觸發(fā)某個事件
這樣的話
其實大概可以理清zygote在init.rc的啟動過程
late-init->zygote-start->start zygote
其中l(wèi)ate-init可能是property:sys.boot_from_charger_mode=1觸發(fā)的,也可能是其他地方觸發(fā)的,下面的講解會提到

2. init.rc的解析

下面再看看具體是怎么解析和執(zhí)行init.rc
精簡的關鍵代碼如下
代碼路徑:system/core/init/init.cpp

int main(int argc, char** argv) {
    //省略代碼
     Parser& parser = Parser::GetInstance();
    parser.AddSectionParser("service",std::make_unique<ServiceParser>());
    parser.AddSectionParser("on", std::make_unique<ActionParser>());
    parser.AddSectionParser("import", std::make_unique<ImportParser>());
     //省略代碼
     parser.ParseConfig("/init.rc");
     ActionManager& am = ActionManager::GetInstance();

    am.QueueEventTrigger("early-init");
     //省略代碼
    // Trigger all the boot actions to get us started.
    am.QueueEventTrigger("init");
     //省略代碼

    // Don't mount filesystems or start core system services in charger mode.
    std::string bootmode = GetProperty("ro.bootmode", "");
    if (bootmode == "charger") {
        am.QueueEventTrigger("charger");
    } else {
        am.QueueEventTrigger("late-init");
    }

    // Run all property triggers based on current state of the properties.
    am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");

    while (true) {
        // By default, sleep until something happens.
        int epoll_timeout_ms = -1;

        if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) {
            am.ExecuteOneCommand();
        }
       //省略代碼
    }
    return 0;
}

從代碼上看,主要分為兩部分

2.1 解析

可以看出有三個解析器分別是seriver,on和import,分為解析相關的關鍵字,這個跟init.rc的結構大體一致

將事件放到隊列中,然后按順序執(zhí)行,這里面都是執(zhí)行的初始化相關的事件,包括上面說的late-init這樣的話,它就按照init.rc的規(guī)則,鏈式觸發(fā)相關事件或者執(zhí)行相關動作

再來看一看parse部分,這里主要看service的parser
先看parse解析器
代碼路徑:system/core/init/init_parser.cpp

void Parser::ParseData(const std::string& filename, const std::string& data) {
    //TODO: Use a parser with const input and remove this copy
    std::vector<char> data_copy(data.begin(), data.end());
    data_copy.push_back('\0');

    parse_state state;
    state.filename = filename.c_str();
    state.line = 0;
    state.ptr = &data_copy[0];
    state.nexttoken = 0;

    SectionParser* section_parser = nullptr;
    std::vector<std::string> args;

    for (;;) {
        switch (next_token(&state)) {
        case T_EOF:
            if (section_parser) {
                section_parser->EndSection();
            }
            return;
        case T_NEWLINE:
            state.line++;
            if (args.empty()) {
                break;
            }
            if (section_parsers_.count(args[0])) {
                if (section_parser) 
                   //遇到下一個關鍵字,即該關鍵字對應的分段解析結束
                    section_parser->EndSection();
                }
               //獲取對應關鍵字的解析器。比如service/on/import
                section_parser = section_parsers_[args[0]].get();
                std::string ret_err;
                //解析關鍵字對應的行
                if (!section_parser->ParseSection(args, &ret_err)) {
                    parse_error(&state, "%s\n", ret_err.c_str());
                    section_parser = nullptr;
                }
            } else if (section_parser) {
                std::string ret_err;
               //解析關鍵字下面的內(nèi)容,也就是init.rc中的option和Commands內(nèi)容
                if (!section_parser->ParseLineSection(args, state.filename,
                                                      state.line, &ret_err)) {
                    parse_error(&state, "%s\n", ret_err.c_str());
                }
            }
            args.clear();
            break;
        case T_TEXT:
            args.emplace_back(state.text);
            break;
        }
    }
}

代碼很簡單,解析init.rc里面的內(nèi)容,遇到關鍵字是就轉(zhuǎn)給關鍵字相關的解析器解析

再來看下service的解析器
代碼路徑:system/core/init/service.cpp

//解析service中option的解析規(guī)則,精簡代碼
Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
    constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
    // clang-format off
    static const Map option_parsers = {
        {"capabilities",
                        {1,     kMax, &Service::ParseCapabilities}},
        {"class",       {1,     kMax, &Service::ParseClass}},
        {"oneshot",     {0,     0,    &Service::ParseOneshot}},
        {"onrestart",   {1,     kMax, &Service::ParseOnrestart}},
    };
    // clang-format on
    return option_parsers;
}


//解析service開頭部分,主要是創(chuàng)建個Service
bool ServiceParser::ParseSection(const std::vector<std::string>& args,
                                 std::string* err) {
    if (args.size() < 3) {
        *err = "services must have a name and a program";
        return false;
    }

    const std::string& name = args[1];
    if (!IsValidName(name)) {
        *err = StringPrintf("invalid service name '%s'", name.c_str());
        return false;
    }

    std::vector<std::string> str_args(args.begin() + 2, args.end());
//init.rc的service語法
//service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
//構造一個service,構造參數(shù)
//name:zygote
//str_args:/system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
    service_ = std::make_unique<Service>(name, str_args);
    return true;
}


//解析option或者comond的內(nèi)容
/**栗子
  class main
    onrestart write /sys/power/state on
    writepid /dev/cpuset/foreground/tasks
**/
bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
                                     const std::string& filename, int line,
                                     std::string* err) const {
    return service_ ? service_->ParseLine(args, err) : false;
}

//解析onrestart,就是把option內(nèi)容分為放在service中對應的數(shù)據(jù)中,其他的option就不一一列舉了
bool Service::ParseOnrestart(const std::vector<std::string>& args, std::string* err) {
    std::vector<std::string> str_args(args.begin() + 1, args.end());
    onrestart_.AddCommand(str_args, "", 0, err);
    return true;
}

//service關鍵字解析結束,將service加到vector容器中
void ServiceParser::EndSection() {
    if (service_) {
        ServiceManager::GetInstance().AddService(std::move(service_));
    }
}
至此service的部分解析結束

2.2 觸發(fā)事件

am.QueueEventTrigger("early-init");
am.QueueEventTrigger("init");
am.QueueEventTrigger("late-init");
am.ExecuteOneCommand();

二. zygote服務(進程)的啟動

1. 相關數(shù)據(jù)結構

從第一章節(jié)的2.2小節(jié)可以看到,解析完成之后觸發(fā)一些事件,對于zygote而言,init.rc里面有如下指令

on late-init
    ## Now we can start zygote for devices with file based encryption
    trigger zygote-start
on zygote-start && property:ro.crypto.state=unsupported
    start zygote
    start zygote_secondary

也就是說late-init事件發(fā)生時,會再觸發(fā)一個zygote-start事件,繼續(xù)觸發(fā)start zygote指令

先看下相關的數(shù)據(jù)結構,精簡代碼
代碼路徑:system/core/init/action.cpp
class Action

class Action {
private:
    std::string event_trigger_;  
    std::vector<Command> commands_;
    static const KeywordMap<BuiltinFunction>* function_map_;
};


class Command {
private:
    BuiltinFunction func_;
    std::vector<std::string> args_;
    std::string filename_;
    int line_;
};

class action中
event_trigger_:該action監(jiān)聽的觸發(fā)器
Command:觸發(fā)器觸發(fā)后要做的指令
function_map_:維護一個指令與具體調(diào)用方法的映射關系

class Command中
func_:具體的方法指針,通過解析on關鍵字,將指令取出(比如start指令),然后通過function_map_拿到具體的方法指針
args_:數(shù)據(jù)

如下是具體指令與具體調(diào)用方法的映射關系的精簡代碼,我們只需關注start指令就行
代碼路徑:system/core/init/builtins.cpp

BuiltinFunctionMap::Map& BuiltinFunctionMap::map() const {
    constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
    // clang-format off
    static const Map builtin_functions = {
        {"bootchart",               {1,     1,    do_bootchart}},
        {"chmod",                   {2,     2,    do_chmod}},
        {"chown",                   {2,     3,    do_chown}},
        {"class_reset",             {1,     1,    do_class_reset}},
        {"class_restart",           {1,     1,    do_class_restart}},
        {"class_start",             {1,     1,    do_class_start}},
        {"class_stop",              {1,     1,    do_class_stop}},
        {"start",                   {1,     1,    do_start}},
    };
    // clang-format on
    return builtin_functions;
}

2. init進程觸發(fā)事件過程

代碼路徑:system/core/init/action.cpp
精簡代碼

void ActionManager::ExecuteOneCommand() {
    // Loop through the trigger queue until we have an action to execute
   //遍歷trigger隊列與action中的監(jiān)聽trigger對比
    while (current_executing_actions_.empty() && !trigger_queue_.empty()) {
        for (const auto& action : actions_) {
            if (trigger_queue_.front()->CheckTriggers(*action)) {
                current_executing_actions_.emplace(action.get());
            }
        }
        trigger_queue_.pop();
    }
     //命中的話,執(zhí)行相關指令
    action->ExecuteOneCommand(current_command_);
}

void Action::ExecuteOneCommand(std::size_t command) const {
    // We need a copy here since some Command execution may result in
    // changing commands_ vector by importing .rc files through parser
    Command cmd = commands_[command];
    ExecuteCommand(cmd);
}

void Action::ExecuteCommand(const Command& command) const {
    Timer t;
    int result = command.InvokeFunc();
}

 //執(zhí)行指令對應的函數(shù)
int Command::InvokeFunc() const {
    expanded_args[0] = args_[0];
    return func_(expanded_args);
}

3.開始啟動zygote 服務

3.1 do_start()

上面func_(expanded_args)其實就是執(zhí)行do_start
代碼路徑:system/core/init/builtins.cpp

static int do_start(const std::vector<std::string>& args) {
    //args是init.rc對應的start zygote指令
    //args[1]就是zygote了,根據(jù)上面2.1章節(jié)解析service時會把結果放在vector容器中,而且service里面有name的成員變量
    //由此還可以根據(jù)name拿到對應的service
    Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
    if (!svc) {
        LOG(ERROR) << "do_start: Service " << args[1] << " not found";
        return -1;
    }
//調(diào)用service的start方法
    if (!svc->Start())
        return -1;
    return 0;
}

3.2 Start()

代碼路徑:system/core/init/service.cpp

bool Service::Start() {
    pid_t pid = -1;
    if (namespace_flags_) {
        pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
    } else {
        //熟悉的fork代碼
        pid = fork();
    }

    if (pid == 0) {
        std::vector<char*> strs;
        ExpandArgs(args_, &strs);
       //strs[0]就是/system/bin/app_process64
        //將fork出來的子進程也就是zygote進程變身到一個新的進程,pid和進程名保持不變,其他的數(shù)據(jù)被新的進程覆蓋
        if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
            PLOG(ERROR) << "cannot execve('" << strs[0] << "')";
        }

        _exit(127);
    }

    if (pid < 0) {
        PLOG(ERROR) << "failed to fork for '" << name_ << "'";
        pid_ = 0;
        return false;
    }
    return true;
}

說明:
1./system/bin/app_process6是有app_main.cpp編譯的可執(zhí)行文件
2.execve() 調(diào)用 成功 后 不會 返回, 其 進程 的 正文(text), 數(shù)據(jù)(data), bss 和 堆棧(stack) 段
被 調(diào)入程序 覆蓋. 調(diào)入程序 繼承了 調(diào)用程序 的 PID 和 所有 打開的 文件描述符, 他們 不會
因為 exec 過程 而 關閉. 父進程 的 未決 信號 被 清除. 所有 被 調(diào)用進程 設置過 的 信號
重置為 缺省行為
也就是說execve如果調(diào)用成功,其后面的代碼不會被執(zhí)行

3.3 app_main的main()

代碼路徑:frameworks/base/cmds/app_process/app_main.cpp

int main(int argc, char* const argv[])
{
   //AppRuntime是繼承AndroidRuntime的,這里創(chuàng)建一個runtime,下文會提及到 //todo_1
   AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
    // Parse runtime arguments.  Stop at first unrecognized option.
    bool zygote = false;
    bool startSystemServer = false;
    bool application = false;
    String8 niceName;
    String8 className;

    ++i;  // Skip unused "parent dir" argument.
    while (i < argc) {
        const char* arg = argv[i++];
        if (strcmp(arg, "--zygote") == 0) {
            zygote = true;
            //zygote的進程名zygote64
            niceName = ZYGOTE_NICE_NAME;
        } else if (strcmp(arg, "--start-system-server") == 0) {
            //啟動system_server進程,也就是說zygote啟動后就去fork出system_server進程
            startSystemServer = true;
        } else if (strcmp(arg, "--application") == 0) {
            application = true;
        } else if (strncmp(arg, "--nice-name=", 12) == 0) {
            niceName.setTo(arg + 12);
        } else if (strncmp(arg, "--", 2) != 0) {
            className.setTo(arg);
            break;
        } else {
            --i;
            break;
        }
    }

    if (!niceName.isEmpty()) {
        //設置zygote的進程名
        runtime.setArgv0(niceName.string(), true /* setProcName */);
    }

    if (zygote) {
        runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
    } else if (className) {
        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.");
    }
}

3.4 AndroidRuntime.start()

代碼路徑:frameworks/base/core/jni/AndroidRuntime.cpp

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

    /* start the virtual machine */
    JniInvocation jni_invocation;
    jni_invocation.Init(NULL);
    JNIEnv* env;
    //啟動虛擬機
    if (startVm(&mJavaVM, &env, zygote, primary_zygote) != 0) {
        return;
    }
    onVmCreated(env);

    /*
     * Register android functions.注冊native方法
     */
    if (startReg(env) < 0) {
        ALOGE("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;

    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).string());
        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.
     */
    char* slashClassName = toSlashClassName(className != NULL ? className : "");
    jclass startClass = env->FindClass(slashClassName);
    if (startClass == NULL) {
        ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
        /* keep going */
    } else {
        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
            "([Ljava/lang/String;)V");
        if (startMeth == NULL) {
            ALOGE("JavaVM unable to find main() in '%s'\n", className);
            /* keep going */
        } else {
            //調(diào)用ZygoteInit的入口函數(shù)main
            env->CallStaticVoidMethod(startClass, startMeth, strArray);

#if 0
            if (env->ExceptionCheck())
                threadExitUncaughtException(env);
#endif
        }
    }
    free(slashClassName);

    ALOGD("Shutting down VM\n");
    if (mJavaVM->DetachCurrentThread() != JNI_OK)
        ALOGW("Warning: unable to detach main thread\n");
    if (mJavaVM->DestroyJavaVM() != 0)
        ALOGW("Warning: VM did not shut down cleanly\n");
}

說明:AndroidRuntime.start()主要做了三件事
1.注冊framework層的native方法以便jni調(diào)用,比如com_android_internal_os_ZygoteInit_nativeZygoteInit
2.啟動虛擬機
3.調(diào)用ZygoteInit.java 的main函數(shù),這個main一直會執(zhí)行或者阻塞,不會退出,這樣的話VM也不會退出

3.5 ZygoteInit.main()

代碼路徑ZygoteInit.java

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

           // Start profiling the zygote initialization.
           SamplingProfilerIntegration.start();

           boolean startSystemServer = false;
           String socketName = "zygote";
           String abiList = null;
           boolean enableLazyPreload = false;
           for (int i = 1; i < argv.length; i++) {
               if ("start-system-server".equals(argv[i])) {
                  //標識啟動system_server進程
                   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)) {
                   socketName = argv[i].substring(SOCKET_NAME_ARG.length());
               } else {
                   throw new RuntimeException("Unknown command line argument: " + argv[i]);
               }
           }
           if (abiList == null) {
               throw new RuntimeException("No ABI list supplied.");
           }
           //注冊一個socket server
           zygoteServer.registerServerSocket(socketName);
           // In some configurations, we avoid preloading resources and classes eagerly.
           // In such cases, we will preload things prior to our first fork.
          preload(bootTimingsTraceLog);

           // Finish profiling the zygote initialization.
           SamplingProfilerIntegration.writeZygoteSnapshot();

           // Do an initial gc to clean up after startup
           bootTimingsTraceLog.traceBegin("PostZygoteInitGC");
           gcAndFinalize();
           bootTimingsTraceLog.traceEnd(); // PostZygoteInitGC

           if (startSystemServer) {
              //啟動system_server進程 
               startSystemServer(abiList, socketName, zygoteServer);
           }

           Log.i(TAG, "Accepting command socket connections");
          //開始在while循環(huán)中監(jiān)聽來自AMS的fork子進程的請求,避免main退出
           zygoteServer.runSelectLoop(abiList);

           zygoteServer.closeServerSocket();
       } catch (Zygote.MethodAndArgsCaller caller) {
           caller.run();
       } catch (Throwable ex) {
           Log.e(TAG, "System zygote died with exception", ex);
           zygoteServer.closeServerSocket();
           throw ex;
       }
   }

說明:main主要做了三件事
1.preload 預加載
預加載framework中的類(/system/etc/
preloaded-classes)
預加載framework中的資源/system/framework/framework-res.apk
預加載動態(tài)庫libandroid.so,libjnigraphics.so等等
預加載動態(tài)庫libandroid.so,libjnigraphics.so等等
預加載默認字體
2.啟動system_server進程
3.注冊socket server并在循環(huán)中監(jiān)聽來自system_server的fork子進程的請求,

三 system_server進程的啟動

1.1 startSystemServer

private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer)
            throws Zygote.MethodAndArgsCaller, RuntimeException {
        String args[] = {
            "--nice-name=system_server",
            "--runtime-args",
            "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) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
            zygoteServer.closeServerSocket();
           //fork成功,處理system_server
            handleSystemServerProcess(parsedArgs);
        }
        return true;
    }

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

        if (parsedArgs.niceName != null) {
            //設置進程名
            Process.setArgV0(parsedArgs.niceName);
        }
            /*
             * Pass the remaining arguments to SystemServer.
             */
           //這里是被zygote進程fork出來的子進程做的一些初始化工作(主要是System_server進程和普通的app進程)
            ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
        /* should never reach here */
    }

1.2 ZygoteInit.zygoteInit

代碼路徑:ZygoteInit.java

 public static final void zygoteInit(int targetSdkVersion, String[] argv,
            ClassLoader classLoader) throws Zygote.MethodAndArgsCaller {
        if (RuntimeInit.DEBUG) {
            Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
        }

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
        RuntimeInit.redirectLogStreams();

        RuntimeInit.commonInit();
        //通過jni調(diào)用native的方法,在5.4 AndroidRuntime.start()中提過的,注冊了jni相關函數(shù)以便java端的調(diào)用,這里正好用到了
        ZygoteInit.nativeZygoteInit();
        RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
    }

說明:zygoteInit主要做了三件事
1.RuntimeInit.commonInit() 設置UncaughtExceptionhandler和UA,具體代碼比較簡單這里不列舉了
2.ZygoteInit.nativeZygoteInit() 調(diào)用native端的ZygoteInit(),這稍后再說
3.RuntimeInit.applicationInit 根據(jù)argv找到啟動類,并執(zhí)行入口main函數(shù),具體代碼比較簡單這里不列舉了(其實就是反射調(diào)用啦)

1.3 ZygoteInit.nativeZygoteInit()

代碼路徑frameworks/base/core/jni/AndroidRuntime.cpp

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

這個gCurRuntime實際就是5.3 app_main.cpp main中創(chuàng)建的appruntime ,可以查看todo_1標簽與之呼應

1.4 onZygoteInit()

代碼路徑frameworks/base/cmds/app_process/app_main.cpp

    virtual void onZygoteInit()
    {
        sp<ProcessState> proc = ProcessState::self();
        ALOGV("App process: starting thread pool.\n");
        proc->startThreadPool();
    }

說明:ProcessState是進程的狀態(tài),在構造函數(shù)時,會打開binder驅(qū)動做內(nèi)存映射,startThreadPool會啟動一個binder主線程,這樣system_server具備binder的能力也就是跨進程通信的能力,app進程也是這樣的,在創(chuàng)建成功后也會構造一個ProcessState,
另外我們可以看到zygote進程在啟動的過程中并沒有去創(chuàng)建ProcessState,所以zygote并沒有binder的能力,所以zygote與system_server通信時用的是socket,至于zygote為什么不用binder
待下回分解。
至此所有的流程分析完畢。

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容