如何应对Android面试官 -> Android 系统启动流程浅析

前言


image.png

本章节主要分析 Android 系统启动流程;

Android系统启动的大概流程


当我们按下电源键的时候,就会从 Boot Rom 执行代码,就会加载一个 Boot loader 引导程序「此引导程序就会引导用户选择哪个系统启动,如果只有一个系统则直接命中」,Boot loader 就会拉起 Linux Kernel,Linux Kernel 就会从固定位置读取设置的一些参数,根据这些参数来加载驱动。Linux Kernel 通过 syscall 系统调用拉起用户态的第一个进程「init 进程,这个 init 进程会:初始化 Android 的一些属性服务,启动一系列的守护进程,启动 zygote 进程,启动 media server(多媒体相关的服务)」,当 zygote 进程启动之后会孵化出 system_server 进程,这个进程就会开启一系列的服务例如 ActivityManagerService,WindowManagerService,PackageManagerService,PowerManagerService 等等大概80多个服务;当我们通过 launcher 进程启动一个 app 的时候,就会通过zygote 进程 fork 出一个子进程,这个子进程就是我们 app 所在进程;

image.png

看到上面的流程,可能大家会有疑问了,为什么不 fork init 进程,不 fork SystemServer 进程呢?带着这些疑问我们继续往下分析;

init 进程分析


我们先来看下 init 进程的启动流程,进入 init.cpp 文件的 main 函数看起;

