Android系统启动流程 源码解析

Android系统启动流程

本文链接:https://blog.csdn.net/feather_wch/article/details/132518105

有道云脑图:https://note.youdao.com/s/GZ9d8vzO

1、整体流程

  1. Boot Room
  2. BootLoader
  3. idle
    1. kthread
    2. init
  4. init
    1. ServiceManager
    2. zygote
  5. zygote
    1. SystemServer
    2. app

一、init

1、kernel/common/init/main.c

kernel_init();
->try_to_run_init_process("/bin/init");
  ->run_init_process(filename)
    ->kernel_execve(filename, xxx, xxx);
      ->// 会执行init

2、andorid.mk->android.bp编译

// init/android.bp

cc_binary {
    name: "init_second_stage",
    stem: "init",
    static_libs: ["libinit"],
    srcs: ["main.cpp"], // main.cpp
    // ...
}

3、init是用户空间鼻祖

  1. 属于C、C++ Framework

1.1 启动源码

FirstStageMain()
 ->挂载文件系统
 ->重定向输入输出
SetupSelinux()
 ->初始化Selinux
SecondStageMain()
 ->初始化属性
 ->设置Selinux
 ->监听子进程终止信号
    ->epoll_ctl 注册监听SIGCHILD 避免僵尸进程
 ->启动属性服务,将sokcet,注册到epoll中
 ->匹配命令和函数
 ->解析init.rc
    ->构造解析器,对应于rc文件里面的service、on、import
    ->parser.ParseConfig:解析rc文件
        ->解析Dir
        ->解析File
            ->按照二进制格式,解析:servicemanager、zygote
 -> 循环执行脚本,epoll循环等待
    -> 执行脚本
// frameworks/core/core/init/main.cpp
int main(int argc, char** argv) {
    // 会反复进入

// 2、第二次进来,根据参数执行
    if (argc > 1) {
        if (!strcmp(argv[1], "subcontext")) {
            const BuiltinFunctionMap& function_map = GetBuiltinFunctionMap();
                // 5、内部while+poll,第四阶段
            return SubcontextMain(argc, argv, &function_map);
        }
    // 3、selinux:第二阶段
        if (!strcmp(argv[1], "selinux_setup")) {
            return SetupSelinux(argv);
        }
    // 4、第三阶段
        if (!strcmp(argv[1], "second_stage")) {
            return SecondStageMain(argc, argv);
        }
    }

// 1、首次进来:第一阶段
    return FirstStageMain(argc, argv);
}

// 第一阶段:
int FirstStageMain(int argc, char** argv) {
    if (REBOOT_BOOTLOADER_ON_PANIC) {
        InstallRebootSignalHandlers();
    }
    CHECKCALL(clearenv());
    CHECKCALL(setenv("PATH", _PATH_DEFPATH, 1));
// 1、挂载文件系统
    CHECKCALL(mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755"));
    CHECKCALL(mount("devpts", "/dev/pts", "devpts", 0, NULL));
    CHECKCALL(mount("sysfs", "/sys", "sysfs", 0, NULL));
    CHECKCALL(mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL));
    CHECKCALL(mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8)));
    CHECKCALL(mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9)));
    // null也是作为管道文件进行处理
    CHECKCALL(mknod("/dev/null", S_IFCHR | 0666, makedev(1, 3)));
    CHECKCALL(mkdir("/mnt/vendor", 0755));
    CHECKCALL(mkdir("/mnt/product", 0755));

// 2、重定向输入输出:stdio重定向Dev Null,作为管道文件,输入输出
    SetStdioToDevNull(argv);
    // 日志输出初始化
    InitKernelLogging(argv);
// 3、设置selinux安全策略:重新进入main.cpp
    const char* path = "/system/bin/init";
    const char* args[] = {path, "selinux_setup", nullptr};
    execv(path, const_cast(args)); // 执行

    return 1;
}
// Selinux:设置SeLinux安全策略,Android最小权限原则,selinux控制
int SetupSelinux(char** argv) {

    // 设置selinux
    SelinuxSetupKernelLogging();
    // selinux初始化
    SelinuxInitialize();
    // 重新进入第二阶段
    const char* path = "/system/bin/init";
    const char* args[] = {path, "second_stage", nullptr};
    execv(path, const_cast(args));
    return 1;
}

