init.cpp revision 41d0b6d3ca4e56f0cc0ae5c19e563f80c8f494d0
1/* 2 * Copyright (C) 2008 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 <ctype.h> 18#include <dirent.h> 19#include <errno.h> 20#include <fcntl.h> 21#include <inttypes.h> 22#include <libgen.h> 23#include <paths.h> 24#include <signal.h> 25#include <stdarg.h> 26#include <stdio.h> 27#include <stdlib.h> 28#include <string.h> 29#include <sys/epoll.h> 30#include <sys/mount.h> 31#include <sys/socket.h> 32#include <sys/stat.h> 33#include <sys/sysmacros.h> 34#include <sys/types.h> 35#include <sys/un.h> 36#include <sys/wait.h> 37#include <unistd.h> 38 39#include <selinux/selinux.h> 40#include <selinux/label.h> 41#include <selinux/android.h> 42 43#include <android-base/file.h> 44#include <android-base/stringprintf.h> 45#include <android-base/strings.h> 46#include <cutils/fs.h> 47#include <cutils/iosched_policy.h> 48#include <cutils/list.h> 49#include <cutils/sockets.h> 50#include <private/android_filesystem_config.h> 51 52#include <fstream> 53#include <memory> 54 55#include "action.h" 56#include "bootchart.h" 57#include "devices.h" 58#include "fs_mgr.h" 59#include "import_parser.h" 60#include "init.h" 61#include "init_parser.h" 62#include "keychords.h" 63#include "log.h" 64#include "property_service.h" 65#include "service.h" 66#include "signal_handler.h" 67#include "ueventd.h" 68#include "util.h" 69#include "watchdogd.h" 70 71using android::base::StringPrintf; 72 73struct selabel_handle *sehandle; 74struct selabel_handle *sehandle_prop; 75 76static int property_triggers_enabled = 0; 77 78static char qemu[32]; 79 80std::string default_console = "/dev/console"; 81static time_t process_needs_restart_at; 82 83const char *ENV[32]; 84 85bool waiting_for_exec = false; 86 87static int epoll_fd = -1; 88 89void register_epoll_handler(int fd, void (*fn)()) { 90 epoll_event ev; 91 ev.events = EPOLLIN; 92 ev.data.ptr = reinterpret_cast<void*>(fn); 93 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) { 94 PLOG(ERROR) << "epoll_ctl failed"; 95 } 96} 97 98/* add_environment - add "key=value" to the current environment */ 99int add_environment(const char *key, const char *val) 100{ 101 size_t n; 102 size_t key_len = strlen(key); 103 104 /* The last environment entry is reserved to terminate the list */ 105 for (n = 0; n < (arraysize(ENV) - 1); n++) { 106 107 /* Delete any existing entry for this key */ 108 if (ENV[n] != NULL) { 109 size_t entry_key_len = strcspn(ENV[n], "="); 110 if ((entry_key_len == key_len) && (strncmp(ENV[n], key, entry_key_len) == 0)) { 111 free((char*)ENV[n]); 112 ENV[n] = NULL; 113 } 114 } 115 116 /* Add entry if a free slot is available */ 117 if (ENV[n] == NULL) { 118 char* entry; 119 asprintf(&entry, "%s=%s", key, val); 120 ENV[n] = entry; 121 return 0; 122 } 123 } 124 125 LOG(ERROR) << "No env. room to store: '" << key << "':'" << val << "'"; 126 127 return -1; 128} 129 130void property_changed(const char *name, const char *value) 131{ 132 if (property_triggers_enabled) 133 ActionManager::GetInstance().QueuePropertyTrigger(name, value); 134} 135 136static void restart_processes() 137{ 138 process_needs_restart_at = 0; 139 ServiceManager::GetInstance().ForEachServiceWithFlags(SVC_RESTARTING, [](Service* s) { 140 s->RestartIfNeeded(&process_needs_restart_at); 141 }); 142} 143 144void handle_control_message(const std::string& msg, const std::string& name) { 145 Service* svc = ServiceManager::GetInstance().FindServiceByName(name); 146 if (svc == nullptr) { 147 LOG(ERROR) << "no such service '" << name << "'"; 148 return; 149 } 150 151 if (msg == "start") { 152 svc->Start(); 153 } else if (msg == "stop") { 154 svc->Stop(); 155 } else if (msg == "restart") { 156 svc->Restart(); 157 } else { 158 LOG(ERROR) << "unknown control msg '" << msg << "'"; 159 } 160} 161 162static int wait_for_coldboot_done_action(const std::vector<std::string>& args) { 163 Timer t; 164 165 LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE "..."; 166 167 // Historically we had a 1s timeout here because we weren't otherwise 168 // tracking boot time, and many OEMs made their sepolicy regular 169 // expressions too expensive (http://b/19899875). 170 171 // Now we're tracking boot time, just log the time taken to a system 172 // property. We still panic if it takes more than a minute though, 173 // because any build that slow isn't likely to boot at all, and we'd 174 // rather any test lab devices fail back to the bootloader. 175 if (wait_for_file(COLDBOOT_DONE, 60s) < 0) { 176 LOG(ERROR) << "Timed out waiting for " COLDBOOT_DONE; 177 panic(); 178 } 179 180 property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration_ns()).c_str()); 181 return 0; 182} 183 184/* 185 * Writes 512 bytes of output from Hardware RNG (/dev/hw_random, backed 186 * by Linux kernel's hw_random framework) into Linux RNG's via /dev/urandom. 187 * Does nothing if Hardware RNG is not present. 188 * 189 * Since we don't yet trust the quality of Hardware RNG, these bytes are not 190 * mixed into the primary pool of Linux RNG and the entropy estimate is left 191 * unmodified. 192 * 193 * If the HW RNG device /dev/hw_random is present, we require that at least 194 * 512 bytes read from it are written into Linux RNG. QA is expected to catch 195 * devices/configurations where these I/O operations are blocking for a long 196 * time. We do not reboot or halt on failures, as this is a best-effort 197 * attempt. 198 */ 199static int mix_hwrng_into_linux_rng_action(const std::vector<std::string>& args) 200{ 201 int result = -1; 202 int hwrandom_fd = -1; 203 int urandom_fd = -1; 204 char buf[512]; 205 ssize_t chunk_size; 206 size_t total_bytes_written = 0; 207 208 hwrandom_fd = TEMP_FAILURE_RETRY( 209 open("/dev/hw_random", O_RDONLY | O_NOFOLLOW | O_CLOEXEC)); 210 if (hwrandom_fd == -1) { 211 if (errno == ENOENT) { 212 LOG(ERROR) << "/dev/hw_random not found"; 213 // It's not an error to not have a Hardware RNG. 214 result = 0; 215 } else { 216 PLOG(ERROR) << "Failed to open /dev/hw_random"; 217 } 218 goto ret; 219 } 220 221 urandom_fd = TEMP_FAILURE_RETRY( 222 open("/dev/urandom", O_WRONLY | O_NOFOLLOW | O_CLOEXEC)); 223 if (urandom_fd == -1) { 224 PLOG(ERROR) << "Failed to open /dev/urandom"; 225 goto ret; 226 } 227 228 while (total_bytes_written < sizeof(buf)) { 229 chunk_size = TEMP_FAILURE_RETRY( 230 read(hwrandom_fd, buf, sizeof(buf) - total_bytes_written)); 231 if (chunk_size == -1) { 232 PLOG(ERROR) << "Failed to read from /dev/hw_random"; 233 goto ret; 234 } else if (chunk_size == 0) { 235 LOG(ERROR) << "Failed to read from /dev/hw_random: EOF"; 236 goto ret; 237 } 238 239 chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size)); 240 if (chunk_size == -1) { 241 PLOG(ERROR) << "Failed to write to /dev/urandom"; 242 goto ret; 243 } 244 total_bytes_written += chunk_size; 245 } 246 247 LOG(INFO) << "Mixed " << total_bytes_written << " bytes from /dev/hw_random into /dev/urandom"; 248 result = 0; 249 250ret: 251 if (hwrandom_fd != -1) { 252 close(hwrandom_fd); 253 } 254 if (urandom_fd != -1) { 255 close(urandom_fd); 256 } 257 return result; 258} 259 260static void security_failure() { 261 LOG(ERROR) << "Security failure..."; 262 panic(); 263} 264 265#define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits" 266#define MMAP_RND_COMPAT_PATH "/proc/sys/vm/mmap_rnd_compat_bits" 267 268/* __attribute__((unused)) due to lack of mips support: see mips block 269 * in set_mmap_rnd_bits_action */ 270static bool __attribute__((unused)) set_mmap_rnd_bits_min(int start, int min, bool compat) { 271 std::string path; 272 if (compat) { 273 path = MMAP_RND_COMPAT_PATH; 274 } else { 275 path = MMAP_RND_PATH; 276 } 277 std::ifstream inf(path, std::fstream::in); 278 if (!inf) { 279 LOG(ERROR) << "Cannot open for reading: " << path; 280 return false; 281 } 282 while (start >= min) { 283 // try to write out new value 284 std::string str_val = std::to_string(start); 285 std::ofstream of(path, std::fstream::out); 286 if (!of) { 287 LOG(ERROR) << "Cannot open for writing: " << path; 288 return false; 289 } 290 of << str_val << std::endl; 291 of.close(); 292 293 // check to make sure it was recorded 294 inf.seekg(0); 295 std::string str_rec; 296 inf >> str_rec; 297 if (str_val.compare(str_rec) == 0) { 298 break; 299 } 300 start--; 301 } 302 inf.close(); 303 if (start < min) { 304 LOG(ERROR) << "Unable to set minimum required entropy " << min << " in " << path; 305 return false; 306 } 307 return true; 308} 309 310/* 311 * Set /proc/sys/vm/mmap_rnd_bits and potentially 312 * /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values. 313 * Returns -1 if unable to set these to an acceptable value. 314 * 315 * To support this sysctl, the following upstream commits are needed: 316 * 317 * d07e22597d1d mm: mmap: add new /proc tunable for mmap_base ASLR 318 * e0c25d958f78 arm: mm: support ARCH_MMAP_RND_BITS 319 * 8f0d3aa9de57 arm64: mm: support ARCH_MMAP_RND_BITS 320 * 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS 321 * ec9ee4acd97c drivers: char: random: add get_random_long() 322 * 5ef11c35ce86 mm: ASLR: use get_random_long() 323 */ 324static int set_mmap_rnd_bits_action(const std::vector<std::string>& args) 325{ 326 int ret = -1; 327 328 /* values are arch-dependent */ 329#if defined(__aarch64__) 330 /* arm64 supports 18 - 33 bits depending on pagesize and VA_SIZE */ 331 if (set_mmap_rnd_bits_min(33, 24, false) 332 && set_mmap_rnd_bits_min(16, 16, true)) { 333 ret = 0; 334 } 335#elif defined(__x86_64__) 336 /* x86_64 supports 28 - 32 bits */ 337 if (set_mmap_rnd_bits_min(32, 32, false) 338 && set_mmap_rnd_bits_min(16, 16, true)) { 339 ret = 0; 340 } 341#elif defined(__arm__) || defined(__i386__) 342 /* check to see if we're running on 64-bit kernel */ 343 bool h64 = !access(MMAP_RND_COMPAT_PATH, F_OK); 344 /* supported 32-bit architecture must have 16 bits set */ 345 if (set_mmap_rnd_bits_min(16, 16, h64)) { 346 ret = 0; 347 } 348#elif defined(__mips__) || defined(__mips64__) 349 // TODO: add mips support b/27788820 350 ret = 0; 351#else 352 LOG(ERROR) << "Unknown architecture"; 353#endif 354 355#ifdef __BRILLO__ 356 // TODO: b/27794137 357 ret = 0; 358#endif 359 if (ret == -1) { 360 LOG(ERROR) << "Unable to set adequate mmap entropy value!"; 361 security_failure(); 362 } 363 return ret; 364} 365 366static int keychord_init_action(const std::vector<std::string>& args) 367{ 368 keychord_init(); 369 return 0; 370} 371 372static int console_init_action(const std::vector<std::string>& args) 373{ 374 std::string console = property_get("ro.boot.console"); 375 if (!console.empty()) { 376 default_console = "/dev/" + console; 377 } 378 return 0; 379} 380 381static void import_kernel_nv(const std::string& key, const std::string& value, bool for_emulator) { 382 if (key.empty()) return; 383 384 if (for_emulator) { 385 // In the emulator, export any kernel option with the "ro.kernel." prefix. 386 property_set(StringPrintf("ro.kernel.%s", key.c_str()).c_str(), value.c_str()); 387 return; 388 } 389 390 if (key == "qemu") { 391 strlcpy(qemu, value.c_str(), sizeof(qemu)); 392 } else if (android::base::StartsWith(key, "androidboot.")) { 393 property_set(StringPrintf("ro.boot.%s", key.c_str() + 12).c_str(), value.c_str()); 394 } 395} 396 397static void export_oem_lock_status() { 398 if (property_get("ro.oem_unlock_supported") != "1") { 399 return; 400 } 401 402 std::string value = property_get("ro.boot.verifiedbootstate"); 403 404 if (!value.empty()) { 405 property_set("ro.boot.flash.locked", value == "orange" ? "0" : "1"); 406 } 407} 408 409static void export_kernel_boot_props() { 410 struct { 411 const char *src_prop; 412 const char *dst_prop; 413 const char *default_value; 414 } prop_map[] = { 415 { "ro.boot.serialno", "ro.serialno", "", }, 416 { "ro.boot.mode", "ro.bootmode", "unknown", }, 417 { "ro.boot.baseband", "ro.baseband", "unknown", }, 418 { "ro.boot.bootloader", "ro.bootloader", "unknown", }, 419 { "ro.boot.hardware", "ro.hardware", "unknown", }, 420 { "ro.boot.revision", "ro.revision", "0", }, 421 }; 422 for (size_t i = 0; i < arraysize(prop_map); i++) { 423 std::string value = property_get(prop_map[i].src_prop); 424 property_set(prop_map[i].dst_prop, (!value.empty()) ? value.c_str() : prop_map[i].default_value); 425 } 426} 427 428static void process_kernel_dt() { 429 static const char android_dir[] = "/proc/device-tree/firmware/android"; 430 431 std::string file_name = StringPrintf("%s/compatible", android_dir); 432 433 std::string dt_file; 434 android::base::ReadFileToString(file_name, &dt_file); 435 if (!dt_file.compare("android,firmware")) { 436 LOG(ERROR) << "firmware/android is not compatible with 'android,firmware'"; 437 return; 438 } 439 440 std::unique_ptr<DIR, int(*)(DIR*)>dir(opendir(android_dir), closedir); 441 if (!dir) return; 442 443 struct dirent *dp; 444 while ((dp = readdir(dir.get())) != NULL) { 445 if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") || !strcmp(dp->d_name, "name")) { 446 continue; 447 } 448 449 file_name = StringPrintf("%s/%s", android_dir, dp->d_name); 450 451 android::base::ReadFileToString(file_name, &dt_file); 452 std::replace(dt_file.begin(), dt_file.end(), ',', '.'); 453 454 std::string property_name = StringPrintf("ro.boot.%s", dp->d_name); 455 property_set(property_name.c_str(), dt_file.c_str()); 456 } 457} 458 459static void process_kernel_cmdline() { 460 // The first pass does the common stuff, and finds if we are in qemu. 461 // The second pass is only necessary for qemu to export all kernel params 462 // as properties. 463 import_kernel_cmdline(false, import_kernel_nv); 464 if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv); 465} 466 467static int property_enable_triggers_action(const std::vector<std::string>& args) 468{ 469 /* Enable property triggers. */ 470 property_triggers_enabled = 1; 471 return 0; 472} 473 474static int queue_property_triggers_action(const std::vector<std::string>& args) 475{ 476 ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger"); 477 ActionManager::GetInstance().QueueAllPropertyTriggers(); 478 return 0; 479} 480 481static void selinux_init_all_handles(void) 482{ 483 sehandle = selinux_android_file_context_handle(); 484 selinux_android_set_sehandle(sehandle); 485 sehandle_prop = selinux_android_prop_context_handle(); 486} 487 488enum selinux_enforcing_status { SELINUX_PERMISSIVE, SELINUX_ENFORCING }; 489 490static selinux_enforcing_status selinux_status_from_cmdline() { 491 selinux_enforcing_status status = SELINUX_ENFORCING; 492 493 import_kernel_cmdline(false, [&](const std::string& key, const std::string& value, bool in_qemu) { 494 if (key == "androidboot.selinux" && value == "permissive") { 495 status = SELINUX_PERMISSIVE; 496 } 497 }); 498 499 return status; 500} 501 502static bool selinux_is_enforcing(void) 503{ 504 if (ALLOW_PERMISSIVE_SELINUX) { 505 return selinux_status_from_cmdline() == SELINUX_ENFORCING; 506 } 507 return true; 508} 509 510static int audit_callback(void *data, security_class_t /*cls*/, char *buf, size_t len) { 511 512 property_audit_data *d = reinterpret_cast<property_audit_data*>(data); 513 514 if (!d || !d->name || !d->cr) { 515 LOG(ERROR) << "audit_callback invoked with null data arguments!"; 516 return 0; 517 } 518 519 snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name, 520 d->cr->pid, d->cr->uid, d->cr->gid); 521 return 0; 522} 523 524static void selinux_initialize(bool in_kernel_domain) { 525 Timer t; 526 527 selinux_callback cb; 528 cb.func_log = selinux_klog_callback; 529 selinux_set_callback(SELINUX_CB_LOG, cb); 530 cb.func_audit = audit_callback; 531 selinux_set_callback(SELINUX_CB_AUDIT, cb); 532 533 if (in_kernel_domain) { 534 LOG(INFO) << "Loading SELinux policy..."; 535 if (selinux_android_load_policy() < 0) { 536 PLOG(ERROR) << "failed to load policy"; 537 security_failure(); 538 } 539 540 bool kernel_enforcing = (security_getenforce() == 1); 541 bool is_enforcing = selinux_is_enforcing(); 542 if (kernel_enforcing != is_enforcing) { 543 if (security_setenforce(is_enforcing)) { 544 PLOG(ERROR) << "security_setenforce(%s) failed" << (is_enforcing ? "true" : "false"); 545 security_failure(); 546 } 547 } 548 549 if (write_file("/sys/fs/selinux/checkreqprot", "0") == -1) { 550 security_failure(); 551 } 552 553 // init's first stage can't set properties, so pass the time to the second stage. 554 setenv("INIT_SELINUX_TOOK", std::to_string(t.duration_ns()).c_str(), 1); 555 } else { 556 selinux_init_all_handles(); 557 } 558} 559 560// Set the UDC controller for the ConfigFS USB Gadgets. 561// Read the UDC controller in use from "/sys/class/udc". 562// In case of multiple UDC controllers select the first one. 563static void set_usb_controller() { 564 std::unique_ptr<DIR, decltype(&closedir)>dir(opendir("/sys/class/udc"), closedir); 565 if (!dir) return; 566 567 dirent* dp; 568 while ((dp = readdir(dir.get())) != nullptr) { 569 if (dp->d_name[0] == '.') continue; 570 571 property_set("sys.usb.controller", dp->d_name); 572 break; 573 } 574} 575 576/* Returns a new path consisting of base_path and the file name in reference_path. */ 577static std::string get_path(const std::string& base_path, const std::string& reference_path) { 578 std::string::size_type pos = reference_path.rfind('/'); 579 if (pos == std::string::npos) { 580 return base_path + '/' + reference_path; 581 } else { 582 return base_path + reference_path.substr(pos); 583 } 584} 585 586/* Imports the fstab info from cmdline. */ 587static std::string import_cmdline_fstab() { 588 std::string prefix, fstab, fstab_full; 589 590 import_kernel_cmdline(false, 591 [&](const std::string& key, const std::string& value, bool in_qemu __attribute__((__unused__))) { 592 if (key == "android.early.prefix") { 593 prefix = value; 594 } else if (key == "android.early.fstab") { 595 fstab = value; 596 } 597 }); 598 if (!fstab.empty()) { 599 // Convert "mmcblk0p09+/odm+ext4+ro+verify" to "mmcblk0p09 /odm ext4 ro verify" 600 std::replace(fstab.begin(), fstab.end(), '+', ' '); 601 for (const auto& entry : android::base::Split(fstab, "\n")) { 602 fstab_full += prefix + entry + '\n'; 603 } 604 } 605 return fstab_full; 606} 607 608/* Early mount vendor and ODM partitions. The fstab info is read from kernel cmdline. */ 609static void early_mount() { 610 std::string fstab_string = import_cmdline_fstab(); 611 if (fstab_string.empty()) { 612 LOG(INFO) << "Failed to load vendor fstab from kernel cmdline"; 613 return; 614 } 615 FILE *fstab_file = fmemopen((void *)fstab_string.c_str(), fstab_string.length(), "r"); 616 if (!fstab_file) { 617 PLOG(ERROR) << "Failed to open fstab string as FILE"; 618 return; 619 } 620 std::unique_ptr<struct fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_file(fstab_file), fs_mgr_free_fstab); 621 fclose(fstab_file); 622 if (!fstab) { 623 LOG(ERROR) << "Failed to parse fstab string: " << fstab_string; 624 return; 625 } 626 LOG(INFO) << "Loaded vendor fstab from cmdline"; 627 628 if (early_device_socket_open()) { 629 LOG(ERROR) << "Failed to open device uevent socket"; 630 return; 631 } 632 633 /* Create /dev/device-mapper for dm-verity */ 634 early_create_dev("/sys/devices/virtual/misc/device-mapper", EARLY_CHAR_DEV); 635 636 for (int i = 0; i < fstab->num_entries; ++i) { 637 struct fstab_rec *rec = &fstab->recs[i]; 638 std::string mount_point = rec->mount_point; 639 std::string syspath = rec->blk_device; 640 641 if (mount_point != "/vendor" && mount_point != "/odm") 642 continue; 643 644 /* Create mount target under /dev/block/ from sysfs via uevent */ 645 LOG(INFO) << "Mounting " << mount_point << " from " << syspath << "..."; 646 char *devpath = strdup(get_path("/dev/block", syspath).c_str()); 647 if (!devpath) { 648 PLOG(ERROR) << "Failed to strdup dev path in early mount " << syspath; 649 continue; 650 } 651 rec->blk_device = devpath; 652 early_create_dev(syspath, EARLY_BLOCK_DEV); 653 654 int rc = fs_mgr_early_setup_verity(rec); 655 if (rc == FS_MGR_EARLY_SETUP_VERITY_SUCCESS) { 656 /* Mount target is changed to /dev/block/dm-<n>; initiate its creation from sysfs counterpart */ 657 early_create_dev(get_path("/sys/devices/virtual/block", rec->blk_device), EARLY_BLOCK_DEV); 658 } else if (rc == FS_MGR_EARLY_SETUP_VERITY_FAIL) { 659 LOG(ERROR) << "Failed to set up dm-verity on " << rec->blk_device; 660 continue; 661 } else { /* FS_MGR_EARLY_SETUP_VERITY_NO_VERITY */ 662 LOG(INFO) << "dm-verity disabled on debuggable device; mount directly on " << rec->blk_device; 663 } 664 665 mkdir(mount_point.c_str(), 0755); 666 rc = mount(rec->blk_device, mount_point.c_str(), rec->fs_type, rec->flags, rec->fs_options); 667 if (rc) { 668 PLOG(ERROR) << "Failed to mount on " << rec->blk_device; 669 } 670 } 671 early_device_socket_close(); 672} 673 674int main(int argc, char** argv) { 675 if (!strcmp(basename(argv[0]), "ueventd")) { 676 return ueventd_main(argc, argv); 677 } 678 679 if (!strcmp(basename(argv[0]), "watchdogd")) { 680 return watchdogd_main(argc, argv); 681 } 682 683 boot_clock::time_point start_time = boot_clock::now(); 684 685 // Clear the umask. 686 umask(0); 687 688 add_environment("PATH", _PATH_DEFPATH); 689 690 bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr); 691 692 // Don't expose the raw commandline to unprivileged processes. 693 chmod("/proc/cmdline", 0440); 694 695 // Get the basic filesystem setup we need put together in the initramdisk 696 // on / and then we'll let the rc file figure out the rest. 697 if (is_first_stage) { 698 mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755"); 699 mkdir("/dev/pts", 0755); 700 mkdir("/dev/socket", 0755); 701 mount("devpts", "/dev/pts", "devpts", 0, NULL); 702 #define MAKE_STR(x) __STRING(x) 703 mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC)); 704 gid_t groups[] = { AID_READPROC }; 705 setgroups(arraysize(groups), groups); 706 mount("sysfs", "/sys", "sysfs", 0, NULL); 707 mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL); 708 mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11)); 709 mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8)); 710 mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9)); 711 } 712 713 // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually 714 // talk to the outside world... 715 InitKernelLogging(argv); 716 717 LOG(INFO) << "init " << (is_first_stage ? "first" : "second") << " stage started!"; 718 719 if (is_first_stage) { 720 // Mount devices defined in android.early.* kernel commandline 721 early_mount(); 722 723 // Set up SELinux, loading the SELinux policy. 724 selinux_initialize(true); 725 726 // We're in the kernel domain, so re-exec init to transition to the init domain now 727 // that the SELinux policy has been loaded. 728 if (restorecon("/init") == -1) { 729 PLOG(ERROR) << "restorecon failed"; 730 security_failure(); 731 } 732 733 setenv("INIT_SECOND_STAGE", "true", 1); 734 735 uint64_t start_ns = start_time.time_since_epoch().count(); 736 setenv("INIT_STARTED_AT", StringPrintf("%" PRIu64, start_ns).c_str(), 1); 737 738 char* path = argv[0]; 739 char* args[] = { path, nullptr }; 740 if (execv(path, args) == -1) { 741 PLOG(ERROR) << "execv(\"" << path << "\") failed"; 742 security_failure(); 743 } 744 } else { 745 // Indicate that booting is in progress to background fw loaders, etc. 746 close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000)); 747 748 property_init(); 749 750 // If arguments are passed both on the command line and in DT, 751 // properties set in DT always have priority over the command-line ones. 752 process_kernel_dt(); 753 process_kernel_cmdline(); 754 755 // Propagate the kernel variables to internal variables 756 // used by init as well as the current required properties. 757 export_kernel_boot_props(); 758 759 // Make the time that init started available for bootstat to log. 760 property_set("ro.boottime.init", getenv("INIT_STARTED_AT")); 761 property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK")); 762 763 // Clean up our environment. 764 unsetenv("INIT_SECOND_STAGE"); 765 unsetenv("INIT_STARTED_AT"); 766 unsetenv("INIT_SELINUX_TOOK"); 767 768 // Now set up SELinux for second stage. 769 selinux_initialize(false); 770 } 771 772 // These directories were necessarily created before initial policy load 773 // and therefore need their security context restored to the proper value. 774 // This must happen before /dev is populated by ueventd. 775 LOG(INFO) << "Running restorecon..."; 776 restorecon("/dev"); 777 restorecon("/dev/kmsg"); 778 restorecon("/dev/socket"); 779 restorecon("/dev/random"); 780 restorecon("/dev/urandom"); 781 restorecon("/dev/__properties__"); 782 restorecon("/property_contexts"); 783 restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE); 784 restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE); 785 restorecon("/dev/device-mapper"); 786 787 epoll_fd = epoll_create1(EPOLL_CLOEXEC); 788 if (epoll_fd == -1) { 789 PLOG(ERROR) << "epoll_create1 failed"; 790 exit(1); 791 } 792 793 signal_handler_init(); 794 795 property_load_boot_defaults(); 796 export_oem_lock_status(); 797 start_property_service(); 798 set_usb_controller(); 799 800 const BuiltinFunctionMap function_map; 801 Action::set_function_map(&function_map); 802 803 Parser& parser = Parser::GetInstance(); 804 parser.AddSectionParser("service",std::make_unique<ServiceParser>()); 805 parser.AddSectionParser("on", std::make_unique<ActionParser>()); 806 parser.AddSectionParser("import", std::make_unique<ImportParser>()); 807 parser.ParseConfig("/init.rc"); 808 809 ActionManager& am = ActionManager::GetInstance(); 810 811 am.QueueEventTrigger("early-init"); 812 813 // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev... 814 am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done"); 815 // ... so that we can start queuing up actions that require stuff from /dev. 816 am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng"); 817 am.QueueBuiltinAction(set_mmap_rnd_bits_action, "set_mmap_rnd_bits"); 818 am.QueueBuiltinAction(keychord_init_action, "keychord_init"); 819 am.QueueBuiltinAction(console_init_action, "console_init"); 820 821 // Trigger all the boot actions to get us started. 822 am.QueueEventTrigger("init"); 823 824 // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random 825 // wasn't ready immediately after wait_for_coldboot_done 826 am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng"); 827 828 // Don't mount filesystems or start core system services in charger mode. 829 std::string bootmode = property_get("ro.bootmode"); 830 if (bootmode == "charger") { 831 am.QueueEventTrigger("charger"); 832 } else { 833 am.QueueEventTrigger("late-init"); 834 } 835 836 // Run all property triggers based on current state of the properties. 837 am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers"); 838 839 while (true) { 840 if (!waiting_for_exec) { 841 am.ExecuteOneCommand(); 842 restart_processes(); 843 } 844 845 // By default, sleep until something happens. 846 int epoll_timeout_ms = -1; 847 848 // If there's a process that needs restarting, wake up in time for that. 849 if (process_needs_restart_at != 0) { 850 epoll_timeout_ms = (process_needs_restart_at - time(nullptr)) * 1000; 851 if (epoll_timeout_ms < 0) epoll_timeout_ms = 0; 852 } 853 854 // If there's more work to do, wake up again immediately. 855 if (am.HasMoreCommands()) epoll_timeout_ms = 0; 856 857 bootchart_sample(&epoll_timeout_ms); 858 859 epoll_event ev; 860 int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms)); 861 if (nr == -1) { 862 PLOG(ERROR) << "epoll_wait failed"; 863 } else if (nr == 1) { 864 ((void (*)()) ev.data.ptr)(); 865 } 866 } 867 868 return 0; 869} 870