关于android:Android系统Launcher启动流程

59次阅读

共计 70718 个字符,预计需要花费 177 分钟才能阅读完成。

本文基于 android13-release 源码浏览整顿

零碎源码地址:init.h – Android Code Search

前言

以往咱们开发 Android 利用都在零碎桌面点击关上,但桌面 Launcher 过程是如何加载并展现利用窗口未能深刻理解,由此去窥探 Android 零碎整体启动流程以加深对 Android 开发体系的了解

1.Android 系统启动外围流程

  • 当开机键按下时 Boot Rom 激活并加载疏导程序 BootLoader 到 RAM
  • 启动 kernal swapper 过程(idle)pid=0
  • 初始化过程治理,内存治理
  • 加载 Binder\Display\Camera Driver
  • 创立 kthreadd 过程(pid=2), 初始化内核工作线程 kworkder, 中断线程 ksoftirad, 内核守护过程 thermal
  • 创立 init 过程

2.init 过程源码解析

2.1 init 过程

性能如下:

  • 解析 init.rc 配置文件,首先开启 ServiceManager 和 MediaServer 等要害过程
  • init 过程 fork 启动 Zygote 服务过程
  • 解决子过程的终止(signal 形式)
  • 提供属性服务的性能

源码文件门路 : system/core/init/main.cpp)

int main(int argc, char** argv) {
    ...
    // 设置过程和用户的过程执行优先级
    setpriority(PRIO_PROCESS, 0, -20);
    //init 过程创立 ueventd 子过程解决设施节点文件,通过 ColdBoot.Run()办法冷启动
    // 具体细节地位:/system/core/init/ueventd.cpp
    if (!strcmp(basename(argv[0]), "ueventd")) {return ueventd_main(argc, argv);
    }
    if (argc > 1) {if (!strcmp(argv[1], "subcontext")) {
        // 内核日志初始化,文件地位:/system/libbase/logging.cpp
        //[logging.cpp - Android Code Search](https://cs.android.com/android/platform/superproject/+/android13-release:system/libbase/logging.cpp;drc=715a186b5d8903d30c25299ed0ecff0e2e9fbb9c;bpv=1;bpt=1;l=337?hl=zh-cn)
            android::base::InitLogging(argv, &android::base::KernelLogger);
            // 文件地位:/system/core/init/builtins.cpp,获取内核函数传递给“subcontext”const BuiltinFunctionMap& function_map = GetBuiltinFunctionMap();
            //subcontext 过程
            return SubcontextMain(argc, argv, &function_map);
        }
        if (!strcmp(argv[1], "selinux_setup")) {return SetupSelinux(argv);
        }
        if (!strcmp(argv[1], "second_stage")) {return SecondStageMain(argc, argv);
        }
    }
    return FirstStageMain(argc, argv);
}

2.2 过程优先级

setpriority(PRIO_PROCESS, 0, -20);

设置过程和用户的过程执行优先级, 源码地位 : bionic/libc/include/sys/resource.h

int getpriority(int __which,id_t __who);
int setpriority(int __which,id_t __who,int __priority);
  • int __which : 三个类别可选,PRIO_PROCESS(标记具体过程)、PRIO_PGRP(标记过程组)、PRIO_USER(标记用户过程,通过 user id 辨别)
  • id_t __who : 与 which 类别一一对应,别离标记上述类别 id
  • int __priority : 优先级范畴 -20~19,值越小优先级越高

运行 adb shell 查看过程 nice 值

adb shell top

2.3 FirstStageMain

代码地位:system/core/init/first_stage_init.cpp, 次要是创立挂载相干文件目录

int FirstStageMain(int argc, char** argv) {
    // 初始化重启零碎的解决信号, 通过 sigaction 注册新号并监听, 源码地位:system/core/init/reboot_utils.cpp
    if (REBOOT_BOOTLOADER_ON_PANIC) {InstallRebootSignalHandlers();
    }
    // 零碎时钟
    boot_clock::time_point start_time = boot_clock::now();
    ...
    // 一系列文件操作,linux 下 socket 也是非凡文件,0755 标记用户具备读 / 写 / 执行 权限,具体可查看相干命令
    CHECKCALL(mkdir("/dev/socket", 0755));
    //CMD 命令行
    CHECKCALL(chmod("/proc/cmdline", 0440));
    std::string cmdline;
    android::base::ReadFileToString("/proc/cmdline", &cmdline);
    // 读取 bootconfig
    chmod("/proc/bootconfig", 0440);
    std::string bootconfig;
    android::base::ReadFileToString("/proc/bootconfig", &bootconfig);
    ...
    SetStdioToDevNull(argv);
    //-------------- SetStdioToDevNull 源码如下正文如下 ---------------------------------
    最初,在第一阶段初始化中简略地调用 SetStdioToDevNull()是不够的,因为首先
    stage init 依然在内核上下文中运行,将来的子过程将无权
    拜访它关上的任何 FDS,包含上面为 /dev/null 关上的 FDS。因而
    SetStdioToDevNull()必须在第二阶段 init 中再次调用。void SetStdioToDevNull(char** argv) {
        // Make stdin/stdout/stderr all point to /dev/null.
        int fd = open("/dev/null", O_RDWR);  // NOLINT(android-cloexec-open)
        if (fd == -1) {
            int saved_errno = errno;
            android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter);
            errno = saved_errno;
            PLOG(FATAL) << "Couldn't open /dev/null";
        }
        dup2(fd, STDIN_FILENO);
        dup2(fd, STDOUT_FILENO);
        dup2(fd, STDERR_FILENO);
        if (fd > STDERR_FILENO) close(fd);
    }
    //-------------- SetStdioToDevNull()---------------------------------
    // 初始化内核日志打印
    InitKernelLogging(argv);
    ...
    //unique_ptr 智能指针被动开释内存
    auto old_root_dir = std::unique_ptr<DIR, decltype(&closedir)>{opendir("/"), closedir};
    struct stat old_root_info;
    if (stat("/", &old_root_info) != 0) {PLOG(ERROR) << "Could not stat(\"/\"), not freeing ramdisk";
        // 无奈开释时间接重启
        old_root_dir.reset(); 重启办法定义文件地位:/external/libcxx/include/memory}
    //FirstStageConsole
    auto want_console = ALLOW_FIRST_STAGE_CONSOLE ? FirstStageConsole(cmdline, bootconfig) : 0;
    auto want_parallel =
            bootconfig.find("androidboot.load_modules_parallel = \"true\"") != std::string::npos;
    ...
    // 在恢复模式 (Recovery) 下验证 AVB 原数据,验证胜利设置 INIT_AVB_VERSION
    SetInitAvbVersionInRecovery();
    // 写入环境变量
    setenv(kEnvFirstStageStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(),
           1);

    const char* path = "/system/bin/init";
    const char* args[] = {path, "selinux_setup", nullptr};
    auto fd = open("/dev/kmsg", O_WRONLY | O_CLOEXEC);
    dup2(fd, STDOUT_FILENO);
    dup2(fd, STDERR_FILENO);
    close(fd);
    // 启动新过程运行“selinux_setup”函数下一个阶段,执行流程回到 main.cpp
    execv(path, const_cast<char**>(args));
    // execv() only returns if an error happened, in which case we
    // panic and never fall through this conditional.
    PLOG(FATAL) << "execv(\"" << path << "\") failed";
    return 1;
}

2.4 SetupSelinux.cpp

设置安全策略
文件地位:/system/core/init/selinux.cpp

int SetupSelinux(char** argv) {
    // 参考 3.3 中同函数形容
    SetStdioToDevNull(argv);
    // 初始化内核日志
    InitKernelLogging(argv);
    if (REBOOT_BOOTLOADER_ON_PANIC) {
        // 参考 3.3 中同函数形容
        InstallRebootSignalHandlers();}
    // 系统启动工夫
    boot_clock::time_point start_time = boot_clock::now();
    //R 上挂载 system_ext,system,product 源码地位:/system/core/init/selinux.cpp
    MountMissingSystemPartitions();
    // 写入 kmsg selinux 日志
    SelinuxSetupKernelLogging();
    // 预编译安全策略
    PrepareApexSepolicy();
    // Read the policy before potentially killing snapuserd.
    std::string policy;
    // 读取 policy
    ReadPolicy(&policy);
    // 清理预编译缓存
    CleanupApexSepolicy();
    ...
    // 加载安全策略
    LoadSelinuxPolicy(policy);
    ...
    // 强制执行安全策略
    SelinuxSetEnforcement();
    ...
    // 设置 env 环境
    setenv(kEnvSelinuxStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(), 1);

    const char* path = "/system/bin/init";
    const char* args[] = {path, "second_stage", nullptr};
    // 启动新过程运行“second_stage”函数下一个阶段,执行流程回到 main.cpp
    execv(path, const_cast<char**>(args));

    // execv() only returns if an error happened, in which case we
    // panic and never return from this function.
    PLOG(FATAL) << "execv(\"" << path << "\") failed";
    return 1;
}

2.5 SecondStageMain.cpp

第二阶段启动, 文件地位:/system/core/init/init.cpp