// frameworks/core/core/init.coo
int SecondStageMain(int argc, char** argv) {

    // Set init and its forked children's oom_adj.
    if (auto result = WriteFile("/proc/1/oom_score_adj", StringPrintf("%d", DEFAULT_OOM_SCORE_ADJUST));
        !result.ok()) {
        LOG(ERROR) << "Unable to write " << DEFAULT_OOM_SCORE_ADJUST
                   << " to /proc/1/oom_score_adj: " << result.error();
    }

// 1. 初始化属性:加载属性
    PropertyInit();

    // Mount extra filesystems required during second stage init
    MountExtraFilesystems();

// 2. Selinux相关
    SelinuxSetupKernelLogging();
    SelabelInitialize();
    SelinuxRestoreContext();

    Epoll epoll; // ===============================================================================> epoll
    if (auto result = epoll.Open(); !result.ok()) {
        PLOG(FATAL) << result.error();
    }
// 3. 监听子进程中止信号:避免僵尸进程 ==============================================================> 僵尸进程
    InstallSignalFdHandler(&epoll);
    InstallInitNotifier(&epoll);
// 4. 启动属性服务
    StartPropertyService(&property_fd);

    SetUsbController();

// 5. 匹配命令和函数的关系:mount等命令都对应于函数
    const BuiltinFunctionMap& function_map = GetBuiltinFunctionMap();
    Action::set_function_map(&function_map);

// 6. 解析 init.rc
    LoadBootScripts(am, sm);

// 7. while循环解析脚本:启动zygote、执行重启
    while (true) {
        // 解析start等命令
        am.ExecuteOneCommand();
        // epoll_wait循环等待 ===================================================================> Handler中Looper.loop
        auto pending_functions = epoll.Wait(epoll_timeout);
    }

    return 0;
}

// >>>>>>>>>>>>>>>>>>>>>>>>>>
//在linux当中,父进程是通过捕捉SIGCHLD信号来得知子进程运行结束的情况,
//SIGCHLD信号会在子进程终止的时候发出
//函数的作用就是,接收到SIGCHLD信号时触发HandleSignalFd进行信号处理
// 这样可以在当子进程发出信号后能够及时的将它销毁,避免僵尸进程的存在
static void InstallSignalFdHandler(Epoll* epoll) {


    const struct sigaction act { .sa_handler = SIG_DFL, .sa_flags = SA_NOCLDSTOP };
    sigaction(SIGCHLD, &act, nullptr);

    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGCHLD); //SIGCHLD

    signal_fd = signalfd(-1, &mask, SFD_CLOEXEC);
    // 注册,epoll注册handler。 ===========================> epoll_ctl EPOLL_CTL_ADD
    if (auto result = epoll->RegisterHandler(signal_fd, HandleSignalFd); !result.ok()) {
        LOG(FATAL) << result.error();
    }
}
    // 注册,epoll注册handler。 ===========================> epoll_ctl EPOLL_CTL_ADD
Result Epoll::RegisterHandler(int fd, std::function handler, uint32_t events) {
    epoll_event ev;
    ev.events = events;
    ev.data.ptr = reinterpret_cast(&it->second);
    if (epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &ev) == -1) {
        epoll_handlers_.erase(fd);
        return result;
    }
    return {};
}

// >>>>>>>>>>>>>>>>>>> 启动属性服务,注册到epoll中
void StartPropertyService(int* epoll_socket) {
    InitPropertySet("ro.property_service.version", "2");

    int sockets[2];
    if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != 0) {
        PLOG(FATAL) << "Failed to socketpair() between property_service and init";
    }
    *epoll_socket = from_init_socket = sockets[0];
    init_socket = sockets[1];
    StartSendingMessages();

    if (auto result = CreateSocket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, false, 0666, 0, 0, {});
        result.ok()) {
        property_set_fd = *result;
    }

    listen(property_set_fd, 8);

    auto new_thread = std::thread{PropertyServiceThread};
    property_service_thread.swap(new_thread);
}


init.rc解析

// 解析init.rc
static void LoadBootScripts(ActionManager& action_manager, ServiceList& service_list) {
    // 1、创建对应解析器 service、on、import
    Parser parser = CreateParser(action_manager, service_list);

    // 2、解析init.rc init.rc里面有zygote等等
    std::string bootscript = GetProperty("ro.boot.init_rc", "");
    if (bootscript.empty()) {
        parser.ParseConfig("/system/etc/init/hw/init.rc");
        if (!parser.ParseConfig("/system/etc/init")) {
            late_import_paths.emplace_back("/system/etc/init");
        }
        parser.ParseConfig("/system_ext/etc/init");
        if (!parser.ParseConfig("/product/etc/init")) {
            late_import_paths.emplace_back("/product/etc/init");
        }
        if (!parser.ParseConfig("/odm/etc/init")) {
            late_import_paths.emplace_back("/odm/etc/init");
        }
        if (!parser.ParseConfig("/vendor/etc/init")) {
            late_import_paths.emplace_back("/vendor/etc/init");
        }
    } else {
        parser.ParseConfig(bootscript);
    }
}
// 根据rc文件的内容,创建对应解析器 
Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) {
    Parser parser;
    parser.AddSectionParser("service", std::make_unique(&service_list, GetSubcontext(), std::nullopt));
    parser.AddSectionParser("on", std::make_unique(&action_manager, GetSubcontext()));
    parser.AddSectionParser("import", std::make_unique(&parser));

    return parser;
}

