Android系統(tǒng)啟動(dòng)之Init流程(下)

image.png

目錄

第一篇:Android系統(tǒng)啟動(dòng)之bootloader
第二篇:Android系統(tǒng)啟動(dòng)之Init流程(上)
第三篇:Android系統(tǒng)啟動(dòng)之Init流程(下)
第四篇:Android系統(tǒng)啟動(dòng)之init.rc文件解析過(guò)程
第五篇:Android系統(tǒng)啟動(dòng)之zyogte進(jìn)程
第六篇:Android系統(tǒng)啟動(dòng)之zyogte進(jìn)程java(上)
第七篇:Android系統(tǒng)啟動(dòng)之zyogte進(jìn)程java(下)
第八篇:Android系統(tǒng)啟動(dòng)之SystemServer

本節(jié)主要是對(duì)代碼進(jìn)行解釋,十分枯燥.O(∩_∩)O哈哈~

下面開(kāi)始

啟動(dòng)代碼(main)

主要分為七部分:

第一部分

判斷啟動(dòng)部分,如果是ueventd,調(diào)用ueventd_main主函數(shù),如果是watchdogd,調(diào)用watchdogd_main主函數(shù).

第二部分

add_environment導(dǎo)入環(huán)境變量,并根據(jù)環(huán)境變量判斷是否是第一次啟動(dòng).

第三部分

創(chuàng)建一些基本的目錄,包括/dev、/porc、/sysfc等。同時(shí)把一些文件系統(tǒng),如tmpfs、devpt、proc、sysfs等mount到項(xiàng)目的目錄。

目錄 功能
tmpfs 一種基于內(nèi)存的文件系統(tǒng),mount后就可以使用。tmpfs文件系統(tǒng)下的文件都存放在內(nèi)存中,訪問(wèn)速度快,但是關(guān)機(jī)后所有內(nèi)容偶讀會(huì)丟失,因此tmpfs文件系統(tǒng)比較合適存放一些臨時(shí)性的文件。
devpts 虛擬終端文件系統(tǒng),它通常mount在目錄dev/pts下
proc 一種基于內(nèi)存的虛擬文件系統(tǒng),它可以看作是內(nèi)核內(nèi)部數(shù)據(jù)結(jié)構(gòu)的接口,通過(guò)它可以獲得系統(tǒng)的信息,同時(shí)能夠在運(yùn)行時(shí)修改特定的內(nèi)核參數(shù)
sysfs proc文件系統(tǒng)類似,它是Linux2.6內(nèi)核引入的,作用是把系統(tǒng)的設(shè)備和總線按層次組織起來(lái),使得它們可以在用戶空間存取

然后使用InitKernelLogging開(kāi)啟log,使得init進(jìn)程可以使用kernel的log系統(tǒng)來(lái)輸出log.

為什么要使用kernel的log系統(tǒng)?

因?yàn)榇藭r(shí)Android系統(tǒng)的log還沒(méi)有啟動(dòng),所以需要使用kernel的log系統(tǒng).

第四部分

SELinex的知識(shí)參考android之SELinux小記
主要使用函數(shù)selinux_initialize啟動(dòng)SELinux.

另外:

close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));

判斷/dev/.booting文件是否可讀寫(xiě)和創(chuàng)建.

在/dev目錄下創(chuàng)建一個(gè)空文件".booting"表示初始化正在進(jìn)行
is_booting()函數(shù)會(huì)依靠空文件".booting"來(lái)判斷是否進(jìn)程處于初始化中,初始化結(jié)束后,這個(gè)文件會(huì)被刪除

第五部分

初始化系統(tǒng)屬性存儲(chǔ)區(qū)域:

property_init();

property_init函數(shù)在system/core/init/property_service.cpp實(shí)現(xiàn):

  void property_init() {
      if (__system_property_area_init()) {
          LOG(ERROR) << "Failed to initialize property area";
          exit(1);
      }
  }

然后,設(shè)定內(nèi)核處理命令行.
并設(shè)定相關(guān)系統(tǒng)屬性export_kernel_boot_props

  static void export_kernel_boot_props() {
      struct {
          const char *src_prop;
          const char *dst_prop;
          const char *default_value;
      } prop_map[] = {
          { "ro.boot.serialno",   "ro.serialno",   "", },
          { "ro.boot.mode",       "ro.bootmode",   "unknown", },
          { "ro.boot.baseband",   "ro.baseband",   "unknown", },
          { "ro.boot.bootloader", "ro.bootloader", "unknown", },
          { "ro.boot.hardware",   "ro.hardware",   "unknown", },
          { "ro.boot.revision",   "ro.revision",   "0", },
      };
      for (size_t i = 0; i < arraysize(prop_map); i++) {
          std::string value = GetProperty(prop_map[i].src_prop, "");
          property_set(prop_map[i].dst_prop, (!value.empty()) ? value : prop_map[i].defau     lt_value);
      }
  }

