xref: /aosp_15_r20/system/core/init/first_stage_init.cpp (revision 00c7fec1bb09f3284aad6a6f96d2f63dfc3650ad)
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "first_stage_init.h"
18 
19 #include <dirent.h>
20 #include <fcntl.h>
21 #include <paths.h>
22 #include <stdlib.h>
23 #include <sys/mount.h>
24 #include <sys/stat.h>
25 #include <sys/sysmacros.h>
26 #include <sys/types.h>
27 #include <sys/utsname.h>
28 #include <unistd.h>
29 
30 #include <chrono>
31 #include <filesystem>
32 #include <string>
33 #include <thread>
34 #include <vector>
35 
36 #include <android-base/chrono_utils.h>
37 #include <android-base/file.h>
38 #include <android-base/logging.h>
39 #include <android-base/stringprintf.h>
40 #include <android/avf_cc_flags.h>
41 #include <fs_mgr.h>
42 #include <modprobe/modprobe.h>
43 #include <private/android_filesystem_config.h>
44 
45 #include "debug_ramdisk.h"
46 #include "first_stage_console.h"
47 #include "first_stage_mount.h"
48 #include "reboot_utils.h"
49 #include "second_stage_resources.h"
50 #include "snapuserd_transition.h"
51 #include "switch_root.h"
52 #include "util.h"
53 
54 using android::base::boot_clock;
55 
56 using namespace std::literals;
57 
58 namespace fs = std::filesystem;
59 
60 namespace android {
61 namespace init {
62 
63 namespace {
64 
65 enum class BootMode {
66     NORMAL_MODE,
67     RECOVERY_MODE,
68     CHARGER_MODE,
69 };
70 
FreeRamdisk(DIR * dir,dev_t dev)71 void FreeRamdisk(DIR* dir, dev_t dev) {
72     int dfd = dirfd(dir);
73 
74     dirent* de = nullptr;
75     while ((de = readdir(dir)) != nullptr) {
76         if (de->d_name == "."s || de->d_name == ".."s) {
77             continue;
78         }
79 
80         bool is_dir = false;
81 
82         if (de->d_type == DT_DIR || de->d_type == DT_UNKNOWN) {
83             struct stat info {};
84             if (fstatat(dfd, de->d_name, &info, AT_SYMLINK_NOFOLLOW) != 0) {
85                 continue;
86             }
87 
88             if (info.st_dev != dev) {
89                 continue;
90             }
91 
92             if (S_ISDIR(info.st_mode)) {
93                 is_dir = true;
94                 auto fd = openat(dfd, de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
95                 if (fd >= 0) {
96                     auto subdir =
97                             std::unique_ptr<DIR, decltype(&closedir)>{fdopendir(fd), closedir};
98                     if (subdir) {
99                         FreeRamdisk(subdir.get(), dev);
100                     } else {
101                         close(fd);
102                     }
103                 }
104             }
105         } else if (de->d_type == DT_REG) {
106             // Do not free snapuserd if we will need the ramdisk copy during the
107             // selinux transition.
108             if (de->d_name == "snapuserd"s && IsFirstStageSnapuserdRunning()) {
109                 continue;
110             }
111         }
112         unlinkat(dfd, de->d_name, is_dir ? AT_REMOVEDIR : 0);
113     }
114 }
115 
ForceNormalBoot(const std::string & cmdline,const std::string & bootconfig)116 bool ForceNormalBoot(const std::string& cmdline, const std::string& bootconfig) {
117     return bootconfig.find("androidboot.force_normal_boot = \"1\"") != std::string::npos ||
118            cmdline.find("androidboot.force_normal_boot=1") != std::string::npos;
119 }
120 
Copy(const char * src,const char * dst)121 static void Copy(const char* src, const char* dst) {
122     if (link(src, dst) == 0) {
123         LOG(INFO) << "hard linking " << src << " to " << dst << " succeeded";
124         return;
125     }
126     PLOG(FATAL) << "hard linking " << src << " to " << dst << " failed";
127 }
128 
129 // Move snapuserd before switching root, so that it is available at the same path
130 // after switching root.
PrepareSwitchRoot()131 void PrepareSwitchRoot() {
132     static constexpr const auto& snapuserd = "/system/bin/snapuserd";
133     static constexpr const auto& snapuserd_ramdisk = "/system/bin/snapuserd_ramdisk";
134     static constexpr const auto& dst = "/first_stage_ramdisk/system/bin/snapuserd";
135 
136     if (access(dst, X_OK) == 0) {
137         LOG(INFO) << dst << " already exists and it can be executed";
138         return;
139     }
140     auto dst_dir = android::base::Dirname(dst);
141     std::error_code ec;
142     if (access(dst_dir.c_str(), F_OK) != 0) {
143         if (!fs::create_directories(dst_dir, ec)) {
144             LOG(FATAL) << "Cannot create " << dst_dir << ": " << ec.message();
145         }
146     }
147 
148     // prefer the generic ramdisk copy of snapuserd, because that's on system side of treble
149     // boundary, and therefore is more likely to be updated along with the Android platform.
150     // The vendor ramdisk copy might be under vendor freeze, or vendor might choose not to update
151     // it.
152     if (access(snapuserd_ramdisk, F_OK) == 0) {
153         LOG(INFO) << "Using generic ramdisk copy of snapuserd " << snapuserd_ramdisk;
154         Copy(snapuserd_ramdisk, dst);
155     } else if (access(snapuserd, F_OK) == 0) {
156         LOG(INFO) << "Using vendor ramdisk copy of snapuserd " << snapuserd;
157         Copy(snapuserd, dst);
158     }
159 }
160 
GetPageSizeSuffix()161 std::string GetPageSizeSuffix() {
162     static const size_t page_size = sysconf(_SC_PAGE_SIZE);
163     if (page_size <= 4096) {
164         return "";
165     }
166     return android::base::StringPrintf("_%zuk", page_size / 1024);
167 }
168 
EndsWith(const std::string_view str,const std::string_view suffix)169 constexpr bool EndsWith(const std::string_view str, const std::string_view suffix) {
170     return str.size() >= suffix.size() &&
171            0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
172 }
173 
GetPageSizeSuffix(std::string_view dirname)174 constexpr std::string_view GetPageSizeSuffix(std::string_view dirname) {
175     if (EndsWith(dirname, "_16k")) {
176         return "_16k";
177     }
178     if (EndsWith(dirname, "_64k")) {
179         return "_64k";
180     }
181     return "";
182 }
183 
184 }  // namespace
185 
GetModuleLoadList(BootMode boot_mode,const std::string & dir_path)186 std::string GetModuleLoadList(BootMode boot_mode, const std::string& dir_path) {
187     std::string module_load_file;
188 
189     switch (boot_mode) {
190         case BootMode::NORMAL_MODE:
191             module_load_file = "modules.load";
192             break;
193         case BootMode::RECOVERY_MODE:
194             module_load_file = "modules.load.recovery";
195             break;
196         case BootMode::CHARGER_MODE:
197             module_load_file = "modules.load.charger";
198             break;
199     }
200 
201     if (module_load_file != "modules.load") {
202         struct stat fileStat {};
203         std::string load_path = dir_path + "/" + module_load_file;
204         // Fall back to modules.load if the other files aren't accessible
205         if (stat(load_path.c_str(), &fileStat)) {
206             module_load_file = "modules.load";
207         }
208     }
209 
210     return module_load_file;
211 }
212 
213 #define MODULE_BASE_DIR "/lib/modules"
LoadKernelModules(BootMode boot_mode,bool want_console,bool want_parallel,int & modules_loaded)214 bool LoadKernelModules(BootMode boot_mode, bool want_console, bool want_parallel,
215                        int& modules_loaded) {
216     struct utsname uts {};
217     if (uname(&uts)) {
218         LOG(FATAL) << "Failed to get kernel version.";
219     }
220     int major = 0, minor = 0;
221     if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
222         LOG(FATAL) << "Failed to parse kernel version " << uts.release;
223     }
224 
225     std::unique_ptr<DIR, decltype(&closedir)> base_dir(opendir(MODULE_BASE_DIR), closedir);
226     if (!base_dir) {
227         LOG(INFO) << "Unable to open /lib/modules, skipping module loading.";
228         return true;
229     }
230     dirent* entry = nullptr;
231     std::vector<std::string> module_dirs;
232     const auto page_size_suffix = GetPageSizeSuffix();
233     const std::string release_specific_module_dir = uts.release + page_size_suffix;
234     while ((entry = readdir(base_dir.get()))) {
235         if (entry->d_type != DT_DIR) {
236             continue;
237         }
238         if (entry->d_name == release_specific_module_dir) {
239             LOG(INFO) << "Release specific kernel module dir " << release_specific_module_dir
240                       << " found, loading modules from here with no fallbacks.";
241             module_dirs.clear();
242             module_dirs.emplace_back(entry->d_name);
243             break;
244         }
245         // Is a directory does not have page size suffix, it does not mean this directory is for 4K
246         // kernels. Certain 16K kernel builds put all modules in /lib/modules/`uname -r` without any
247         // suffix. Therefore, only ignore a directory if it has _16k/_64k suffix and the suffix does
248         // not match system page size.
249         const auto dir_page_size_suffix = GetPageSizeSuffix(entry->d_name);
250         if (!dir_page_size_suffix.empty() && dir_page_size_suffix != page_size_suffix) {
251             continue;
252         }
253         int dir_major = 0, dir_minor = 0;
254         if (sscanf(entry->d_name, "%d.%d", &dir_major, &dir_minor) != 2 || dir_major != major ||
255             dir_minor != minor) {
256             continue;
257         }
258         module_dirs.emplace_back(entry->d_name);
259     }
260 
261     // Sort the directories so they are iterated over during module loading
262     // in a consistent order. Alphabetical sorting is fine here because the
263     // kernel version at the beginning of the directory name must match the
264     // current kernel version, so the sort only applies to a label that
265     // follows the kernel version, for example /lib/modules/5.4 vs.
266     // /lib/modules/5.4-gki.
267     std::sort(module_dirs.begin(), module_dirs.end());
268 
269     for (const auto& module_dir : module_dirs) {
270         std::string dir_path = MODULE_BASE_DIR "/";
271         dir_path.append(module_dir);
272         Modprobe m({dir_path}, GetModuleLoadList(boot_mode, dir_path));
273         bool retval = m.LoadListedModules(!want_console);
274         modules_loaded = m.GetModuleCount();
275         if (modules_loaded > 0) {
276             LOG(INFO) << "Loaded " << modules_loaded << " modules from " << dir_path;
277             return retval;
278         }
279     }
280 
281     Modprobe m({MODULE_BASE_DIR}, GetModuleLoadList(boot_mode, MODULE_BASE_DIR));
282     bool retval = (want_parallel) ? m.LoadModulesParallel(std::thread::hardware_concurrency())
283                                   : m.LoadListedModules(!want_console);
284     modules_loaded = m.GetModuleCount();
285     if (modules_loaded > 0) {
286         LOG(INFO) << "Loaded " << modules_loaded << " modules from " << MODULE_BASE_DIR;
287         return retval;
288     }
289     return true;
290 }
291 
IsChargerMode(const std::string & cmdline,const std::string & bootconfig)292 static bool IsChargerMode(const std::string& cmdline, const std::string& bootconfig) {
293     return bootconfig.find("androidboot.mode = \"charger\"") != std::string::npos ||
294             cmdline.find("androidboot.mode=charger") != std::string::npos;
295 }
296 
GetBootMode(const std::string & cmdline,const std::string & bootconfig)297 static BootMode GetBootMode(const std::string& cmdline, const std::string& bootconfig)
298 {
299     if (IsChargerMode(cmdline, bootconfig))
300         return BootMode::CHARGER_MODE;
301     else if (IsRecoveryMode() && !ForceNormalBoot(cmdline, bootconfig))
302         return BootMode::RECOVERY_MODE;
303 
304     return BootMode::NORMAL_MODE;
305 }
306 
MaybeResumeFromHibernation(const std::string & bootconfig)307 static void MaybeResumeFromHibernation(const std::string& bootconfig) {
308     std::string hibernationResumeDevice;
309     android::fs_mgr::GetBootconfigFromString(bootconfig, "androidboot.hibernation_resume_device",
310                                              &hibernationResumeDevice);
311     if (!hibernationResumeDevice.empty()) {
312         android::base::unique_fd fd(open("/sys/power/resume", O_RDWR | O_CLOEXEC));
313         if (fd >= 0) {
314             if (!android::base::WriteStringToFd(hibernationResumeDevice, fd)) {
315                 PLOG(ERROR) << "Failed to write to /sys/power/resume";
316             }
317         } else {
318             PLOG(ERROR) << "Failed to open /sys/power/resume";
319         }
320     }
321 }
322 
CreateFirstStageMount(const std::string & cmdline)323 static std::unique_ptr<FirstStageMount> CreateFirstStageMount(const std::string& cmdline) {
324     auto ret = FirstStageMount::Create(cmdline);
325     if (ret.ok()) {
326         return std::move(*ret);
327     } else {
328         LOG(ERROR) << "Failed to create FirstStageMount : " << ret.error();
329         return nullptr;
330     }
331 }
332 
FirstStageMain(int argc,char ** argv)333 int FirstStageMain(int argc, char** argv) {
334     if (REBOOT_BOOTLOADER_ON_PANIC) {
335         InstallRebootSignalHandlers();
336     }
337 
338     boot_clock::time_point start_time = boot_clock::now();
339 
340     std::vector<std::pair<std::string, int>> errors;
341 #define CHECKCALL(x) \
342     if ((x) != 0) errors.emplace_back(#x " failed", errno);
343 
344     // Clear the umask.
345     umask(0);
346 
347     CHECKCALL(clearenv());
348     CHECKCALL(setenv("PATH", _PATH_DEFPATH, 1));
349     // Get the basic filesystem setup we need put together in the initramdisk
350     // on / and then we'll let the rc file figure out the rest.
351     CHECKCALL(mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755"));
352     CHECKCALL(mkdir("/dev/pts", 0755));
353     CHECKCALL(mkdir("/dev/socket", 0755));
354     CHECKCALL(mkdir("/dev/dm-user", 0755));
355     CHECKCALL(mount("devpts", "/dev/pts", "devpts", 0, NULL));
356 #define MAKE_STR(x) __STRING(x)
357     CHECKCALL(mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC)));
358 #undef MAKE_STR
359     // Don't expose the raw commandline to unprivileged processes.
360     CHECKCALL(chmod("/proc/cmdline", 0440));
361     std::string cmdline;
362     android::base::ReadFileToString("/proc/cmdline", &cmdline);
363     // Don't expose the raw bootconfig to unprivileged processes.
364     chmod("/proc/bootconfig", 0440);
365     std::string bootconfig;
366     android::base::ReadFileToString("/proc/bootconfig", &bootconfig);
367     gid_t groups[] = {AID_READPROC};
368     CHECKCALL(setgroups(arraysize(groups), groups));
369     CHECKCALL(mount("sysfs", "/sys", "sysfs", 0, NULL));
370     CHECKCALL(mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL));
371 
372     CHECKCALL(mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11)));
373 
374     if constexpr (WORLD_WRITABLE_KMSG) {
375         CHECKCALL(mknod("/dev/kmsg_debug", S_IFCHR | 0622, makedev(1, 11)));
376     }
377 
378     CHECKCALL(mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8)));
379     CHECKCALL(mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9)));
380 
381     // This is needed for log wrapper, which gets called before ueventd runs.
382     CHECKCALL(mknod("/dev/ptmx", S_IFCHR | 0666, makedev(5, 2)));
383     CHECKCALL(mknod("/dev/null", S_IFCHR | 0666, makedev(1, 3)));
384 
385     // These below mounts are done in first stage init so that first stage mount can mount
386     // subdirectories of /mnt/{vendor,product}/.  Other mounts, not required by first stage mount,
387     // should be done in rc files.
388     // Mount staging areas for devices managed by vold
389     // See storage config details at http://source.android.com/devices/storage/
390     CHECKCALL(mount("tmpfs", "/mnt", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
391                     "mode=0755,uid=0,gid=1000"));
392     // /mnt/vendor is used to mount vendor-specific partitions that can not be
393     // part of the vendor partition, e.g. because they are mounted read-write.
394     CHECKCALL(mkdir("/mnt/vendor", 0755));
395     // /mnt/product is used to mount product-specific partitions that can not be
396     // part of the product partition, e.g. because they are mounted read-write.
397     CHECKCALL(mkdir("/mnt/product", 0755));
398 
399     // /debug_ramdisk is used to preserve additional files from the debug ramdisk
400     CHECKCALL(mount("tmpfs", "/debug_ramdisk", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
401                     "mode=0755,uid=0,gid=0"));
402 
403     // /second_stage_resources is used to preserve files from first to second
404     // stage init
405     CHECKCALL(mount("tmpfs", kSecondStageRes, "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
406                     "mode=0755,uid=0,gid=0"));
407 
408     if (IsMicrodroid() && android::virtualization::IsOpenDiceChangesFlagEnabled()) {
409         CHECKCALL(mount("tmpfs", "/microdroid_resources", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
410                         "mode=0750,uid=0,gid=0"));
411     }
412 #undef CHECKCALL
413 
414     SetStdioToDevNull(argv);
415     // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually
416     // talk to the outside world...
417     InitKernelLogging(argv);
418 
419     if (!errors.empty()) {
420         for (const auto& [error_string, error_errno] : errors) {
421             LOG(ERROR) << error_string << " " << strerror(error_errno);
422         }
423         LOG(FATAL) << "Init encountered errors starting first stage, aborting";
424     }
425 
426     LOG(INFO) << "init first stage started!";
427 
428     auto old_root_dir = std::unique_ptr<DIR, decltype(&closedir)>{opendir("/"), closedir};
429     if (!old_root_dir) {
430         PLOG(ERROR) << "Could not opendir(\"/\"), not freeing ramdisk";
431     }
432 
433     struct stat old_root_info {};
434     if (stat("/", &old_root_info) != 0) {
435         PLOG(ERROR) << "Could not stat(\"/\"), not freeing ramdisk";
436         old_root_dir.reset();
437     }
438 
439     auto want_console = ALLOW_FIRST_STAGE_CONSOLE ? FirstStageConsole(cmdline, bootconfig) : 0;
440     auto want_parallel =
441             bootconfig.find("androidboot.load_modules_parallel = \"true\"") != std::string::npos;
442 
443     boot_clock::time_point module_start_time = boot_clock::now();
444     int module_count = 0;
445     BootMode boot_mode = GetBootMode(cmdline, bootconfig);
446     if (!LoadKernelModules(boot_mode, want_console,
447                            want_parallel, module_count)) {
448         if (want_console != FirstStageConsoleParam::DISABLED) {
449             LOG(ERROR) << "Failed to load kernel modules, starting console";
450         } else {
451             LOG(FATAL) << "Failed to load kernel modules";
452         }
453     }
454     if (module_count > 0) {
455         auto module_elapse_time = std::chrono::duration_cast<std::chrono::milliseconds>(
456                 boot_clock::now() - module_start_time);
457         setenv(kEnvInitModuleDurationMs, std::to_string(module_elapse_time.count()).c_str(), 1);
458         LOG(INFO) << "Loaded " << module_count << " kernel modules took "
459                   << module_elapse_time.count() << " ms";
460     }
461 
462     MaybeResumeFromHibernation(bootconfig);
463 
464     std::unique_ptr<FirstStageMount> fsm;
465 
466     bool created_devices = false;
467     if (want_console == FirstStageConsoleParam::CONSOLE_ON_FAILURE) {
468         if (!IsRecoveryMode()) {
469             fsm = CreateFirstStageMount(cmdline);
470             if (fsm) {
471                 created_devices = fsm->DoCreateDevices();
472                 if (!created_devices) {
473                     LOG(ERROR) << "Failed to create device nodes early";
474                 }
475             }
476         }
477         StartConsole(cmdline);
478     }
479 
480     if (access(kBootImageRamdiskProp, F_OK) == 0) {
481         std::string dest = GetRamdiskPropForSecondStage();
482         std::string dir = android::base::Dirname(dest);
483         std::error_code ec;
484         if (!fs::create_directories(dir, ec) && !!ec) {
485             LOG(FATAL) << "Can't mkdir " << dir << ": " << ec.message();
486         }
487         if (!fs::copy_file(kBootImageRamdiskProp, dest, ec)) {
488             LOG(FATAL) << "Can't copy " << kBootImageRamdiskProp << " to " << dest << ": "
489                        << ec.message();
490         }
491         LOG(INFO) << "Copied ramdisk prop to " << dest;
492     }
493 
494     // If "/force_debuggable" is present, the second-stage init will use a userdebug
495     // sepolicy and load adb_debug.prop to allow adb root, if the device is unlocked.
496     if (access("/force_debuggable", F_OK) == 0) {
497         constexpr const char adb_debug_prop_src[] = "/adb_debug.prop";
498         constexpr const char userdebug_plat_sepolicy_cil_src[] = "/userdebug_plat_sepolicy.cil";
499         std::error_code ec;  // to invoke the overloaded copy_file() that won't throw.
500         if (access(adb_debug_prop_src, F_OK) == 0 &&
501             !fs::copy_file(adb_debug_prop_src, kDebugRamdiskProp, ec)) {
502             LOG(WARNING) << "Can't copy " << adb_debug_prop_src << " to " << kDebugRamdiskProp
503                          << ": " << ec.message();
504         }
505         if (access(userdebug_plat_sepolicy_cil_src, F_OK) == 0 &&
506             !fs::copy_file(userdebug_plat_sepolicy_cil_src, kDebugRamdiskSEPolicy, ec)) {
507             LOG(WARNING) << "Can't copy " << userdebug_plat_sepolicy_cil_src << " to "
508                          << kDebugRamdiskSEPolicy << ": " << ec.message();
509         }
510         // setenv for second-stage init to read above kDebugRamdisk* files.
511         setenv("INIT_FORCE_DEBUGGABLE", "true", 1);
512     }
513 
514     if (ForceNormalBoot(cmdline, bootconfig)) {
515         mkdir("/first_stage_ramdisk", 0755);
516         PrepareSwitchRoot();
517         // SwitchRoot() must be called with a mount point as the target, so we bind mount the
518         // target directory to itself here.
519         if (mount("/first_stage_ramdisk", "/first_stage_ramdisk", nullptr, MS_BIND, nullptr) != 0) {
520             PLOG(FATAL) << "Could not bind mount /first_stage_ramdisk to itself";
521         }
522         SwitchRoot("/first_stage_ramdisk");
523     }
524 
525     if (IsRecoveryMode()) {
526         LOG(INFO) << "First stage mount skipped (recovery mode)";
527     } else {
528         if (!fsm) {
529             fsm = CreateFirstStageMount(cmdline);
530         }
531         if (!fsm) {
532             LOG(FATAL) << "FirstStageMount not available";
533         }
534 
535         if (!created_devices && !fsm->DoCreateDevices()) {
536             LOG(FATAL) << "Failed to create devices required for first stage mount";
537         }
538 
539         if (!fsm->DoFirstStageMount()) {
540             LOG(FATAL) << "Failed to mount required partitions early ...";
541         }
542     }
543 
544     struct stat new_root_info {};
545     if (stat("/", &new_root_info) != 0) {
546         PLOG(ERROR) << "Could not stat(\"/\"), not freeing ramdisk";
547         old_root_dir.reset();
548     }
549 
550     if (old_root_dir && old_root_info.st_dev != new_root_info.st_dev) {
551         FreeRamdisk(old_root_dir.get(), old_root_info.st_dev);
552     }
553 
554     SetInitAvbVersionInRecovery();
555 
556     setenv(kEnvFirstStageStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(),
557            1);
558 
559     const char* path = "/system/bin/init";
560     const char* args[] = {path, "selinux_setup", nullptr};
561     auto fd = open("/dev/kmsg", O_WRONLY | O_CLOEXEC);
562     dup2(fd, STDOUT_FILENO);
563     dup2(fd, STDERR_FILENO);
564     close(fd);
565     execv(path, const_cast<char**>(args));
566 
567     // execv() only returns if an error happened, in which case we
568     // panic and never fall through this conditional.
569     PLOG(FATAL) << "execv(\"" << path << "\") failed";
570 
571     return 1;
572 }
573 
574 }  // namespace init
575 }  // namespace android
576