// frameworks/core/core/init/parse.cpp
// 解析
bool Parser::ParseConfig(const std::string& path) {
    if (is_dir(path.c_str())) {
        return ParseConfigDir(path); // 目录 -> ParseConfigFile
    }
    return ParseConfigFile(path); // 文件
}
bool Parser::ParseConfigFile(const std::string& path) {
    // 解析数据
    ParseData(path, &config_contents.value());
    return true;
}

// 根据二进制格式要求,解析数据
void Parser::ParseData(const std::string& filename, std::string* data) {
    for (;;) {
        switch (next_token(&state)) {
            case T_EOF:
                // ...
                return;
            case T_NEWLINE: {
                // ...
                break;
            }
            case T_TEXT:
                args.emplace_back(state.text);
                break;
        }
    }
}

1.2 init.rc文件

import /system/etc/init/hw/init.${ro.zygote}.rc

on init

    # Mount binderfs
    mkdir /dev/binderfs
    mount binder binder /dev/binderfs stats=global
    chmod 0755 /dev/binderfs

    symlink /dev/binderfs/binder /dev/binder
    symlink /dev/binderfs/hwbinder /dev/hwbinder
    symlink /dev/binderfs/vndbinder /dev/vndbinder

    # Start essential services.
    start servicemanager
    start hwservicemanager
    start vndservicemanager

on late-init
    # Now we can start zygote for devices with file based encryption
    trigger zygote-start

on zygote-start && property:ro.crypto.state=unencrypted
    # A/B update verifier that marks a successful boot.
    exec_start update_verifier_nonencrypted
    start statsd
    start netd
    start zygote
    start zygote_secondary

二、ServiceManager

ServiceManager启动流程:见Binder部分。

main()
->1.初始化Binder驱动,加载"/dev/binder"
->2.实例化ServiceManager,并将自己作为第一个服务,进行添加注册
->3.将自己设置为IPCThreadState的contextobject,也就是设置服务端的BBinder对象
->4.利用Looper,也就是底层epoll处理事务,设置BinderCallback监听(epoll_ctl),无限等待
->5.while() // Binder驱动遇到事件,会回调handleEvent

三、Zygote

3.1 rc解析

// 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
    socket usap_pool_primary stream 660 root system
 # zygote被关闭就会重启Android操作系统 
    onrestart exec_background - system system -- /system/bin/vdc volume abort_fuse
    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
// frameworks/base/cmds/app_process/Android.bp
cc_binary {
    name: "app_process",
    srcs: ["app_main.cpp"] // 指明代码为app_main.cpp
}

3.2 启动:app_main.cpp

AppRuntime

class AppRuntime : public AndroidRuntime
{
public:
    AppRuntime(char* argBlockStart, const size_t argBlockLength): AndroidRuntime(argBlockStart, argBlockLength), mClass(NULL){}

    void setClassNameAndArgs(const String8& className, int argc, char * const *argv) {
        mClassName = className;
        for (int i = 0; i < argc; ++i) {
             mArgs.add(String8(argv[i]));
        }
    }

    virtual void onVmCreated(JNIEnv* env)
    {
        if (mClassName.isEmpty()) {
            return; // Zygote. Nothing to do here.
        }

        char* slashClassName = toSlashClassName(mClassName.string());
        mClass = env->FindClass(slashClassName);
        if (mClass == NULL) {
            ALOGE("ERROR: could not find class '%s'\n", mClassName.string());
        }
        free(slashClassName);

        mClass = reinterpret_cast(env->NewGlobalRef(mClass));
    }

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

        AndroidRuntime* ar = AndroidRuntime::getRuntime();
        ar->callMain(mClassName, mClass, mArgs);

        IPCThreadState::self()->stopProcess();
        hardware::IPCThreadState::self()->stopProcess();
    }

// nativeZygoteInit调用时,被JNI中转到这里。
    virtual void onZygoteInit()
    {
        sp proc = ProcessState::self(); // 1、初始化ProcessState(初始化Binder驱动)
        ALOGV("App process: starting thread pool.\n");
        proc->startThreadPool(); // 2、创建Binder线程池,底层一路到IPCThreadState::self()->joinThreadPool();
    }

    virtual void onExit(int code)
    {
        if (mClassName.isEmpty()) {
            // if zygote
            IPCThreadState::self()->stopProcess();
            hardware::IPCThreadState::self()->stopProcess();
        }

        AndroidRuntime::onExit(code);
    }


    String8 mClassName;
    Vector mArgs;
    jclass mClass;
};

main

1、app_main.cpp 启动Zygote或者正常app流程 ->目录frameworks\base\cmds\app_process\