export_kernel_boot_props這個(gè)函數(shù),它就是設(shè)置一些屬性,設(shè)置ro屬性根據(jù)之前的ro.boot這類的屬性值,如果沒(méi)有設(shè)置成unknown,像之前我們有ro.boot.hardware,那我們就可以設(shè)置root.hardware這樣的屬性。

第六部分

  1. 調(diào)用epoll_create1創(chuàng)建epoll句柄,如果創(chuàng)建失敗,則退出。
  2. 調(diào)用signal_handler_init()函數(shù),裝載進(jìn)程信號(hào)處理器。
  3. 調(diào)用property_load_boot_defaults()函數(shù)解析根目錄的default.prop的屬性,設(shè)置默認(rèn)屬性配置的相關(guān)工作。
  4. 調(diào)用start_prperty_service()函數(shù),啟動(dòng)屬性服務(wù),并接受屬性的socket的fd加入到epoll中,定義了處理函數(shù)。
  5. 解析rc文件(重要).參考:Android系統(tǒng)啟動(dòng)之init.rc文件解析過(guò)程

signal_handler_init函數(shù)主要是當(dāng)子進(jìn)程被kill之后,會(huì)在父進(jìn)程接受一個(gè)信號(hào)。

處理這個(gè)信號(hào)的時(shí)候往sockpair一段寫(xiě)數(shù)據(jù),而另一端的fd是加入epoll中

init是一個(gè)守護(hù)進(jìn)程,為了防止init的子進(jìn)程稱為僵尸進(jìn)程(zombie process),需要init在子進(jìn)程結(jié)束時(shí)獲取子進(jìn)程的結(jié)束碼,通過(guò)結(jié)束碼將程序表中的子進(jìn)程移除,防止稱為僵尸進(jìn)程的子進(jìn)程占用程序表的空間(程序表的空間達(dá)到上線時(shí),系統(tǒng)就不能再啟動(dòng)新的進(jìn)城了,會(huì)引起嚴(yán)重的系統(tǒng)問(wèn)題)。

第七部分

啟動(dòng)守護(hù)進(jìn)程

源碼如下

int main(int argc, char** argv) {
//---------------------第一部分------------------------------------
// 根據(jù)傳入的參數(shù),運(yùn)行不同的主函數(shù)
//----------------------------------------------------------------------
    //匹配啟動(dòng)程序名
    if (!strcmp(basename(argv[0]), "ueventd")) {
        return ueventd_main(argc, argv);
    }

    if (!strcmp(basename(argv[0]), "watchdogd")) {
        return watchdogd_main(argc, argv);
    }

    if (REBOOT_BOOTLOADER_ON_PANIC) {
        InstallRebootSignalHandlers();
    }
//---------------------第二部分--------------------------------------
// 設(shè)定環(huán)境變量
//----------------------------------------------------------------------
    //設(shè)定環(huán)境變量
    add_environment("PATH", _PATH_DEFPATH);

    bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);

    //判斷是否是第一次
    if (is_first_stage) {
        boot_clock::time_point start_time = boot_clock::now();

        // Clear the umask.
        // 清楚權(quán)限掩碼
        umask(0);
//----------------------第三部分-------------------------------------
// 設(shè)定文件目錄并掛載對(duì)應(yīng)的設(shè)備
//----------------------------------------------------------------------
        // 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.
        // 創(chuàng)建文件系統(tǒng)和對(duì)應(yīng)的權(quán)限,并掛載
        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("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11));
        mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8));
        mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9));

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

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

        if (!DoFirstStageMount()) {
            LOG(ERROR) << "Failed to mount required partitions early ...";
            panic();
        }

        SetInitAvbVersionInRecovery();