int SecondStageMain(int argc, char** argv) {
    ...
    ...
    // 当设施解锁时容许 adb root 加载调试信息
    const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
    bool load_debug_prop = false;
    if (force_debuggable_env && AvbHandle::IsDeviceUnlocked()) {load_debug_prop = "true"s == force_debuggable_env;}
    ...
    // 属性初始化,源码地位:/system/core/init/property_service.cpp
    // 创立属性信息并存储在 /dev/__properties__/property_info 中,同时解决
    //ProcessKernelDt();
    //ProcessKernelCmdline();
    //ProcessBootconfig();
    //ExportKernelBootProps();
    //PropertyLoadBootDefaults();
    PropertyInit();
    // Umount second stage resources after property service has read the .prop files.
    UmountSecondStageRes();
    // Umount the debug ramdisk after property service has read the .prop files when it means to.
    if (load_debug_prop) {UmountDebugRamdisk();
    }
    // Mount extra filesystems required during second stage init
    MountExtraFilesystems();
    // Now set up SELinux for second stage.
    SelabelInitialize();
    SelinuxRestoreContext();
    Epoll epoll;
    if (auto result = epoll.Open(); !result.ok()) {PLOG(FATAL) << result.error();}
    // We always reap children before responding to the other pending functions. This is to
    // prevent a race where other daemons see that a service has exited and ask init to
    // start it again via ctl.start before init has reaped it.
    epoll.SetFirstCallback(ReapAnyOutstandingChildren);
    // 设置监听解决子过程退出信号
    InstallSignalFdHandler(&epoll);
    // 唤醒 init 过程
    InstallInitNotifier(&epoll);
    // 创立 property_service,property_set_fd sockets,property service 线程,通过 sokcet 与 init 过程通信
    // 源码地位:/system/core/init/property_service.cpp
    StartPropertyService(&property_fd);
    // Make the time that init stages started available for bootstat to log.
    RecordStageBoottimes(start_time);
    // Set libavb version for Framework-only OTA match in Treble build.
    if (const char* avb_version = getenv("INIT_AVB_VERSION"); avb_version != nullptr) {SetProperty("ro.boot.avb_version", avb_version);
    }
    ...
    // 初始化 subcontext
    InitializeSubcontext();
    // 创立 ActionManager、ServiceList
    ActionManager& am = ActionManager::GetInstance();
    ServiceList& sm = ServiceList::GetInstance();
    // 加载 rc 文件
    LoadBootScripts(am, sm);
    // 触发 early-init 语句
    am.QueueEventTrigger("early-init");
    ...
    // 触发 init 语句
    am.QueueEventTrigger("init");
    ...
    // 插入要执行的 Action
    am.QueueBuiltinAction(InitBinder, "InitBinder");
    ...
    // 设置 action, 期待 event_queue 执行函数
    am.QueueBuiltinAction(SetupCgroupsAction, "SetupCgroups");
    ...
    std::string bootmode = GetProperty("ro.bootmode", "");
    if (bootmode == "charger") {
        // 触发 charger 语句
        am.QueueEventTrigger("charger");
    } else {
        // 触发 late-init 语句
        am.QueueEventTrigger("late-init");
    }
    ...
    ...
    while (true) {
        // By default, sleep until something happens. Do not convert far_future into
        // std::chrono::milliseconds because that would trigger an overflow. The unit of boot_clock
        // is 1ns.
        const boot_clock::time_point far_future = boot_clock::time_point::max();
        boot_clock::time_point next_action_time = far_future;
        auto shutdown_command = shutdown_state.CheckShutdown();
        // 关机命令
        if (shutdown_command) {LOG(INFO) << "Got shutdown_command'" << *shutdown_command
                      << "'Calling HandlePowerctlMessage()";
            HandlePowerctlMessage(*shutdown_command);
        }
        // 执行 action
        if (!(prop_waiter_state.MightBeWaiting() || Service::is_exec_service_running())) {am.ExecuteOneCommand();
            // If there's more work to do, wake up again immediately.
            if (am.HasMoreCommands()) {next_action_time = boot_clock::now();
            }
        }
        ...
        if (!IsShuttingDown()) {
            // 解决属性的 control 命令,关联 ctl. 结尾的属性
            HandleControlMessages();
            // 设置 usb 属性
            SetUsbController();}
    }
    return 0;
}

exec 函数族有多个变种的模式:execl、execle、execv,具体形容可浏览该文档
https://zhuanlan.zhihu.com/p/363510745

2.6 SubcontextMain-subcontext 过程

源码地位 : system/core/init/subcontext.cpp

首先执行 adb shell 查看 context CMD 命令

adb shell ps -Af
root 572 1 0 17:40:12 ? 00:00:21 init subcontext u:r:vendor_init:s0 12
root 573 1 0 17:40:12 ? 00:00:04 init subcontext u:r:vendor_init:s0 13
  • system context : u:r:init:s0
  • vendor context : u:r:vendor_init:s0

外围调用办法, 通过 socket 与 init 过程通信

// 初始化 subcontext
void InitializeSubcontext() {  
    ...
    // 应用 u:r:vendor_init:s0 context 来执行命令
    if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
        subcontext.reset(new Subcontext(std::vector<std::string>{"/vendor", "/odm"}, kVendorContext));
    }
}
//Fork 子过程
void Subcontext::Fork()
//init.cpp main()初始化
int SubcontextMain(int argc, char** argv, const BuiltinFunctionMap* function_map) {auto context = std::string(argv[2]);
    auto init_fd = std::atoi(argv[3]);
    ...
    auto subcontext_process = SubcontextProcess(function_map, context, init_fd);
    // Restore prio before main loop
    setpriority(PRIO_PROCESS, 0, 0);
    //MainLoop 死循环,对 socket 进行监听 / 读取 / 解析 / 执行 CMD/SendMessage init
    subcontext_process.MainLoop();
    return 0;
}
void SubcontextProcess::MainLoop()

2.7 第二阶段 LoadBootScripts 办法

static void LoadBootScripts(ActionManager& action_manager, ServiceList& service_list) {
    // 创立解析器
    Parser parser = CreateParser(action_manager, service_list);
    // 获取.init_rc 属性
    std::string bootscript = GetProperty("ro.boot.init_rc", "");
    if (bootscript.empty()) {
        // 解析 init.rc
        parser.ParseConfig("/system/etc/init/hw/init.rc");
        if (!parser.ParseConfig("/system/etc/init")) {late_import_paths.emplace_back("/system/etc/init");
        }
        // late_import is available only in Q and earlier release. As we don't
        // have system_ext in those versions, skip late_import for system_ext.
        // 通用零碎组件
        parser.ParseConfig("/system_ext/etc/init");
        //“vendor”厂商对系统的定制
        if (!parser.ParseConfig("/vendor/etc/init")) {late_import_paths.emplace_back("/vendor/etc/init");
        }
        //“odm”厂商对系统定制的可选分区
        if (!parser.ParseConfig("/odm/etc/init")) {late_import_paths.emplace_back("/odm/etc/init");
        }
        //“product”特定的产品模块,对系统的定制化
        if (!parser.ParseConfig("/product/etc/init")) {late_import_paths.emplace_back("/product/etc/init");
        }
    } else {parser.ParseConfig(bootscript);
    }
}

解析器有 Parser, 蕴含 Action,Command,ActionManager,Service,Option,ServiceList 等对象,整个解析过程是面向对象

Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) {
    // 以 section 块为单位,蕴含 service,on,import 语句
    Parser parser;
    //ServiceParser 解析器
    parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, GetSubcontext(), std::nullopt));
    //ActionParser 解析器
    parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, GetSubcontext()));
    //ImportParser 解析器
    parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
    return parser;
}

解析器都继承于 SectionParser, 文件地位:/system/core/init/parser.h,每个 parser 从上往下解析,对应步骤如下(具体能够看文件源码):

  • 剖析开始(ParseSection)
  • 每一行剖析(ParseLineSection)
  • 完结剖析(EndSection/EndFile)

不同解析器解决不同 section 块,以下面三种解析器为例:

  • ServiceParser:解析 service section,构建 Service 对象,记录可执行文件门路和参数,最初交由 ServiceList(std::vector<Service*>)治理
  • ActionParser:解析 action section, 构建 action 对象,蕴含所有 command,最初交由 ActionManager 治理
  • ImportParser:解析导入的 rc 文件名

理解解析器后,咱们持续看 init.rc 具体脚本内容,文件地位:/system/core/rootdir/init.rc
脚本源码内容根本 1000+ 行,所以拆分出主流程,具体的可浏览源码理解

//am.QueueEventTrigger("early-init")
on early-init
    // 一个守护过程,负责解决 uevent 音讯
    start ueventd
    //apex 服务于零碎模块装置
    exec_start apexd-bootstrap

// 触发所有 action
//am.QueueEventTrigger("init");
on init
    // 创立 stdio 规范输入输出链接
    symlink /proc/self/fd/0 /dev/stdin
    // 设置 sdcard 权限
    chmod 0770 /config/sdcardfs
    // 启动 servicemanager
    start servicemanager
    // 启动硬件服务
    start hwservicemanager
    // 供应商服务
    start vndservicemanager
    
//am.QueueEventTrigger("charger");
// 属性 - 充电模式 trigger late-init
on property:sys.boot_from_charger_mode=1
    class_stop charger
    trigger late-init
    
// 挂载文件系统,启动系统核心服务
//am.QueueEventTrigger("late-init")
on late-init
    // 触发 fs:内部存储
    trigger early-fs
    // 触发 zygote 过程,文件地位:system/core/rootdir/init.zygote32.rc
    trigger zygote-start
    //boot
    trigger early-boot
    trigger boot

on boot
    // 启动 HAL 硬件服务
    class_start hal
    // 启动外围类服务
    class_start core

2.8 解析 zygote.rc 脚本文件

文件地位:

  • /system/core/rootdir/init.zygote32.rc,
  • system/core/rootdir/init.zygote64.rc,
  • system/core/rootdir/init.zygote64_32.rc
  • system/core/rootdir/init.no_zygote.rc

    service zygote /system/bin/app_process -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
      onrestart exec_background - system system -- /system/bin/vdc volume abort_fuse
      onrestart write /sys/power/state on
      # NOTE: If the wakelock name here is changed, then also
      # update it in SystemSuspend.cpp
      onrestart write /sys/power/wake_lock zygote_kwl
      onrestart restart audioserver
      onrestart restart cameraserver
      onrestart restart media
      onrestart restart media.tuner
      onrestart restart netd
      onrestart restart wificond
      task_profiles ProcessCapacityHigh
      critical window=${zygote.critical_window.minute:-off} target=zygote-fatal
  • service zygote 定义 zygote 服务,init 过程通过该名称 fork 子过程
  • /system/bin/app_process 执行零碎下 app_process 并传入前面参数
  • -Xzygote 参数作为虚拟机入参
  • /system/bin 虚拟机所在文件地位
  • –zygote 指定虚拟机执行入口函数:ZygoteInit.java main()
  • –start-system-server 启动 zygote 零碎服务

3. Zygote 过程

基于 init.rc 脚本配置, 通过解析器及服务相干配置,此时曾经进入 native framework 层筹备进入启动入口,通过 AppRuntime main() 调用 AndroidRuntime start()最终启动,AppRuntime 继承于 AndroidRuntime,main()会解析启动 zygote 服务传递的参数,而后依据指定参数启动是 ZygoteInit 还是 RuntimeInit; 上面我看下 AppRuntime app_process 源码定义