// 核心:根据init.zygote64.rc里面配置的参数,--zygote和--start-system-server,启动zygote,systemserver作为参数传入,以后启动
int main(int argc, char* const argv[])
{
    /**========================
     * 1、根据rc配置,解析出需要启动zygote,并且在zygote启动后,
     *========================*/
    AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
    // 解析传入的参数 -Xzygote /system/bin --zygote --start-system-server
    int i;
    for (i = 0; i < argc; i++) {
        // 参数解析
        runtime.addOption(strdup(argv[i]));
    }

    // 判断是zygote还是app
    bool zygote = false;
    bool startSystemServer = false; // 用于存入参数
    bool application = false; // app
    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;
            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.setTo(arg + 12);
        } else if (strncmp(arg, "--", 2) != 0) {
            className.setTo(arg);
            break;
        } else {
            --i;
            break;
        }

    }
    Vector args;
    if (!className.isEmpty()) {
        // 非zygote模式,存入application启动相关参数
        args.add(application ? String8("application") : String8("tool"));
        runtime.setClassNameAndArgs(className, argc - i, argv + i);

    } else {
        // zygote模式,将systemserver和其他剩余参数,都一次性放入

        if (startSystemServer) {
            args.add(String8("start-system-server"));
        }
        String8 abiFlag("--abi-list=");
        abiFlag.append(prop);
        args.add(abiFlag);
        // In zygote mode, pass all remaining arguments to the zygote
        // main() method.
        for (; i < argc; ++i) {
            args.add(String8(argv[i]));
        }
    }

    /**===============================================
     * 2、启动zygote(systemserver等内容作为参数传入)
     *=====================================================*/

    //  启动zygote的java层调用
    if (zygote) {
        zygote 为true 表示正在启动的进程为zygote进程
        //由此可知app_main.cpp在zygote启动其他进程的时候都会通过main()方法
        //这里启动的是zygote进程调用runtime start()方法 传入参数
        runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
    } else if (className) {  //这个地方是用于启动app的 // application = true时,会解析。
        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.");
    }
}

2、AndroidRuntime.cpp ->目录frameworks\base\core\jni\

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

    // 创建虚拟机
    if (startVm(&mJavaVM, &env, zygote, primary_zygote) != 0) { // heapsize默认16MB,也在这里面设置
        return;
    }    
    // 注册JNI
    if (startReg(env) < 0) {
        return;
    }
    // 反射调用main方法(进入ZygoteInit.java的main()方法) ==============================> JNI反射
    char* slashClassName = toSlashClassName(className != NULL ? className : "");
    jclass startClass = env->FindClass(slashClassName);

    jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
"([Ljava/lang/String;)V");

    env->CallStaticVoidMethod(startClass, startMeth, strArray);
}
JNI注册

AndroidRuntime.cpp中注册了所有JNI

/*static*/ int AndroidRuntime::startReg(JNIEnv* env)
{
    if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
        env->PopLocalFrame(NULL);
        return -1;
    }
}

// 循环执行数组里面的mProc()方法
static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
{
    for (size_t i = 0; i < count; i++) {
        if (array[i].mProc(env) < 0) {
            return -1;
        }
    }
    return 0;
}

#define REG_JNI(name)      { name, #name }
struct RegJNIRec {
    int (*mProc)(JNIEnv*); // mProc函数指针 ============================================> Kotlin函数引用
    const char* mName;
};

// 数组存放了所有JNI对应关系

static const RegJNIRec gRegJNI[] = {
        REG_JNI(register_com_android_internal_os_RuntimeInit), //REG_JNI是RegJNIRec结构体的别名
        REG_JNI(register_com_android_internal_os_ZygoteInit_nativeZygoteInit),
        ...
}

// REG_JNI是将函数名,作为函数指针mProc的内容,后续直接mProc(env)进行调用
int register_com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env)
{
    // JNI动态注册,绑定nativeZygoteInit Java方法 和 底层方法 com_android_internal_os_ZygoteInit_nativeZygoteInit
    const JNINativeMethod methods[] = {
        { "nativeZygoteInit", "()V",
            (void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
    };
    return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
        methods, NELEM(methods));
}
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
    //gCurRuntime是app_main.cpp中的class AppRuntime : public AndroidRuntime,实现了onZygoteInit()方法
    gCurRuntime->onZygoteInit();
}

3.3 ZygoteInit

3、ZygoteInit.java ->目录frameworks\base\cor\java\com\android\internal\os\