/*
*
* 1.C++中主函数有两个参数,第一个参数argc表示参数个数,第二个参数是参数列表,也就是具体的参数
*
* 2.init的main函数有两个其它入口,一是参数中有ueventd,进入ueventd_main,二是参数中有watchdogd,进入watchdogd_main
*
*/
int main(int argc, char** argv) {
    /*
    * 1.strcmp是String的一个函数,比较字符串,相等返回0
    * 2.C++中0也可以表示false
    * 3.basename是C库中的一个函数,得到特定的路径中的最后一个'/'后面的内容,
    * 比如/sdcard/miui_recovery/backup,得到的结果是backup
    */
    if (!strcmp(basename(argv[0]), "ueventd")) { //当argv[0]的内容为ueventd时,strcmp的值为0,!strcmp为1, 1表示true,也就执行ueventd_main,ueventd主要是负责设备节点的创建、权限设定等一
些列工作
        return ueventd_main(argc, argv);
    }
    // watchdogd俗称看门狗,用于系统出问题时重启系统
    if (!strcmp(basename(argv[0]), "watchdogd")) {
        return watchdogd_main(argc, argv);
    }

    if (argc > 1 && !strcmp(argv[1], "subcontext")) {
        InitKernelLogging(argv);
        const BuiltinFunctionMap function_map;
        return SubcontextMain(argc, argv, &function_map);
    }
    // 初始化重启系统的处理信号,内部通过 sigaction 注册信号,当监听到该信号时重启系统
    if (REBOOT_BOOTLOADER_ON_PANIC) {
        InstallRebootSignalHandlers();
    }
    // 查看是否有环境变量INIT_SECOND_STAGE
    bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);
    /*
     * 1.init的main方法会执行两次,由is_first_stage控制,first_stage就是第一阶段要做的事
     */
    if (is_first_stage) {
        boot_clock::time_point start_time = boot_clock::now();

        // Clear the umask. 清空文件权限
        umask(0);

        clearenv();
        setenv("PATH", _PATH_DEFPATH, 1);
        // Get the basic filesystem setup we need put together in the initramdisk
        // on / and then we'll let the rc file figure out the rest.
        // mount 用来挂载文件系统,mount 属于 linux 系统调用
        mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
        // 创建目录,第一个表示目录路径,第二个表示读写权限
        mkdir("/dev/pts", 0755);
        mkdir("/dev/socket", 0755);
        mount("devpts", "/dev/pts", "devpts", 0, NULL);
        #define MAKE_STR(x) __STRING(x)
        mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
        // Don't expose the raw commandline to unprivileged processes.
        // 用于修改文件/目录的读写权限
        chmod("/proc/cmdline", 0440);
        gid_t groups[] = { AID_READPROC };
        setgroups(arraysize(groups), groups);
        mount("sysfs", "/sys", "sysfs", 0, NULL);
        mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL);
        // mknod用于创建Linux中的设备文件
        mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11));

        if constexpr (WORLD_WRITABLE_KMSG) {
            mknod("/dev/kmsg_debug", S_IFCHR | 0622, makedev(1, 11));
        }

        mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8));
        mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9));

        // Mount staging areas for devices managed by vold
        // See storage config details at http://source.android.com/devices/storage/
        mount("tmpfs", "/mnt", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
              "mode=0755,uid=0,gid=1000");
        // /mnt/vendor is used to mount vendor-specific partitions that can not be
        // part of the vendor partition, e.g. because they are mounted read-write.
        mkdir("/mnt/vendor", 0755);

        // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually
        // talk to the outside world...
        InitKernelLogging(argv);

        LOG(INFO) << "init first stage started!";

        if (!DoFirstStageMount()) {
            LOG(FATAL) << "Failed to mount required partitions early ...";
        }
        // Avb即Android Verfied boot,功能包括Secure Boot, verfying boot 和 dmverity,
        // 原理都是对二进制文件进行签名,在系统启动时进行认证,确保系统运行的是合法的二进制镜像文件。
        // 其中认证的范围涵盖:bootloader,boot.img,system.img
        SetInitAvbVersionInRecovery(); // 在刷机模式下初始化avb的版本,不是刷机模式直接跳过

        // Enable seccomp if global boot option was passed (otherwise it is enabled in zygote).
        global_seccomp();

        // Set up SELinux, loading the SELinux policy.
        SelinuxSetupKernelLogging();
        SelinuxInitialize(); // 加载SELinux policy,也就是安全策略

        // We're in the kernel domain, so re-exec init to transition to the init domain now
        // that the SELinux policy has been loaded.
        /*
         * 1.这句英文大概意思是,我们执行第一遍时是在kernel domain,所以要重新执行init文件,切换到init domain,
         * 这样SELinux policy才已经加载进来了
         * 2.后面的security_failure函数会调用panic重启系统
         */
        if (selinux_android_restorecon("/init", 0) == -1) {
            PLOG(FATAL) << "restorecon failed of /init failed";
        }

        setenv("INIT_SECOND_STAGE", "true", 1);

        static constexpr uint32_t kNanosecondsPerMillisecond = 1e6;
        uint64_t start_ms = start_time.time_since_epoch().count() / kNanosecondsPerMillisecond;
        setenv("INIT_STARTED_AT", std::to_string(start_ms).c_str(), 1);

        char* path = argv[0];
        char* args[] = { path, nullptr };
        execv(path, args);

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

    // At this point we're in the second stage of init.
    InitKernelLogging(argv);
    LOG(INFO) << "init second stage started!";

    // Set up a session keyring that all processes will have access to. It
    // will hold things like FBE encryption keys. No process should override
    // its session keyring.
    keyctl_get_keyring_ID(KEY_SPEC_SESSION_KEYRING, 1);

    // Indicate that booting is in progress to background fw loaders, etc.
    close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
    // 初始化属性系统,并从指定文件读取属性
    property_init();

    // If arguments are passed both on the command line and in DT,
    // properties set in DT always have priority over the command-line ones.
    //接下来的一系列操作都是从各个文件读取一些属性,然后通过property_set设置系统属性
    // If arguments are passed both on the command line and in DT,
    // properties set in DT always have priority over the command-line ones.

    /*
     * 1.这句英文的大概意思是,如果参数同时从命令行和DT传过来,DT的优先级总是大于命令行的
     * 2.DT即device-tree,中文意思是设备树,这里面记录自己的硬件配置和系统运行参数,参考http://www.wowotech.net/linux_kenrel/why-dt.html
     */
    process_kernel_dt(); // 处理DT属性
    process_kernel_cmdline(); // 处理命令行属性

    // Propagate the kernel variables to internal variables
    // used by init as well as the current required properties.
    export_kernel_boot_props(); // 处理其他的一些属性

    // Make the time that init started available for bootstat to log.
    property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
    property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));

    // Set libavb version for Framework-only OTA match in Treble build.
    const char* avb_version = getenv("INIT_AVB_VERSION");
    if (avb_version) property_set("ro.boot.avb_version", avb_version);

    // Clean up our environment.
    // 清空这些环境变量,因为之前都已经存入到系统属性中去了
    unsetenv("INIT_SECOND_STAGE"); 
    unsetenv("INIT_STARTED_AT");
    unsetenv("INIT_SELINUX_TOOK");
    unsetenv("INIT_AVB_VERSION");

    // Now set up SELinux for second stage.
    SelinuxSetupKernelLogging();
    SelabelInitialize();
    SelinuxRestoreContext();
    // 创建epoll实例,并返回epoll的文件描述符
    epoll_f
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值