源码地位:/frameworks/base/cmds/app_process/app_main.cpp

#if defined(__LP64__)
static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist64";
static const char ZYGOTE_NICE_NAME[] = "zygote64";
#else
static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist32";
static const char ZYGOTE_NICE_NAME[] = "zygote";
#endif

//AppRuntime 结构函数调用父类办法初始化 Skia 引擎
AndroidRuntime::AndroidRuntime(char* argBlockStart, const size_t argBlockLength) :
        mExitWithoutCleanup(false),
        mArgBlockStart(argBlockStart),
        mArgBlockLength(argBlockLength){init_android_graphics();
    ...
}
// 入口办法
int main(int argc, char* const argv[]){
    // 构建 AppRuntime
    AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
    // Process command line arguments
    // ignore argv[0]
    argc--;
    argv++;
    // 解析 init.rc 启动 zygote service 参数
    // 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) {
            //ztgote 设置为 true
            zygote = true;
            //32 位名称为 zygote,64 位为 zygote64
            niceName = ZYGOTE_NICE_NAME;
        } else if (strcmp(arg, "--start-system-server") == 0) {
            // 是否启动 system-server
            startSystemServer = true;
        } else if (strcmp(arg, "--application") == 0) {
            // 独立利用
            application = true;
        } else if (strncmp(arg, "--nice-name=", 12) == 0) {
            // 过程别名,辨别 abi
            niceName.setTo(arg + 12);
        } else if (strncmp(arg, "--", 2) != 0) {className.setTo(arg);
            break;
        } else {
            --i;
            break;
        }
    }
    Vector<String8> args;
    if (!className.isEmpty()) {
        // We're not in zygote mode, the only argument we need to pass
        // to RuntimeInit is the application argument.
        //
        // The Remainder of args get passed to startup class main(). Make
        // copies of them before we overwrite them with the process name.
        args.add(application ? String8("application") : String8("tool"));
        runtime.setClassNameAndArgs(className, argc - i, argv + i);
        ...
    } else {
        // We're in zygote mode. 进入 zygote 模式,创立 dalvik 缓存目录,data/dalivk-cache
        maybeCreateDalvikCache();
        // 退出 "start-system-server" 参数
        if (startSystemServer) {args.add(String8("start-system-server"));
        }
        // 解决 abi 相干
        char prop[PROP_VALUE_MAX];
        if (property_get(ABI_LIST_PROPERTY, prop, NULL) == 0) {
            LOG_ALWAYS_FATAL("app_process: Unable to determine ABI list from property %s.",
                ABI_LIST_PROPERTY);
            return 11;
        }
        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]));
        }
    }
    // 设置 process 名称 -  由 app_process 改为 niceName 变量值
    if (!niceName.isEmpty()) {runtime.setArgv0(niceName.string(), true /* setProcName */);
    }
    // 如果是 zygote 启动模式,加载 com.android.internal.os.ZygoteInit.java
    if (zygote) {runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
    } else if (className) {
        // 如果是 application 模式,加载 RuntimeInit.java
        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.");
    }
}

基于 AppRuntime 继承 AndroidRuntime, 咱们持续看下 runtime.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;
    // 加载 libart.so
    jni_invocation.Init(NULL);
    JNIEnv* env;
    // 启动 Java 虚拟机
    if (startVm(&mJavaVM, &env, zygote, primary_zygote) != 0) {return;}
    // 回调子类重写办法
    onVmCreated(env);
    // 注册 Android JNI 办法,为前面查找 ZygoteInit.java 类筹备
    /*
     * Register android functions.
     */
    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;
    // 查找 zygote 初始化类,//runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
    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.
     */
    //JNI 中的类名规定:将 Java 类名中的 "." 替换成 "/"
    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 {
        // 获取 ZygoteInit.java main 办法
        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 {
            // 已找到 main 办法,通过 JNI 调用 Java 办法,最终启动 zygote init 初始化相干
            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 源码咱们能够看到它做了以下几点

  • jni_invocation.Init 加载 libart.so
  • startVm 启动 Java 虚拟机
  • startReg 注册 Android JNI 办法
  • FindClass 查找 zygote 初始化类
  • CallStaticVoidMethod 调用 ZygoteInit.java main()

3.1 启动 JVM:JniInvocation 初始化

JniInvocation 理论是头文件代理类,最终调用实现为 JniInvocationImpl,通过构造函数初始化 impl, 接着调用 init 办法,最终都转向 JniInvocationImpl.c 中办法调用

JniInvocation.h 源码地位:
/libnativehelper/include_platform/nativehelper/JniInvocation.h

JniInvocationImpl.c 源码地位:
/libnativehelper/include_platform/nativehelper/JniInvocation.h

static const char* kDefaultJniInvocationLibrary = "libart.so";

bool JniInvocationInit(struct JniInvocationImpl* instance, const char* library_name) {
  ...
  // 非 debug 模式返回 kDefaultJniInvocationLibrary 参数
  library_name = JniInvocationGetLibrary(library_name, buffer);
  // 关上 "libart.so"
  DlLibrary library = DlOpenLibrary(library_name);
  if (library == NULL) {
    // 加载失败返回 false
    if (strcmp(library_name, kDefaultJniInvocationLibrary) == 0) {
      // Nothing else to try.
      ALOGE("Failed to dlopen %s: %s", library_name, DlGetError());
      return false;
    }
    ...
  }
  // 从以后 "libart.so" 获取以下 3 个 JNI 函数指针
  DlSymbol JNI_GetDefaultJavaVMInitArgs_ = FindSymbol(library, "JNI_GetDefaultJavaVMInitArgs");
  // 获取虚拟机默认初始化参数
  if (JNI_GetDefaultJavaVMInitArgs_ == NULL) {return false;}
  DlSymbol JNI_CreateJavaVM_ = FindSymbol(library, "JNI_CreateJavaVM");
  // 创立虚拟机
  if (JNI_CreateJavaVM_ == NULL) {return false;}
  DlSymbol JNI_GetCreatedJavaVMs_ = FindSymbol(library, "JNI_GetCreatedJavaVMs");
  // 获取创立的实例
  if (JNI_GetCreatedJavaVMs_ == NULL) {return false;}
  ...
  return true;
}

3.2 启动 JVM:startVM()

该办法次要解决以下内容

  • 配置虚拟机参数和选项
  • 调用 JNI_CreateJavaVM()创立并初始化,该办法原始地位:/art/runtime/jni/java_vm_ext.cc

3.3 startReg 注册 Android JNI 办法

/*
 * Register android native functions with the VM.
 */
/*static*/ int AndroidRuntime::startReg(JNIEnv* env){ATRACE_NAME("RegisterAndroidNatives");
    /*
     * This hook causes all future threads created in this process to be
     * attached to the JavaVM.  (This needs to go away in favor of JNI
     * Attach calls.)
     */
     // 依据源码正文,此处调用 javaCreateThreadEtc 创立的线程会 attached jvm, 这样 C ++、Java 代码都能执行
    androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
    /*
     * Every "register" function calls one or more things that return
     * a local reference (e.g. FindClass).  Because we haven't really
     * started the VM yet, they're all getting stored in the base frame
     * and never released.  Use Push/Pop to manage the storage.
     */
     //jni 部分援用 - 入栈
    env->PushLocalFrame(200);
    // 注册 jni 办法
    if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {env->PopLocalFrame(NULL);
        return -1;
    }
    //jni 部分援用 - 出栈
    env->PopLocalFrame(NULL);
    //createJavaThread("fubar", quickTest, (void*) "hello");
    return 0;
}
//JNI 函数数组
static const RegJNIRec gRegJNI[] = {REG_JNI(register_com_android_internal_os_RuntimeInit),
    REG_JNI(register_com_android_internal_os_ZygoteInit_nativeZygoteInit),
    ...
    ...
}
// 循环调用 gRegJNI 数组中所有的函数
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;
}
//gRegJNI 函数数组实例,JNI 函数相干调用
int register_com_android_internal_os_RuntimeInit(JNIEnv* env){const JNINativeMethod methods[] = {{"nativeFinishInit", "()V",
             (void*)com_android_internal_os_RuntimeInit_nativeFinishInit},
            {"nativeSetExitWithoutCleanup", "(Z)V",
             (void*)com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup},
    };
    return jniRegisterNativeMethods(env, "com/android/internal/os/RuntimeInit",
        methods, NELEM(methods));
}
int register_com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env){const JNINativeMethod methods[] = {{ "nativeZygoteInit", "()V",
            (void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
    };
    return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
        methods, NELEM(methods));
}

通过以上 JVM 虚拟机配置 / 创立,JNI 援用注册 / 函数查找,以及对 ZygoteInit main()调用,咱们能够进入 ZygoteInit.java 代码了,一起看看 Java 层是如何实现

4. ZygoteInit.java 类

源码门路:frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

上面先看看 main()源码定义, 而后再持续剖析

public static void main(String[] argv) {
    ZygoteServer zygoteServer = null;
    // Mark zygote start. This ensures that thread creation will throw
    // an error.
    ZygoteHooks.startZygoteNoThreadCreation();
    // Zygote goes into its own process group.
    try {Os.setpgid(0, 0);
    } catch(ErrnoException ex) {throw new RuntimeException("Failed to setpgid(0,0)", ex);
    }
    Runnable caller;
    try {
        // Store now for StatsLogging later.
        final long startTime = SystemClock.elapsedRealtime();
        final boolean isRuntimeRestarted = "1".equals(SystemProperties.get("sys.boot_completed"));

        String bootTimeTag = Process.is64Bit() ? "Zygote64Timing": "Zygote32Timing";
        TimingsTraceLog bootTimingsTraceLog = new TimingsTraceLog(bootTimeTag, Trace.TRACE_TAG_DALVIK);
        bootTimingsTraceLog.traceBegin("ZygoteInit");
        RuntimeInit.preForkInit();
        // 设置 startSystemServer,abiList,argvs 参数,sokcet name 等
        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]);
            }
        }
        final boolean isPrimaryZygote = zygoteSocketName.equals(Zygote.PRIMARY_SOCKET_NAME);
        if (!isRuntimeRestarted) {if (isPrimaryZygote) {FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED, BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__ZYGOTE_INIT_START, startTime);
            } else if (zygoteSocketName.equals(Zygote.SECONDARY_SOCKET_NAME)) {FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED, BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SECONDARY_ZYGOTE_INIT_START, startTime);
            }
        }
        if (abiList == null) {throw new RuntimeException("No ABI list supplied.");
        }
        // In some configurations, we avoid preloading resources and classes eagerly.
        // In such cases, we will preload things prior to our first fork.
        if (!enableLazyPreload) {bootTimingsTraceLog.traceBegin("ZygotePreload");
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START, SystemClock.uptimeMillis());
            preload(bootTimingsTraceLog);
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END, SystemClock.uptimeMillis());
            bootTimingsTraceLog.traceEnd(); // ZygotePreload}
        // Do an initial gc to clean up after startup
        bootTimingsTraceLog.traceBegin("PostZygoteInitGC");
        gcAndFinalize();
        bootTimingsTraceLog.traceEnd(); // PostZygoteInitGC
        bootTimingsTraceLog.traceEnd(); // ZygoteInit
        Zygote.initNativeState(isPrimaryZygote);
        ZygoteHooks.stopZygoteNoThreadCreation();
        zygoteServer = new ZygoteServer(isPrimaryZygote);
        if (startSystemServer) {Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
            // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
            // child (system_server) process.
            if (r != null) {r.run();
                return;
            }
        }
        Log.i(TAG, "Accepting command socket connections");
        // The select loop returns early in the child process after a fork and
        // loops forever in the zygote.
        caller = zygoteServer.runSelectLoop(abiList);
    } catch(Throwable ex) {Log.e(TAG, "System zygote died with fatal exception", 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();
    }
}