public static void main(String argv[]) {
    //step1 重要的函数 preload
    preload(bootTimingsTraceLog);
    //Step2 重要函数 创建socket服务
    zygoteServer = new ZygoteServer(isPrimaryZygote);  

   if (startSystemServer) {
        //Step3 重要函数 Zygote Fork出的第一个进程 system_server
        Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
        r.run(); // r: ZygoteInit.zygoteInit
        return;
   }
   //Step4 重要函数 循环等待fork出其他的应用进程,比如Launcher,比如app
   caller = zygoteServer.runSelectLoop(abiList);
   //执行返回的Runnable对象,进入子进程
   caller.run();
      
}

preload

    static void preload(TimingsTraceLog bootTimingsTraceLog) {
        preloadClasses();// 加载系统类
        preloadResources();// 加载系统资源
        nativePreloadAppProcessHALs();
        maybePreloadGraphicsDriver();
        preloadSharedLibraries();// 加载一些共享so库,其实就三个:android、compiler_rt、jnigraphics
        preloadTextResources();// 加载字体资源
        WebViewFactory.prepareWebViewInZygote();// 加载webview相关资源
        warmUpJcaProviders();// 初始化JCA安全相关的参数
    }

预加载资源

1、preloadClasses()

"/system/etc/preloaded-classes"
// 会预加载上述文件中的类
// 例如:SurfaceView、TextView、View等等

2、preloadResources()

// 预加载如 com.android.internal.R.xxx 资源
"frameworks/base/core/res/values/arrays.xml"...

ZygoteServer

创建
// 创建ZygoteServer的本质就是创建LocalServerSocket
static void main(){
    zygoteServer = new ZygoteServer(isPrimaryZygote);  
}
// ZygoteServer.java frameworks\base\core\java\com\android\internal\os\ZygoteServer.java

    ZygoteServer(boolean isPrimaryZygote) {
        // 初始化,创建Socket
        mZygoteSocket = Zygote.createManagedSocketFromInitSocket(Zygote.PRIMARY_SOCKET_NAME);

    }

    static LocalServerSocket createManagedSocketFromInitSocket(String socketName) {
        return new LocalServerSocket(fd);// =======================================================================>LocalServerSocket
    }

创建连接

AMS会创建连接 ==========> AMS

处理事务

1、ZygoteServer源码

  1. poll机制,多路复用
  2. 处理客户端连接请求
  3. 处理数据处理请求:processOneCommand
  Runnable runSelectLoop(String abiList) {
        //mZygoteSocket 是socket通信中的服务端,即zygote进程。保存到socketFDs[0]
        socketFDs.add(mZygoteSocket.getFileDescriptor());
        while (true) {
            // Step 1:Poll机制,IO多路复用。没有事件到来就阻塞
            // 1. 每次循环,都重新创建需要监听的pollFds。并且关注事件:POLLIN
            StructPollfd[] pollFDs;
            for (FileDescriptor socketFD : socketFDs) {
                pollFDs[pollIndex].events = (short) POLLIN; // 关注事件的到来
            }
            // 2. Poll机制:处理轮询状态,当pollFds有事件到来则往下执行,否则阻塞在这里
            pollReturnValue = Os.poll(pollFDs, pollTimeoutMs); // ===================================================================================>Poll
            while (--pollIndex >= 0) {
                // Step 2:处理 客户端发出连接请求
                if (pollIndex == 0) { // 意味着有客户端连接请求
                    ZygoteConnection newPeer = acceptCommandPeer(abiList);// 则创建ZygoteConnection对象,并添加到socketFDs。
                    peers.add(newPeer); //  加入到peers和socketFDs,下一次也开始监听
                    socketFDs.add(newPeer.getFileDescriptor());
                }
                // Step 3:处理 数据处理请求
                else if (pollIndex < usapPoolEventFDIndex) {
                    //pollIndex>0,则代表通过socket接收来自对端的数据,并执行相应操作
                    ZygoteConnection connection = peers.get(pollIndex);
                    ///重要细节///
                    //  进行进程的处理:创建进程
                    final Runnable command = connection.processOneCommand(this);
                    // TODO (chriswailes): Is this extra check necessary?
                    if (mIsForkChild) {
                        return command; // child
                    } else {
                        socketFDs.remove(pollIndex);//处理完则从socketFDs中移除该文件描述符
                    }
                    
                }
            }
        }
    }


// 接受客户端连接
    private ZygoteConnection acceptCommandPeer(String abiList) {
        // 用LocalSocket建立连接
        return createNewConnection(mZygoteSocket.accept(), abiList);
    }
    protected ZygoteConnection createNewConnection(LocalSocket socket, String abiList){
        return new ZygoteConnection(socket, abiList);
    }
    // 初始化输入输出流 BIO
    ZygoteConnection(LocalSocket socket, String abiList) throws IOException { // =================================>Java BIO
        mSocket = socket;
        this.abiList = abiList;

        mSocketOutStream = new DataOutputStream(socket.getOutputStream());
        mSocketReader =
                new BufferedReader( // ============================> 装饰者模式
                        new InputStreamReader(socket.getInputStream()), Zygote.SOCKET_BUFFER_SIZE);

        mSocket.setSoTimeout(CONNECTION_TIMEOUT_MILLIS);
        peer = mSocket.getPeerCredentials();

        isEof = false;
    }