//-----------------------第四部分-------------------------------------
// 啟動(dòng)SELinux,根據(jù)SELinux的配置重新啟動(dòng)init
//----------------------------------------------------------------------
        // Set up SELinux, loading the SELinux policy.
        // 設(shè)置SELinux,加載SEPolicy
        selinux_initialize(true);

        // We're in the kernel domain, so re-exec init to transition to the init domain now
        // that the SELinux policy has been loaded.
        // 根據(jù)SELinux的要求重新設(shè)定init文件屬性
        if (restorecon("/init") == -1) {
            PLOG(ERROR) << "restorecon failed";
            security_failure();
        }

        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", StringPrintf("%" PRIu64, start_ms).c_str(), 1);


        //設(shè)定參數(shù)
        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(ERROR) << "execv(\"" << path << "\") failed";
        security_failure();
    }

    // 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));
//-----------------------第五部分-------------------------------------
// 運(yùn)行屬性服務(wù),根據(jù)屬性值設(shè)定內(nèi)核命令
//----------------------------------------------------------------------
    //設(shè)定屬性值
    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.
    process_kernel_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.
    selinux_initialize(false);
    selinux_restore_context();
//-----------------------第六部分------------------------------------
// 啟動(dòng)服務(wù),并解析rc文件,根據(jù)rc文件啟動(dòng)進(jìn)程
//----------------------------------------------------------------------
    epoll_fd = epoll_create1(EPOLL_CLOEXEC);
    if (epoll_fd == -1) {
        PLOG(ERROR) << "epoll_create1 failed";
        exit(1);
    }

    signal_handler_init();

    property_load_boot_defaults();
    export_oem_lock_status();
    start_property_service();
    set_usb_controller();

    const BuiltinFunctionMap function_map;
    Action::set_function_map(&function_map);

    Parser& parser = Parser::GetInstance();
    parser.AddSectionParser("service",std::make_unique<ServiceParser>());
    parser.AddSectionParser("on", std::make_unique<ActionParser>());
    parser.AddSectionParser("import", std::make_unique<ImportParser>());
    std::string bootscript = GetProperty("ro.boot.init_rc", "");
    if (bootscript.empty()) {
        parser.ParseConfig("/init.rc");
        parser.set_is_system_etc_init_loaded(
                parser.ParseConfig("/system/etc/init"));
        parser.set_is_vendor_etc_init_loaded(
                parser.ParseConfig("/vendor/etc/init"));
        parser.set_is_odm_etc_init_loaded(parser.ParseConfig("/odm/etc/init"));
    } else {
        parser.ParseConfig(bootscript);
        parser.set_is_system_etc_init_loaded(true);
        parser.set_is_vendor_etc_init_loaded(true);
        parser.set_is_odm_etc_init_loaded(true);
    }

    // Turning this on and letting the INFO logging be discarded adds 0.2s to
    // Nexus 9 boot time, so it's disabled by default.
    if (false) parser.DumpState();

    ActionManager& am = ActionManager::GetInstance();

    am.QueueEventTrigger("early-init");

    // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
    am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
    // ... so that we can start queuing up actions that require stuff from /dev.
    am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
    am.QueueBuiltinAction(set_mmap_rnd_bits_action, "set_mmap_rnd_bits");
    am.QueueBuiltinAction(set_kptr_restrict_action, "set_kptr_restrict");
    am.QueueBuiltinAction(keychord_init_action, "keychord_init");
    am.QueueBuiltinAction(console_init_action, "console_init");

    // Trigger all the boot actions to get us started.
    am.QueueEventTrigger("init");

    // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
    // wasn't ready immediately after wait_for_coldboot_done
    am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");

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

    // Run all property triggers based on current state of the properties.
    am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
//---------------------第七部分--------------------------------------
// 啟動(dòng)結(jié)束,開(kāi)始守護(hù)服務(wù)(守護(hù)進(jìn)程)
//----------------------------------------------------------------------
    while (true) {
        // By default, sleep until something happens.
        int epoll_timeout_ms = -1;

        if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) {
            am.ExecuteOneCommand();
        }
        if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) {
            restart_processes();

            // If there's a process that needs restarting, wake up in time for that.
            if (process_needs_restart_at != 0) {
                epoll_timeout_ms = (process_needs_restart_at - time(nullptr)) * 1000;
                if (epoll_timeout_ms < 0) epoll_timeout_ms = 0;
            }

            // If there's more work to do, wake up again immediately.
            if (am.HasMoreCommands()) epoll_timeout_ms = 0;
        }

        epoll_event ev;
        int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms));
        if (nr == -1) {
            PLOG(ERROR) << "epoll_wait failed";
        } else if (nr == 1) {
            ((void (*)()) ev.data.ptr)();
        }
    }

    return 0;
}

參考

Android系統(tǒng)啟動(dòng)——2init進(jìn)程

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

相關(guān)閱讀更多精彩內(nèi)容

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