main 办法次要解决以下内容:

  1. ZygoteHooks.startZygoteNoThreadCreation() 标记 zygote 启动, 单线程模式

    Java 层调用 native 办法,源码:art/runtime/native/dalvik_system_ZygoteHooks.cc

    static void ZygoteHooks_startZygoteNoThreadCreation(JNIEnv* env ATTRIBUTE_UNUSED,jclass klass ATTRIBUTE_UNUSED) {Runtime::Current()->SetZygoteNoThreadSection(true);
    }
    static void ZygoteHooks_stopZygoteNoThreadCreation(JNIEnv* env ATTRIBUTE_UNUSED,jclass klass ATTRIBUTE_UNUSED) {Runtime::Current()->SetZygoteNoThreadSection(false);
    }
    // 调用下面 2 个办法设置 zygote_no_threads_参数值,源码:/art/runtime/runtime.h
    void SetZygoteNoThreadSection(bool val) {zygote_no_threads_ = val;}
  2. android.system.Os.setpgid(0, 0) 设置过程组 id 为 0
  3. RuntimeInit.preForkInit() Zygote Init 预初始化,开启 DDMS,设置 MimeMap
  4. preload(bootTimingsTraceLog) 开始预加载 resources,class,tff

    static void preload(TimingsTraceLog bootTimingsTraceLog) {
        // 开始
        beginPreload();
        // 加载 pre class, 文件地位:frameworks/base/boot/preloaded-classes frameworks/base/config/preloaded-classes
        preloadClasses();
        // 加载无奈放入 Boot classpath 的文件,/system/framework/android.hidl.base-V1.0-java.jar /system/framework/android.test.base.jar
        cacheNonBootClasspathClassLoaders();
        // 加载 drawables、colors
        preloadResources();
        // 加载 hal 硬件
        nativePreloadAppProcessHALs();
        // 调用 OpenGL/Vulkan 加载图形驱动程序
        maybePreloadGraphicsDriver();
        // 加载共享库,System.loadLibrary("android")(“jnigraphics”)(“compiler_rt”)preloadSharedLibraries();
        // 初始化 TextView
        preloadTextResources();
        // 初始化 WebView
        WebViewFactory.prepareWebViewInZygote();
        // 完结
        endPreload();
        warmUpJcaProviders();
        sPreloadComplete = true;
    }
  5. gcAndFinalize() 在 fork 之前被动调用 Java gc
  6. Zygote.initNativeState(isPrimaryZygote) [1]从环境中获取套接字 FD [2]初始化平安属性 [3]适当地卸载存储 [4]加载必要的性能配置文件信息
  7. ZygoteHooks.stopZygoteNoThreadCreation() 标记 zygote 进行保护单线程模式,可创立子线程
  8. zygoteServer = new ZygoteServer 初始化 ZygoteServer – socket

    调用 Zygote.createManagedSocketFromInitSocket 办法实例化 LocalServerSocketImpl 对象

    // 源码地位:/frameworks/base/core/java/android/net/LocalServerSocket.java
    //        /frameworks/base/core/java/android/net/LocalSocketImpl.java
    public LocalServerSocket(String name) throws IOException {
        // 实例化
        impl = new LocalSocketImpl();
        // 创立 socket 流
        impl.create(LocalSocket.SOCKET_STREAM);
        // 建设本地通信地址
        localAddress = new LocalSocketAddress(name);
        // 绑定该地址
        impl.bind(localAddress);
        //Linux 函数 listen 开启监听
        impl.listen(LISTEN_BACKLOG);
    }
  9. Runnable r = forkSystemServer : fork 出 SystemServer,对应 com.android.server.SystemServer
  10. caller = zygoteServer.runSelectLoop 始终循环接管 socket 音讯
    在 runSelectLoop 死循环中,会先创立 StructPollfd 数组并通过 Os.poll 函数转换为 struct pollfd 数组,如果是 ZygoteServer socket 对应的 fd,则调用 ZygoteConnection newPeer = acceptCommandPeer(abiList)建设 socket 连贯,源码如下:

    //acceptCommandPeer
    private ZygoteConnection acceptCommandPeer(String abiList) {
        try {return createNewConnection(mZygoteSocket.accept(), abiList);
        } catch(IOException ex) {throw new RuntimeException("IOException during accept()", ex);
        }
    }
    // 调用 LocalSocketImpl 的 accept 办法承受 socket
    public LocalSocket accept() throws IOException {LocalSocketImpl acceptedImpl = new LocalSocketImpl();
        impl.accept(acceptedImpl);
        // 把 LocalSocketImpl 包装成 LocalSocket 对象
        return LocalSocket.createLocalSocketForAccept(acceptedImpl);
    }
    // 而后将 LocalSocket 包装成 ZygoteConnection socket 连贯
    ZygoteConnection(LocalSocket socket, String abiList) throws IOException {
        mSocket = socket;
        this.abiList = abiList;
        // 开启写入流,筹备写入数据
        mSocketOutStream = new DataOutputStream(socket.getOutputStream());
        mSocket.setSoTimeout(CONNECTION_TIMEOUT_MILLIS);
        try {peer = mSocket.getPeerCredentials();
        } catch(IOException ex) {Log.e(TAG, "Cannot read peer credentials", ex);
            throw ex;
        }
        isEof = false;
    }

    循环持续往下走,调用 connection.processOneCommand 执行 socket 命令,通过 Zygote.readArgumentList 读取 socket 传递参数,ZygoteArguments 对象解决参数,一系列参数校验实现,开始调用 Zygote.forkAndSpecialize 创立子过程

    static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir, boolean isTopApp, String[] pkgDataInfoList, String[] allowlistedDataInfoList, boolean bindMountAppDataDirs, boolean bindMountAppStorageDirs) {
        //1. 事后 fork 时会进行 zygote 创立的 4 个守护过程,开释资源
            //HeapTaskDaemon.INSTANCE.stop();           Java 堆工作线程
            //ReferenceQueueDaemon.INSTANCE.stop();     援用队列线程
            //FinalizerDaemon.INSTANCE.stop();          析构线程
            //FinalizerWatchdogDaemon.INSTANCE.stop();  析构监控线程
        //2. 调用 native 办法实现 gc heap 初始化
        //3. 期待所有子线程完结
        ZygoteHooks.preFork();
        // 调用 native 办法
        int pid = nativeForkAndSpecialize(uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose, fdsToIgnore, startChildZygote, instructionSet, appDataDir, isTopApp, pkgDataInfoList, allowlistedDataInfoList, bindMountAppDataDirs, bindMountAppStorageDirs);
        if (pid == 0) {
            // 监控 handleChildProc 解决,直到子过程 fork 结束
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
            // If no GIDs were specified, don't make any permissions changes based on groups.
            if (gids != null && gids.length > 0) {NetworkUtilsInternal.setAllowNetworkingForProcess(containsInetGid(gids));
            }
        }
        // Set the Java Language thread priority to the default value for new apps.
        Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
        //fork 完结后复原其它线程
        ZygoteHooks.postForkCommon();
        return pid;
    }
    
    //nativeFork 办法,源码地位:frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
    private static native int nativeForkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir, boolean isTopApp, String[] pkgDataInfoList, String[] allowlistedDataInfoList, boolean bindMountAppDataDirs, boolean bindMountAppStorageDirs);

    咱们持续往下查看 handleChildProc 子过程解决,

    private Runnable handleChildProc(ZygoteArguments parsedArgs, FileDescriptor pipeFd, boolean isZygote) {
        // 过程创立结束敞开 socket
        closeSocket();
        // 设置过程名称
        Zygote.setAppProcessName(parsedArgs, TAG);
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        // 这个中央 mInvokeWith 未找到调用源
        if (parsedArgs.mInvokeWith != null) {WrapperInit.execApplication(parsedArgs.mInvokeWith, parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion, VMRuntime.getCurrentInstructionSet(), pipeFd, parsedArgs.mRemainingArgs);
            throw new IllegalStateException("WrapperInit.execApplication unexpectedly returned");
        } else {if (!isZygote) {return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion, parsedArgs.mDisabledCompatChanges, parsedArgs.mRemainingArgs, null);
            } else {return ZygoteInit.childZygoteInit(parsedArgs.mRemainingArgs);
            }
        }
    }
    //ZygoteInit.zygoteInit 源码地位:frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
    public static Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges, String[] argv, ClassLoader classLoader) {
        ...
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
        // 重定向 log 流
        RuntimeInit.redirectLogStreams();
        //log、thread、AndroidConfig 初始化
        RuntimeInit.commonInit();
        // 最终调用 AndroidRuntime-AppRuntime-onZygoteInit(), 初始化 binder
        ZygoteInit.nativeZygoteInit();
        // 利用初始化
        return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv, classLoader);
    }
    
    // 源码地位:frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
    protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges, String[] argv, ClassLoader classLoader) {// 如果应用程序调用 System.exit(),则终止过程立刻运行,而不运行 hooks; 不可能优雅地敞开 Android 应用程序。// 除其余外 Android 运行时敞开挂钩敞开 Binder 驱动程序,这可能导致残余的运行线程在过程理论退出之前解体
        nativeSetExitWithoutCleanup(true);
        // 设置 targetVersion\disabledCompatChanges 参数
        VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
        VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);
        // 解析参数
        final Arguments args = new Arguments(argv);
        // The end of of the RuntimeInit event (see #zygoteInit).
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        // 解析参数,调用 startClass 对应的 main 办法,此处 class 为:android.app.ActivityThread
        // 通过反射查找 main 办法并创立 MethodAndArgsCaller runnable 执行对象
        // 通过调用 ZygoteInit.runSelectLoop 返回 runnable caller, 如果不为空 caller.run
        return findStaticMain(args.startClass, args.startArgs, classLoader);
    }
  11. zygoteServer.closeServerSocket() 敞开接管 socket 音讯