2、ZygoteServer和select、poll、epoll

  1. select <= Andorid 5.0,使用复杂,最大1024FD
  2. poll >= Android 6.0,取消FD数量限制

3、为什么使用poll,不使用epoll?

  1. fork进程频率远不如Handler的Looper,epoll在低并发场景下并没有特别优势
  2. epoll还需要维护事件队列,没有必要
poll

Title
死磕epoll

四、SystemServer

1、是什么

  1. 是独立进程
  2. 管理服务(90+)

4.0 forkSystemServer

forkSystemServer()
->nativeFork()->fork()
->ZygoteInit.zygoteInit()
  ->Runtime.commonInit // 初始化运行时环境
    ->设置异常处理器KillApplicationHandler
  ->ZygoteInit.nativeZygoteInit // JNI注册时,可以发现通过JNI转到了AppRuntime的onZygoteInit回调
    ->构造ProcessSate::self()
        ->open_driver
            ->初始化Binder驱动
            ->设置最大线程数15
        ->mmap 1024-8kb
    ->通过IPCThreadState启动Binder线程池
  ->main()

1、fork出SystemServer
ZygoteInit.java ->目录frameworks\base\core\java\com\android\internal\os\

private static Runnable forkSystemServer(String abiList, String socketName,
            ZygoteServer zygoteServer) {
        int pid = Zygote.forkSystemServer(
                    parsedArgs.mUid, parsedArgs.mGid,
                    parsedArgs.mGids,
                    parsedArgs.mRuntimeFlags,
                    null,
                    parsedArgs.mPermittedCapabilities,
                    parsedArgs.mEffectiveCapabilities);

        // 子进程继续处理
        if (pid == 0) { 
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
            zygoteServer.closeServerSocket();
            return handleSystemServerProcess(parsedArgs);
        }
        // 父进程什么也不做
        return null;
}

2、Zygote.java frameworks\base\core\java\com\android\internal\os\Zygote.java

    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);

        return pid;
    }

// 核心作用:调用底层fork()
    private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
            int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);

3、ZygoteInit.java frameworks\base\core\java\com\android\internal\os\

private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) 
    // pathclassloader
    ClassLoader cl = createPathClassLoader(systemServerClasspath, parsedArgs.mTargetSdkVersion); // ===============================> PathClassLoader

    return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
                    parsedArgs.mDisabledCompatChanges,
                    parsedArgs.mRemainingArgs, cl);
}

// 双亲委派,用BootClassLoader构造PathClassLoader,传入库路径:"java.library.path"
    static ClassLoader createPathClassLoader(String classPath, int targetSdkVersion) {
        String libraryPath = System.getProperty("java.library.path");
        ClassLoader parent = ClassLoader.getSystemClassLoader().getParent(); // We use the boot class loader, that's what the runtime expects at AOT.
        return ClassLoaderFactory.createClassLoader(classPath, libraryPath, libraryPath,parent, targetSdkVersion, true /* isNamespaceShared */, null /* classLoaderName */);
    }

4、ZygoteInit.java frameworks\base\core\java\com\android\internal\os\

    public static final Runnable zygoteInit(xxx) {
        //1. 初始化运行环境
        RuntimeInit.commonInit();//初始化运行环境 
        //2. 启动Binder ,方法在 androidRuntime.cpp中注册       
        ZygoteInit.nativeZygoteInit();
        //3. 通过反射创建程序入口函数的 Method 对象,并返回 Runnable 对象
        // ActivityThread.main
        return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv, classLoader);
    }

    protected static Runnable applicationInit(xxx, ClassLoader classLoader) {
        // startClass: 如果AMS通过socket传递过来的是 ActivityThread
        return findStaticMain(args.startClass, args.startArgs, classLoader);
    }

4.1 commonInit

framworks\base\core\java\com\android\internal\os\

    protected static final void commonInit() {
        if (DEBUG) Slog.d(TAG, "Entered RuntimeInit!");

//1、设置异常处理器:
// 1. 设置未捕获异常的预处理器(pre-handler)为 LoggingHandler,用于处理未捕获的异常日志。
// 2. 设置默认的未捕获异常处理器为 KillApplicationHandler,用于处理应用程序崩溃并终止应用。 =========================> ANR KillApplicationHandler
        LoggingHandler loggingHandler = new LoggingHandler();
        RuntimeHooks.setUncaughtExceptionPreHandler(loggingHandler);
        Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler));

//2、设置日志管理器
        LogManager.getLogManager().reset();
        new AndroidConfig();

//3、关联套接字标记和流量统计:
        NetworkManagementSocketTagger.install();
// 省略
        initialized = true;
    }

4.2 main()

SystemServer.java

    public static void main(String[] args) {
        new SystemServer().run(); // 构造SystemServer执行run方法
    }

    private void run() {
        /**=====================================
         * 1、startService之前的准备工作
         *=======================================*/
        TimingsTraceAndSlog t = new TimingsTraceAndSlog();
        try {
            // Binder线程池 线程数量 -> 31
            BinderInternal.setMaxThreads(sMaxBinderThreads);
            // 线程优先级
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);
            android.os.Process.setCanSelfBackground(false);
        // STEP 1: 主线程Looper =================================================> Handler
            Looper.prepareMainLooper();

            // load android_servers.so // 服务相关
            System.loadLibrary("android_servers");

        // STEP 2: 创建SystemServer的Context,用于黑白屏的启动
            createSystemContext();

        // STEP 3: 构造SystemServiceManager并且添加到本地服务中。系统服务(SystemServer)的管理者
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            // 添加到LocalServices
            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
            // 启动SystemServer内部线程池:mService = ConcurrentUtils.newFixedThreadPool
            SystemServerInitThreadPool.start(); // 
            // JVMTI相关
            if (Build.IS_DEBUGGABLE) {
                // Property is of the form "library_path=parameters".
                String jvmtiAgent = SystemProperties.get("persist.sys.dalvik.jvmtiagent");
                int equalIndex = jvmtiAgent.indexOf('=');
                String libraryPath = jvmtiAgent.substring(0, equalIndex);
                String parameterList =jvmtiAgent.substring(equalIndex + 1, jvmtiAgent.length());
                Debug.attachJvmtiAgent(libraryPath, parameterList, null);
            }
        } finally {
            t.traceEnd();  // InitBeforeStartServices
        }

        /**=====================================
         * 2、startService
         *=======================================*/
        // STEP 4: 启动各类服务
            startBootstrapServices(t);
            startCoreServices(t);
            startOtherServices(t);

        // STEP 5: loop 无限循环
        Looper.loop();
    }

createSystemContext()

// SystemServer.java :attach(创建Context和Application执行onCreate)、设置主题
    private void createSystemContext() {
        // 1、attach,参数一 system:true
        ActivityThread activityThread = ActivityThread.systemMain();
        mSystemContext = activityThread.getSystemContext();
        // 2、设置主题
        mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
        final Context systemUiContext = activityThread.getSystemUiContext();
        systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
    }
// ActivityThread.java-attach
    public static ActivityThread systemMain() {
        ActivityThread thread = new ActivityThread();
        thread.attach(true, 0); // system:true startSeq:0
        return thread;
    }
// ActivityThread.java: context和application+onCreate
    private void attach(boolean system, long startSeq) {
        mSystemThread = system;
        if (system) {
            mInstrumentation = new Instrumentation();
            mInstrumentation.basicInit(this);
            // 1、创建系统的ContextImpl
            ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
            // 2、构造Applicaiton,执行onCreate
            mInitialApplication = context.mPackageInfo.makeApplication(true, null);
            mInitialApplication.onCreate();
        
        }
    }

BinderInternal.setMaxThreads

BinderInternal.setMaxThreads(sMaxBinderThreads);

// 增加SystemServer的binder线程池中线程数量,15---->31
// JNI转给ProcessState
status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
    status_t result = NO_ERROR;
    // ioctl
    if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
        mMaxThreads = maxThreads;
    }
    return result;
}

LocalServices

LocalServices

// ArrayMap  key=服务.class, value=服务对象                ====================================================> ArrayMap
    private static final ArrayMap<Class<?>, Object> sLocalServiceObjects = new ArrayMap<Class<?>, Object>();
    public static <T> void addService(Class<T> type, T service) {
        synchronized (sLocalServiceObjects) { // =================================>synchronized
            if (sLocalServiceObjects.containsKey(type)) {
                throw new IllegalStateException("Overriding service registration");
            }
            sLocalServiceObjects.put(type, service);
        }
    }