5.SystemServer.java

Zygote 的 forkSystemServer 办法最终会走到 nativeForkSystemServer 进行解决,
对应源码地位:frameworks/base/core/jni/com_android_internal_os_Zygote.cpp

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",
};

调用办法传参时定义了 “com.android.server.SystemServer”, 由此后续在调用 ZygoteInit.zygoteInit、RuntimeInit.applicationInit、findStaticMain 等办法后,最终会调用 com.android.server.SystemServer main()办法,省略以上过程咱们间接进入主入口源码

// 源码门路:frameworks/base/services/java/com/android/server/SystemServer.java
public static void main(String[] args) {new SystemServer().run();}
public SystemServer() {
    // Check for factory test mode.
    mFactoryTestMode = FactoryTest.getMode();
    // 记录过程启动信息
    mStartCount = SystemProperties.getInt(SYSPROP_START_COUNT, 0) + 1;
    // 设置工夫
    mRuntimeStartElapsedTime = SystemClock.elapsedRealtime();
    mRuntimeStartUptime = SystemClock.uptimeMillis();
    Process.setStartTimes(mRuntimeStartElapsedTime, mRuntimeStartUptime, mRuntimeStartElapsedTime, mRuntimeStartUptime);
    // 记录是运行时重启还是重新启动
    mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
}
//run
private void run() {TimingsTraceAndSlog t = new TimingsTraceAndSlog();
    try {
        // 监控开始
        t.traceBegin("InitBeforeStartServices");
        // 过程零碎属性信息
        SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount));
        SystemProperties.set(SYSPROP_START_ELAPSED, String.valueOf(mRuntimeStartElapsedTime));
        SystemProperties.set(SYSPROP_START_UPTIME, String.valueOf(mRuntimeStartUptime));
        EventLog.writeEvent(EventLogTags.SYSTEM_SERVER_START, mStartCount, mRuntimeStartUptime, mRuntimeStartElapsedTime);
        // 设置时区
        String timezoneProperty = SystemProperties.get("persist.sys.timezone");
        if (!isValidTimeZoneId(timezoneProperty)) {Slog.w(TAG, "persist.sys.timezone is not valid (" + timezoneProperty + "); setting to GMT.");
            SystemProperties.set("persist.sys.timezone", "GMT");
        }
        // 设置零碎语言
        // NOTE: Most changes made here will need an equivalent change to
        // core/jni/AndroidRuntime.cpp
        if (!SystemProperties.get("persist.sys.language").isEmpty()) {final String languageTag = Locale.getDefault().toLanguageTag();
            SystemProperties.set("persist.sys.locale", languageTag);
            SystemProperties.set("persist.sys.language", "");
            SystemProperties.set("persist.sys.country", "");
            SystemProperties.set("persist.sys.localevar", "");
        }
        // The system server should never make non-oneway calls
        Binder.setWarnOnBlocking(true);
        // The system server should always load safe labels
        PackageItemInfo.forceSafeLabels();
        // Default to FULL within the system server.
        SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
        // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
        SQLiteCompatibilityWalFlags.init(null);
        // Here we go!
        Slog.i(TAG, "Entered the Android system server!");
        final long uptimeMillis = SystemClock.elapsedRealtime();
        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
        if (!mRuntimeRestart) {FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED, FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_INIT_START, uptimeMillis);
        }
        // In case the runtime switched since last boot (such as when
        // the old runtime was removed in an OTA), set the system
        // property so that it is in sync. We can't do this in
        // libnativehelper's JniInvocation::Init code where we already
        // had to fallback to a different runtime because it is
        // running as root and we need to be the system user to set
        // the property. http://b/11463182
        // 设置虚拟机属性
        SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
        // 清理内存
        VMRuntime.getRuntime().clearGrowthLimit();
        // Some devices rely on runtime fingerprint generation, so make sure
        // we've defined it before booting further.
        Build.ensureFingerprintProperty();
        // Within the system server, it is an error to access Environment paths without
        // explicitly specifying a user.
        Environment.setUserRequired(true);
        // Within the system server, any incoming Bundles should be defused
        // to avoid throwing BadParcelableException.
        BaseBundle.setShouldDefuse(true);
        // Within the system server, when parceling exceptions, include the stack trace
        Parcel.setStackTraceParceling(true);
        // Ensure binder calls into the system always run at foreground priority.
        BinderInternal.disableBackgroundScheduling(true);
        // Increase the number of binder threads in system_server
        BinderInternal.setMaxThreads(sMaxBinderThreads);
        // Prepare the main looper thread (this thread)
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);
        android.os.Process.setCanSelfBackground(false);
        Looper.prepareMainLooper();
        SystemServiceRegistry.sEnableServiceNotFoundWtf = true;
        // Initialize native services.
        System.loadLibrary("android_servers");
        // Allow heap / perf profiling.
        initZygoteChildHeapProfiling();
        // Debug builds - spawn a thread to monitor for fd leaks.
        if (Build.IS_DEBUGGABLE) {spawnFdLeakCheckThread();
        }
        // Check whether we failed to shut down last time we tried.
        // This call may not return.
        performPendingShutdown();
        // Initialize the system 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.
        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);
        // Load preinstalled system fonts for system server, so that WindowManagerService, etc
        // can start using Typeface. Note that fonts are required not only for text rendering,
        // but also for some text operations (e.g. TextUtils.makeSafeForPresentation()).
        if (Typeface.ENABLE_LAZY_TYPEFACE_INITIALIZATION) {Typeface.loadPreinstalledSystemFontMap();
        }
        // 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");
        // 疏导服务[Watchdog][FileIntegrityService][Installer][AMS][PMS]...
        startBootstrapServices(t);
        // 启动外围服务[Battery][SystemConfig][LooperState][GpuService]...
        startCoreServices(t);
        // 其它服务[Network][Vpn][WMS][IMS][TelephonyRegistry]...
        startOtherServices(t);
        //Android Q APEX 格式文件
        startApexServices(t);
    } catch(Throwable ex) {Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {t.traceEnd(); // StartServices
    }
    // 初始化虚拟机 StrictMode
    StrictMode.initVmDefaults(null);
    // 非运行时重启或者首次启动或更新
    if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {final long uptimeMillis = SystemClock.elapsedRealtime();        FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED, FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_READY, uptimeMillis);
        final long maxUptimeMillis = 60 * 1000;
        if (uptimeMillis > maxUptimeMillis) {Slog.wtf(SYSTEM_SERVER_TIMING_TAG, "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
        }
    }
    // Loop forever.
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

以上 run 办法源码原始英文正文十分具体,流程执行也很清晰,外围步骤如下

  • 调用 SystemServerInitThreadPool 初始化线程池
  • 创立 SystemServiceManager 服务治理对象
  • 调用 startBootstrapServices 启动疏导服务
  • 调用 startCoreServices 启动外围服务
  • 调用 startOtherServices 启动其它服务
  • 调用 startApexServices 启动 APEX 文件服务

6. ActivityManagerService

ActivityManagerService 次要管理系统中所有的利用过程和四大组件服务,
LifeCycle.getService()返回 ActivityTaskManagerService 对象(Lifecycle 继承于 SystemService),mSystemServiceManager.startService 通过反射查找 class 并最终 startService, 咱们接着看 ActivityManagerService 的构造函数

public ActivityManagerService(Context systemContext,
                                ActivityTaskManagerService atm) {LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
    // 初始化 Injector 对象
    mInjector = new Injector(systemContext);
    mContext = systemContext;
    mFactoryTest = FactoryTest.getMode();
    // 获取 SystemServer.createSystemContext 函数中初始化的 ActivityThread
    mSystemThread = ActivityThread.currentActivityThread();
    mUiContext = mSystemThread.getSystemUiContext();
    //TAG 线程名,默认 TAG_AM 即 ActivityManager 前台线程, 获取 mHandler
    mHandlerThread = new ServiceThread(TAG, THREAD_PRIORITY_FOREGROUND, false/*allowIo*/);
    mHandlerThread.start();
    // 创立 MainHandler, 与 mHandlerThread 关联
    mHandler = new MainHandler(mHandlerThread.getLooper());
    // 初始化 UiHandler 对象,继承于 Handler
    mUiHandler = mInjector.getUiHandler(this);
    // 新建 mProcStartHandlerThread 线程并于创立 handle 关联
    mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", THREAD_PRIORITY_FOREGROUND, false
    /* allowIo */
    );
    mProcStartHandlerThread.start();
    mProcStartHandler = new ProcStartHandler(this, mProcStartHandlerThread.getLooper());
    //ActivityManager 常量治理
    mConstants = new ActivityManagerConstants(mContext, this, mHandler);
    final ActiveUids activeUids = new ActiveUids(this, true
    /* postChangesToAtm */
    );
    mPlatformCompat = (PlatformCompat) ServiceManager.getService(Context.PLATFORM_COMPAT_SERVICE);
    mProcessList = mInjector.getProcessList(this);
    mProcessList.init(this, activeUids, mPlatformCompat);
    //profiler, 低内存监控
    mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), new LowMemDetector(this));
    mPhantomProcessList = new PhantomProcessList(this);
    //OOM 监控
    mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
    // 监听 BROADCAST_BG_CONSTANTS 播送相干
    // Broadcast policy parameters
    final BroadcastConstants foreConstants = new BroadcastConstants(Settings.Global.BROADCAST_FG_CONSTANTS);
    foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;

    final BroadcastConstants backConstants = new BroadcastConstants(Settings.Global.BROADCAST_BG_CONSTANTS);
    backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
    final BroadcastConstants offloadConstants = new BroadcastConstants(Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
    offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
    // by default, no "slow" policy in this queue
    offloadConstants.SLOW_TIME = Integer.MAX_VALUE;

    mEnableOffloadQueue = SystemProperties.getBoolean("persist.device_config.activity_manager_native_boot.offload_queue_enabled", true);
    // 初始化播送队列
    mFgBroadcastQueue = new BroadcastQueue(this, mHandler, "foreground", foreConstants, false);
    mBgBroadcastQueue = new BroadcastQueue(this, mHandler, "background", backConstants, true);
    mBgOffloadBroadcastQueue = new BroadcastQueue(this, mHandler, "offload_bg", offloadConstants, true);
    mFgOffloadBroadcastQueue = new BroadcastQueue(this, mHandler, "offload_fg", foreConstants, true);
    mBroadcastQueues[0] = mFgBroadcastQueue;
    mBroadcastQueues[1] = mBgBroadcastQueue;
    mBroadcastQueues[2] = mBgOffloadBroadcastQueue;
    mBroadcastQueues[3] = mFgOffloadBroadcastQueue;
    // 初始化后盾服务治理对象
    mServices = new ActiveServices(this);
    //ContentProvider helper
    mCpHelper = new ContentProviderHelper(this, true);
    // 监控零碎运行状况
    mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
    // 处理错误信息
    mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
    mUidObserverController = new UidObserverController(mUiHandler);
    // 初始化 /data/system 目录
    final File systemDir = SystemServiceManager.ensureSystemDir();
    //BatteryStatsService
    mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, BackgroundThread.get().getHandler());
    mBatteryStatsService.getActiveStatistics().readLocked();
    mBatteryStatsService.scheduleWriteToDisk();
    mOnBattery = DEBUG_POWER ? true: mBatteryStatsService.getActiveStatistics().getIsOnBattery();
    mBatteryStatsService.getActiveStatistics().setCallback(this);
    mOomAdjProfiler.batteryPowerChanged(mOnBattery);
    // 创立过程统计服务
    mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
    //AppOpsService
    mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
    mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
    //UserController 治理多用户过程
    mUserController = new UserController(this);
    //PendingIntent 治理
    mPendingIntentController = new PendingIntentController(mHandlerThread.getLooper(), mUserController, mConstants);
    ...
    // 初始化 ActivityTaskManagerService 配置
    mActivityTaskManager = atm;
    mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, DisplayThread.get().getLooper());
    // 获取 LocalService 对象,继承于 ActivityTaskManagerInternal
    mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
    mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
    mSdkSandboxSettings = new SdkSandboxSettings(mContext);
    // 初始化监控
    Watchdog.getInstance().addMonitor(this);
    // 监控线程是否死锁
    Watchdog.getInstance().addThread(mHandler);
    // bind background threads to little cores
    // this is expected to fail inside of framework tests because apps can't touch cpusets directly
    // make sure we've already adjusted system_server's internal view of itself first
    updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
    try {Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(), Process.THREAD_GROUP_SYSTEM);
        Process.setThreadGroupAndCpuset(mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(), Process.THREAD_GROUP_SYSTEM);
    } catch(Exception e) {Slog.w(TAG, "Setting background thread cpuset failed");
    }
    mInternal = new LocalService();
    mPendingStartActivityUids = new PendingStartActivityUids();
    mTraceErrorLogger = new TraceErrorLogger();
    mComponentAliasResolver = new ComponentAliasResolver(this);
}