4.3 startServices

    private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
        t.traceBegin("startBootstrapServices");

        // WatchDog SystemServer可能crash =========================> crash、anr
        t.traceBegin("StartWatchdog");
        final Watchdog watchdog = Watchdog.getInstance();
        watchdog.start();

        // 等待安装完成,安装好后创建/data/user目录(需要先启动)
        t.traceBegin("StartInstaller");
        Installer installer = mSystemServiceManager.startService(Installer.class);
        t.traceEnd();

        // ATMS
        // MAS
        t.traceBegin("StartActivityManager");
        ActivityTaskManagerService atm = mSystemServiceManager.startService(
                ActivityTaskManagerService.Lifecycle.class).getService(); //启动atms
        mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                mSystemServiceManager, atm); // 启动AMS
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
        mWindowManagerGlobalLock = atm.getGlobalLock();
        t.traceEnd();


        // PwerManager
        t.traceBegin("StartPowerManager");
        mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
        t.traceEnd();

        // 需要reboot是提供recoery服务
        t.traceBegin("StartRecoverySystemService");
        mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);
        t.traceEnd();

        // LED服务,灯服务
        t.traceBegin("StartLightsService");
        mSystemServiceManager.startService(LightsService.class);
        t.traceEnd();

        // Display服务,用于提供display metrics
        t.traceBegin("StartDisplayManager");
        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
        t.traceEnd();

        // PKMS
        t.traceBegin("StartPackageManagerService");
        try {
            Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
            mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                    mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
        } finally {
            Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
        }

        // User管理
        t.traceBegin("StartUserManagerService");
        mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
        t.traceEnd();

         // 没有加密,otadexopt
        if (!mOnlyCore) {
            boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
                    false);
            if (!disableOtaDexopt) {
                t.traceBegin("StartOtaDexOptService");
                try {
                    Watchdog.getInstance().pauseWatchingCurrentThread("moveab");
                    OtaDexoptService.main(mSystemContext, mPackageManagerService);
                } catch (Throwable e) {
                    reportWtf("starting OtaDexOptService", e);
                } finally {
                    Watchdog.getInstance().resumeWatchingCurrentThread("moveab");
                    t.traceEnd();
                }
            }
        }

        // 核心内容,为app进程安排系统进程的以便后期监控
        t.traceBegin("SetSystemProcess");
        mActivityManagerService.setSystemProcess();
        t.traceEnd();

        t.traceEnd(); // startBootstrapServices
    }
  • 不需要Binder通信的,比如电源服务,可以直接继承SystemService

SystemServiceManager.startService

// SystemServiceManager.java
    public SystemService startService(String className) {
        // Class.forName
        final Class<SystemService> serviceClass = loadClassFromLoader(className, this.getClass().getClassLoader());
        return startService(serviceClass);
    }

    public <T extends SystemService> T startService(Class<T> serviceClass) {
        // 反射构造
            final String name = serviceClass.getName();
            final T service;
            Constructor<T> constructor = serviceClass.getConstructor(Context.class);
            service = constructor.newInstance(mContext);

            startService(service);
            return service;  
    }

    private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
    public void startService(@NonNull final SystemService service) {
// 1、添加到ArrayList中
        mServices.add(service);
// 2、执行SystemService接口的onStart()方法
        long time = SystemClock.elapsedRealtime();
        try {
            service.onStart();
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
        warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
    }

// xxxService: 如BatteryService.java
    public void onStart() {
        mBinderService = new BinderService();
        // 是SystemService接口,发布到ServiceManager中
        publishBinderService("battery", mBinderService);
        mBatteryPropertiesRegistrar = new BatteryPropertiesRegistrar();
        publishBinderService("batteryproperties", mBatteryPropertiesRegistrar);
        publishLocalService(BatteryManagerInternal.class, new LocalService());
    }
// ServiceManager.addService()
    protected final void publishBinderService(String name, IBinder service,
            boolean allowIsolated, int dumpPriority) {
        ServiceManager.addService(name, service, allowIsolated, dumpPriority);
    }

答疑

1、挂载是什么意思?

  1. U盘插入,会绑定到一个文件,才能看到

2、先分配进程还是先分配虚拟机?

  1. 先分配进程
  2. 再分配虚拟机:虚拟机是一段代码,并且实现了内存管理

3、孤儿进程是什么?

  1. 父进程先退出
  2. 子进程还没有退出
  3. 会托孤给init进程(任何一个进程都必须有父进程)

4、僵尸进程

  1. 子进程先退出
  2. 父进程还没有退出
  3. 子进程必须等待父进程捕获子进程的退出状态,子进程会变成僵尸进程(只保留一部分退出信息,等着父进程查询)

5、子进程和父进程的区别

  1. 除了文件锁以外,其他锁都会被继承 ========================>mmkv

6、Zygote的native为什么要启动虚拟机?

  1. 要跑Java代码就需要JVM
  2. 需要做预处理工作,不然都交给App进程去做,太慢了。
  3. 所有进程时Zygote fork出来的,因此JVM、预加载的东西都会被fork出来。
  4. 如果zygote是多线程的,fork出来的东西没什么用。

7、车载中需要增加一个系统服务帮助其他模块之间通信,需要增加fdbus

  1. 增加系统服务
  2. 修改init
  3. 修改selinux

自我检测

  1. nativeZygoteInit是谁调用的?
  2. nativeZygoteInit的作用是什么?
  3. IPCThreadState的作用是什么?

你可能感兴趣的:(Android,android)