联合 AMS 的构造函数,大抵解决以下内容

  • 创立 ServiceThread 音讯循环线程,并于 MainHandler 关联
  • 创立一些服务以及 /data/system 系统目录创立
  • 初始化 Watchdog 并监控零碎、线程运行状况
  • 初始化播送队列
  • 其它初始化内容

ActivityManagerService.start() 启动办法,次要将服务注册到 ServiceManager 和 LocalServices 中供后续调用

private void start() {
    // 注册服务到 LocalService
    //LocalServices.addService(BatteryStatsInternal.class, new LocalService());
    //ServiceManager.addService(BatteryStats.SERVICE_NAME, asBinder());
    mBatteryStatsService.publish();
    // 零碎操作
    //ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
    //LocalServices.addService(AppOpsManagerInternal.class, mAppOpsManagerInternal);
    mAppOpsService.publish();
    // 利用过程信息
    //LocalServices.addService(ProcessStatsInternal.class, new LocalService());
    mProcessStats.publish();
    // 增加本地零碎服务接口
    //mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
    //mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
    LocalServices.addService(ActivityManagerInternal.class, mInternal);
    LocalManagerRegistry.addManager(ActivityManagerLocal.class, (ActivityManagerLocal) mInternal);
    //LocalServices 注册实现后,在 ActivityTaskManagerService 获取该对象
    mActivityTaskManager.onActivityManagerInternalAdded();
    //LocalServices 注册实现后,在 PendingIntentController 获取该对象
    mPendingIntentController.onActivityManagerInternalAdded();
    //AppProfiler 获取
    mAppProfiler.onActivityManagerInternalAdded();
    // 初始化最近要害事件日志
    CriticalEventLog.init();}

6.1 startBootstrapServices

bootstrap 源码内容

private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
    // 初始化 Watchdog
    final Watchdog watchdog = Watchdog.getInstance();
    watchdog.start();
    // 退出 dumper 汇合
    mDumper.addDumpable(watchdog);
    // 提交系统配置初始化工作到线程池
    final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
    SystemServerInitThreadPool.submit(SystemConfig: :getInstance, TAG_SYSTEM_CONFIG);
    // Platform compat service is used by ActivityManagerService, PackageManagerService, and
    // possibly others in the future. b/135010838.
    // 零碎外部 api 变更
    PlatformCompat platformCompat = new PlatformCompat(mSystemContext);
    ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat);
    ServiceManager.addService(Context.PLATFORM_COMPAT_NATIVE_SERVICE, new PlatformCompatNative(platformCompat));
    AppCompatCallbacks.install(new long[0]);
    // 启动文件完整性操作服务
    mSystemServiceManager.startService(FileIntegrityService.class);
    // Wait for installd to finish starting up so that it has a chance to
    // create critical directories such as /data/user with the appropriate
    // permissions.  We need this to complete before we initialize other services.
    //Installer 继承于 SystemSerivce, 期待零碎服务装置实现再初始化其它服务
    Installer installer = mSystemServiceManager.startService(Installer.class);
    // In some cases after launching an app we need to access device identifiers,
    // therefore register the device identifier policy before the activity manager.
    // 在 ActivityManager 启动前注册设施标识符(序列号)
    mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
    // Uri Grants Manager.
    // 治理 Uri Permission
    mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
    // Tracks rail data to be used for power statistics.
    // 启动零碎服务电量应用统计服务,WI-FI、GPS、显示器,提供数据监听回调
    mSystemServiceManager.startService(PowerStatsService.class);
    //native 办法,启动跨过程通信服务
    //startStatsHidlService();
    //startStatsAidlService();
    startIStatsService();
    // Start MemtrackProxyService before ActivityManager, so that early calls
    // to Memtrack::getMemory() don't fail.
    // 内存监控代理服务
    startMemtrackProxyService();
    // Activity manager runs the show.
    // TODO: Might need to move after migration to WM.
    // 获取 ActivityManager
    ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService();
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
    mWindowManagerGlobalLock = atm.getGlobalLock();

    // Data loader manager service needs to be started before package manager
    //SystemService 数据加载管理器
    mDataLoaderManagerService = mSystemServiceManager.startService(DataLoaderManagerService.class);

    // Incremental service needs to be started before package manager
    t.traceBegin("StartIncrementalService");
    mIncrementalServiceHandle = startIncrementalService();
    t.traceEnd();

    // Power manager needs to be started early because other services need it.
    // Native daemons may be watching for it to be registered so it must be ready
    // to handle incoming binder calls immediately (including being able to verify
    // the permissions for those calls).
    // 启动电源治理服务
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    // 启动 hal 监听事件服务
    mSystemServiceManager.startService(ThermalManagerService.class);
    mSystemServiceManager.startService(HintManagerService.class);
    t.traceEnd();

    // Now that the power manager has been started, let the activity manager
    // initialize power management features.
    // 后面已启动电源治理服务,当初通过 ActivityManager 初始化电源治理
    mActivityManagerService.initPowerManagement();
    // Bring up recovery system in case a rescue party needs a reboot
    // 恢复模式
    mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);
    // Now that we have the bare essentials of the OS up and running, take
    // note that we just booted, which might send out a rescue party if
    // we're stuck in a runtime restart loop.
    // 已启动完根本配置服务,注册零碎状况监听
    RescueParty.registerHealthObserver(mSystemContext);
    PackageWatchdog.getInstance(mSystemContext).noteBoot();

    // Manages LEDs and display backlight so we need it to bring up the display.
    // 启动显示器服务
    mSystemServiceManager.startService(LightsService.class);
    // Package manager isn't started yet; need to use SysProp not hardware feature
    if (SystemProperties.getBoolean("config.enable_display_offload", false)) {mSystemServiceManager.startService(WEAR_DISPLAYOFFLOAD_SERVICE_CLASS);
    }
    // Package manager isn't started yet; need to use SysProp not hardware feature
    if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
    }
    // Display manager is needed to provide display metrics before package manager
    // starts up.
    // 启动显示窗口服务
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
    // We need the default display before we can initialize the package manager.
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
    // Only run "core" apps if we're encrypting the device.
    String cryptState = VoldProperties.decrypt().orElse("");
    if (ENCRYPTING_STATE.equals(cryptState)) {Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
        mOnlyCore = true;
    } else if (ENCRYPTED_STATE.equals(cryptState)) {Slog.w(TAG, "Device encrypted - only parsing core apps");
        mOnlyCore = true;
    }
    // Start the package manager.
    if (!mRuntimeRestart) {FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED, FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__PACKAGE_MANAGER_INIT_START, SystemClock.elapsedRealtime());
    }
    // 启动域名验证服务
    DomainVerificationService domainVerificationService = new DomainVerificationService(mSystemContext, SystemConfig.getInstance(), platformCompat);
    mSystemServiceManager.startService(domainVerificationService);
    // 包管理器
    IPackageManager iPackageManager;
    t.traceBegin("StartPackageManagerService");
    try {Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
        Pair < PackageManagerService,
        IPackageManager > pmsPair = PackageManagerService.main(mSystemContext, installer, domainVerificationService, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
        mPackageManagerService = pmsPair.first;
        iPackageManager = pmsPair.second;
    } finally {Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
    }
    // Now that the package manager has started, register the dex load reporter to capture any
    // dex files loaded by system server.
    // These dex files will be optimized by the BackgroundDexOptService.
    SystemServerDexLoadReporter.configureSystemServerDexReporter(iPackageManager);
    mFirstBoot = mPackageManagerService.isFirstBoot();
    mPackageManager = mSystemContext.getPackageManager(); 
    if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED, FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__PACKAGE_MANAGER_INIT_READY, SystemClock.elapsedRealtime());
    }
    // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
    // A/B artifacts after boot, before anything else might touch/need them.
    // Note: this isn't needed during decryption (we don't have /data anyways).
    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();}
        }
    }
    // 启动用户治理服务
    mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
    // 初始化零碎属性资源
    // Initialize attribute cache used to cache resources from packages.
    AttributeCache.init(mSystemContext);
    // Set up the Application instance for the system process and get started.
    //1. 增加 meminfo\dbinfo\permission\processinfo\cacheinfo 服务
    //2. 启动线程装置 ApplicationInfo
    //3. 同步监控并锁定 ApplicationInfo 过程,缓存监控,OOM 监控
    //4. 监控应用程序操作
    mActivityManagerService.setSystemProcess();
    // The package receiver depends on the activity service in order to get registered.
    platformCompat.registerPackageReceiver(mSystemContext);
    // Complete the watchdog setup with an ActivityManager instance and listen for reboots
    // Do this only after the ActivityManagerService is properly started as a system process
    // 初始化 watchdog
    watchdog.init(mSystemContext, mActivityManagerService);
    // DisplayManagerService needs to setup android.display scheduling related policies
    // since setSystemProcess() would have overridden policies due to setProcessGroup
    // 设置 DMS 调度策略
    mDisplayManagerService.setupSchedulerPolicies();
    // Manages Overlay packages
    // 启动 Overlay 资源管理服务
    mSystemServiceManager.startService(new OverlayManagerService(mSystemContext));
    // Manages Resources packages
    ResourcesManagerService resourcesService = new ResourcesManagerService(mSystemContext);
    resourcesService.setActivityManagerService(mActivityManagerService);
    mSystemServiceManager.startService(resourcesService);
    // 传感器
    mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));
    if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
        // DisplayManager needs the overlay immediately.
        mActivityManagerService.updateSystemUiContext();
        LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();}
    // The sensor service needs access to package manager service, app op
    // service, and permissions service, therefore we start it after them.
    t.traceBegin("StartSensorService");
    mSystemServiceManager.startService(SensorService.class);
    t.traceEnd();
    t.traceEnd(); // startBootstrapServices completed}

6.2 startCoreServices

启动的外围服务 BatteryLooperStateUsageStatsService 等,具体细节可看源码

6.3 startOtherServices

启动其它服务为运行利用筹备,该办法源码特地长,大抵启动服务 NetworkWMS[TelephonyRegistry]如有须要可进入源码浏览, 咱们持续看次要节点

mActivityManagerService.systemReady(() - >{
    // 零碎 service 曾经筹备实现
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
    // 监控 native crashs
    try {mActivityManagerService.startObservingNativeCrashes();
    } catch(Throwable e) {reportWtf("observing native crashes", e);
    }
    ...
    // No dependency on Webview preparation in system server. But this should
    // be completed before allowing 3rd party
    // 在 webView 筹备好后,第三方 apk 能够调用
    final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
    Future < ?>webviewPrep = null;
    if (!mOnlyCore && mWebViewUpdateService != null) {webviewPrep = SystemServerInitThreadPool.submit(() - >{Slog.i(TAG, WEBVIEW_PREPARATION);
            TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
            traceLog.traceBegin(WEBVIEW_PREPARATION);
            ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
            mZygotePreload = null;
            mWebViewUpdateService.prepareWebViewInSystemServer();
            traceLog.traceEnd();},WEBVIEW_PREPARATION);
    }
    // 一系列零碎组件筹备实现
    ...
    networkManagementF.systemReady();
    networkPolicyF.networkScoreAndNetworkManagementServiceReady();
    connectivityF.systemReady();
    vpnManagerF.systemReady();
    vcnManagementF.systemReady();
    networkPolicyF.systemReady(networkPolicyInitReadySignal);
    ...
    // 期待所有 app 数据预加载
    mPackageManagerService.waitForAppDataPrepared();
    // It is now okay to let the various system services start their
    // third party code...
    // confirm webview completion before starting 3rd party
    // 期待 WebView 筹备实现
    if (webviewPrep != null) {ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
    }
    // 三方 app 能够启动
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
    // 启动在独自模块中运行的网络堆栈通信服务
    try {
        // Note : the network stack is creating on-demand objects that need to send
        // broadcasts, which means it currently depends on being started after
        // ActivityManagerService.mSystemReady and ActivityManagerService.mProcessesReady
        // are set to true. Be careful if moving this to a different place in the
        // startup sequence.
        NetworkStackClient.getInstance().start();
    } catch(Throwable e) {reportWtf("starting Network Stack", e);
    }
    // 一系列组件曾经筹备好并运行
    ...
    countryDetectorF.systemRunning();
    networkTimeUpdaterF.systemRunning();
    inputManagerF.systemRunning();
    telephonyRegistryF.systemRunning();
    mediaRouterF.systemRunning();
    ...
    incident.systemRunning();
    ...
},t);
// 启动 SystemUI, 快靠近 Launcher 启动
try {startSystemUi(context, windowManagerF);
} catch(Throwable e) {reportWtf("starting System UI", e);
}
//startSystemUi
private static void startSystemUi(Context context, WindowManagerService windowManager) {
    // 获取本地包治理服务
    PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
    // 设置启动 intent
    Intent intent = new Intent();
    intent.setComponent(pm.getSystemUiServiceComponent());
    intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
    // 对阵零碎用户启动服务
    context.startServiceAsUser(intent, UserHandle.SYSTEM);
    //systemUI 启动后调用
    windowManager.onSystemUiStarted();}
//onSystemUiStarted 理论调用最终指向 PhoneWindowManager.java
private void bindKeyguard() {synchronized(mLock) {if (mKeyguardBound) {return;}
        mKeyguardBound = true;
    }
    // 绑定 keyguardService 服务
    mKeyguardDelegate.bindService(mContext);
}

7.AMS.systemReady 办法

// 通过以上所有 ready\running 工作,当初正式进入 AMS.systemReady 办法
public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
    //ActivityManager 筹备实现
    mSystemServiceManager.preSystemReady();
    // 锁定并执行上述所有 ready\running 服务
    synchronized(this) {if (mSystemReady) {
            // If we're done calling all the receivers, run the next"boot phase" passed in
            // by the SystemServer
            if (goingCallback != null) {goingCallback.run();
            }
            return;
        }
        // 所有工作准备就绪
        mLocalDeviceIdleController = LocalServices.getService(DeviceIdleInternal.class);
        mActivityTaskManager.onSystemReady();
        // Make sure we have the current profile info, since it is needed for security checks.
        mUserController.onSystemReady();
        mAppOpsService.systemReady();
        mProcessList.onSystemReady();
        mAppRestrictionController.onSystemReady();
        // 设置筹备实现标记
        mSystemReady = true;
    }

    try {sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE)).getSerial();} catch(RemoteException e) {}
    // 清理过程
    ArrayList < ProcessRecord > procsToKill = null;
    synchronized(mPidsSelfLocked) {for (int i = mPidsSelfLocked.size() - 1; i >= 0; i--) {ProcessRecord proc = mPidsSelfLocked.valueAt(i);
            if (!isAllowedWhileBooting(proc.info)) {if (procsToKill == null) {procsToKill = new ArrayList < ProcessRecord > ();
                }
                procsToKill.add(proc);
            }
        }
    }
    synchronized(this) {if (procsToKill != null) {for (int i = procsToKill.size() - 1; i >= 0; i--) {ProcessRecord proc = procsToKill.get(i);
                Slog.i(TAG, "Removing system update proc:" + proc);
                mProcessList.removeProcessLocked(proc, true, false, ApplicationExitInfo.REASON_OTHER, ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE, "system update done");
            }
        }

        // Now that we have cleaned up any update processes, we
        // are ready to start launching real processes and know that
        // we won't trample on them any more.
        mProcessesReady = true;
    }
    ...
    ...
    // 如果 systemReady = true 未标记实现,执行此处 ready\running 服务
    if (goingCallback != null) goingCallback.run();
    ...
    ...
    // 给 BatteryStatsService 发送状态
    mBatteryStatsService.onSystemReady();
    mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, Integer.toString(currentUserId), currentUserId);
    mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, Integer.toString(currentUserId), currentUserId);
    ...
    ...
    synchronized(this) {
        // Only start up encryption-aware persistent apps; once user is
        // unlocked we'll come back around and start unaware apps
        t.traceBegin("startPersistentApps");
        // 启动 startPersistentApps
        startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
        ...
        boolean isBootingSystemUser = currentUserId == UserHandle.USER_SYSTEM;
        // Some systems - like automotive - will explicitly unlock system user then switch
        // to a secondary user.
        // TODO(b/242195409): this workaround shouldn't be necessary once we move
        // the headless-user start logic to UserManager-land.
        if (isBootingSystemUser && !UserManager.isHeadlessSystemUserMode()) {
            // 启动 Launcher 过程, 回调给 RootWindowContainer.startHomeOnAllDisplays,mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
        }
        ...
        t.traceBegin("resumeTopActivities");
        mAtmInternal.resumeTopActivities(false
        ...
    }
}
//startHomeOnAllDisplays 最终调用 - RootWindowContainer.java
public boolean startHomeOnTaskDisplayArea(int userId, String reason, TaskDisplayArea taskDisplayArea, boolean allowInstrumenting, boolean fromHomeKey) {
    ...
    ...
    // 获取 homeIntent
    Intent homeIntent = null;
    // 查问 ActivityInfo
    ActivityInfo aInfo = null;
    if (taskDisplayArea == getDefaultTaskDisplayArea()) {
        // 通过 ActivityTaskManagerService 获取 intent
        homeIntent = mService.getHomeIntent();
        // 通过 PackageManagerService 解析 intent
        aInfo = resolveHomeActivity(userId, homeIntent);
    } else if (shouldPlaceSecondaryHomeOnDisplayArea(taskDisplayArea)) {
        Pair < ActivityInfo,
        Intent > info = resolveSecondaryHomeActivity(userId, taskDisplayArea);
        aInfo = info.first;
        homeIntent = info.second;
    }
    ...
    ...
    // Updates the home component of the intent.
    // 更新设置 intent 参数
    homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
    homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
    // Updates the extra information of the intent.
    if (fromHomeKey) {homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true);
        if (mWindowManager.getRecentsAnimationController() != null) {mWindowManager.getRecentsAnimationController().cancelAnimationForHomeStart();}
    }
    homeIntent.putExtra(WindowManagerPolicy.EXTRA_START_REASON, reason);
    // Update the reason for ANR debugging to verify if the user activity is the one that
    // actually launched.
    final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId(aInfo.applicationInfo.uid) + ":" + taskDisplayArea.getDisplayId();
    // 通过获取到的 intent、aInfo 调用 startHomeActivity 启动 launcher
    mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason, taskDisplayArea);
    return true;
}
//startHomeActivity 办法 - ActivityStartController.java
void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason, TaskDisplayArea taskDisplayArea) {
    //ActivityOptions 一系列参数
    final ActivityOptions options = ActivityOptions.makeBasic();
    options.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);
    if (!ActivityRecord.isResolverActivity(aInfo.name)) {options.setLaunchActivityType(ACTIVITY_TYPE_HOME);
    }
    final int displayId = taskDisplayArea.getDisplayId();
    options.setLaunchDisplayId(displayId);
    options.setLaunchTaskDisplayArea(taskDisplayArea.mRemoteToken.toWindowContainerToken());
    // 执行启动 executeRequest - execute()在 ActivityStarter.java 中
    mLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity:" + reason).setOutActivity(tmpOutRecord).setCallingUid(0).setActivityInfo(aInfo).setActivityOptions(options.toBundle()).execute();
    ...
}
  1. execute()办法解决 Activity 启动申请,进入到
  2. executeRequest(mRequest); 执行执行一系列权限查看,进入到
  3. startActivityUnchecked()校验初步权限查看是否实现,进入到
  4. startActivityInner()启动 Activity,并确定是否将 activity 增加到栈顶, 进入到
  5. startActivityLocked()判断以后 activity 是否可见以及是否须要为其新建 Task,并将 ActivityRecord 退出到 Task 栈顶中, 进入到
  6. resumeFocusedTasksTopActivities() – RootWindowContainer.java , 次要判断 targetRootTask 是否处于栈顶,同时判断 task 是否处于暂停状态,进入到
  7. resumeTopActivityUncheckedLocked() – Task.java, 递归调用该办法并查找栈顶可显示 activity 以及状态是否暂停,进入到
  8. resumeTopActivityInnerLocked() – Task.java, 该办法次要解决 ActivityRecord、设置 resume 状态、筹备启动 activity,进入到
  9. resumeTopActivity() – TaskFragment.java, 查找栈顶 activity 是否处于 running,查看所有暂停操作是否实现,进入到
  10. startSpecificActivity() – ActivityTaskSupervisor.java, 如果 activity 已运行则间接启动,未运行则启动指标 Activity, 开启启动新过程,进入到
  11. startProcessAsync() – ActivityTaskManagerService.java,通过 handle 发送音讯给 AMS 启动过程,ATMS 不持有该锁,回到 AMS 中,进入到
  12. startProcessLocked() – ActivityManagerService.java, 持续调用
  13. ProcessList.startProcessLocked() – ProcessList.java, 最终调用 startProcess(), 定义

    final String entryPoint = "android.app.ActivityThread";
    final Process.ProcessStartResult startResult = startProcess(hostingRecord, entryPoint, app, uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith, startUptime);

    以上调用链最终进入 startProcess() – ProcessList.java,依据参数类型启动过程

    final Process.ProcessStartResult startResult;
    boolean regularZygote = false;
    if (hostingRecord.usesWebviewZygote()) {startResult = startWebView(entryPoint, app.processName, uid, uid, gids, runtimeFlags, mountExternal, app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, app.info.dataDir, null, app.info.packageName, app.getDisabledCompatChanges(), new String[] {PROC_START_SEQ_IDENT + app.getStartSeq()
     });
    } else if (hostingRecord.usesAppZygote()) {final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
     // We can't isolate app data and storage data as parent zygote already did that.
     startResult = appZygote.getProcess().start(entryPoint, app.processName, uid, uid, gids, runtimeFlags, mountExternal, app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, app.info.dataDir, null, app.info.packageName,
     /*zygotePolicyFlags=*/
     ZYGOTE_POLICY_FLAG_EMPTY, isTopApp, app.getDisabledCompatChanges(), pkgDataInfoMap, allowlistedAppDataInfoMap, false, false, new String[] {PROC_START_SEQ_IDENT + app.getStartSeq()
     });
    } else {
     regularZygote = true;
     startResult = Process.start(entryPoint, app.processName, uid, uid, gids, runtimeFlags, mountExternal, app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, app.info.dataDir, invokeWith, app.info.packageName, zygotePolicyFlags, isTopApp, app.getDisabledCompatChanges(), pkgDataInfoMap, allowlistedAppDataInfoMap, bindMountAppsData, bindMountAppStorageDirs, new String[] {PROC_START_SEQ_IDENT + app.getStartSeq()
     });
    }

    regularZygote 示意惯例的 zygote32/zygote64,此处最终调用 Process.start()创立过程,通过 zygoteWriter 发送给 zygote 过程,告诉 zygote 开始 fork 过程,在前文 ZygoteServer 中
    【5. ZygoteInit.java 类 – 8 大节】,此处会循环接管来自 AMS 发送的音讯,且 entryPoint 携带标记 “android.app.ActivityThread”,此时子过程入口即为:ActivityThread 的 main(),
    基于此 launcher 过程曾经启动,ActivityThread.main()最初调用 Looper.loop()进入循环期待,子过程启动实现后 AMS 接着实现 activity 启动操作

8. 启动 Activity

通过上一节繁冗的的调用链,最终来到利用启动入口

public static void main(String[] args) {
    // 装置选择性零碎调用拦挡
    AndroidOs.install();
    // 敞开 CloseGuard
    CloseGuard.setEnabled(false);
    // 初始化 user environment
    Environment.initForCurrentUser();
    ...
    // Call per-process mainline module initialization.
    initializeMainlineModules();
    // 设置过程 args
    Process.setArgV0("<pre-initialized>");
    Looper.prepareMainLooper();
    // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
    // It will be in the format "seq=114"
    long startSeq = 0;
    if (args != null) {for (int i = args.length - 1; i >= 0; --i) {if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {startSeq = Long.parseLong(args[i].substring(PROC_START_SEQ_IDENT.length()));
            }
        }
    }
    // 初始化 ActivityThread
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);
    // 获取 MainThreadHandler
    if (sMainThreadHandler == null) {sMainThreadHandler = thread.getHandler();
    }
    if (false) {Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));
    }
    // 进入循环期待
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}
// 持续看下 thread.attach()
private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mConfigurationController = new ConfigurationController(this);
    mSystemThread = system;
    if (!system) {android.ddm.DdmHandleAppName.setAppName("<pre-initialized>", UserHandle.myUserId());
        //RuntimeInit 设置 launcher binder 服务:ApplicationThread
        RuntimeInit.setApplicationObject(mAppThread.asBinder());
        // 获取 ActivityManagerService, 由 IActivityManager 代理
        final IActivityManager mgr = ActivityManager.getService();
        try {
            // 通过 IApplicationThread 跨过程告诉 launcher 过程开始绑定
            mgr.attachApplication(mAppThread, startSeq);
        } catch(RemoteException ex) {throw ex.rethrowFromSystemServer();
        }
        ...
    } else {...}
    ...
}
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {synchronized (this) {
        // 通过 binder 获取过程 id
        int callingPid = Binder.getCallingPid();
        // 获取 user id
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        // 启动正在期待的 activity
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        Binder.restoreCallingIdentity(origId);
    }
}

再往下就是创立 Application 对象,回调 attachBaseContext(), 初始化 ContentProvider, 回调 onCreate(), 持续回调 Application onCreate(),
尔后就是 Activity 创立,调用 attach(), 执行 onCreate 办法,回调 Activity 各个生命周期办法,至此 Launcher 整体启动实现,AMS 启动 activity 波及屡次跨过程通信
,与 zygote 通信判断过程是否存在,不存在则 fork 新过程,并回调 AMS 执行其初始化办法,最初执行 ActivityThread.main(), 整体调用链十分繁冗,但各个模块各司其职,
咱们在应用层进行组件工程根底模型宰割时也可参考其外部的架构形式

9. 文档阐明

因为源码流程较长,整体调用链十分繁冗,可能存在错漏的中央,欢送在浏览时提出问题和有余

参考文档:

Android Code Search

/ – OpenGrok cross reference for / (aospxref.com)

torvalds/linux: Linux kernel source tree (github.com)

首页 – 内核技术中文网 – 构建全国最权威的内核技术交换分享论坛 (0voice.com)

ActivityManagerService 启动过程 – Gityuan 博客 | 袁辉辉的技术博客

init 过程 – personal blog (liujunyang.site)

正文完
 0