blob: 9cdbd19837ac9192656d6f71c9a1a69ee33b09e1 [file] [log] [blame]
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001/*
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
Elliott Hughes8d82ea02015-02-06 20:15:18 -080017#include <ctype.h>
Rom Lemarchand6a524432015-02-28 06:39:11 -080018#include <dirent.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080019#include <errno.h>
20#include <fcntl.h>
Elliott Hughes9605a942016-11-10 17:43:47 -080021#include <inttypes.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080022#include <libgen.h>
Elliott Hughescc86fb22015-03-17 20:01:13 -070023#include <paths.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080024#include <signal.h>
25#include <stdarg.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070026#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
Elliott Hughes929f4072015-04-24 21:13:44 -070029#include <sys/epoll.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070030#include <sys/mount.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070031#include <sys/socket.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080032#include <sys/stat.h>
Elliott Hughes35f5d042016-07-26 09:32:33 -070033#include <sys/sysmacros.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080034#include <sys/types.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070035#include <sys/un.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080036#include <sys/wait.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080037#include <unistd.h>
38
Stephen Smalleye46f9d52012-01-13 08:48:47 -050039#include <selinux/selinux.h>
40#include <selinux/label.h>
Stephen Smalleyae6f3d72012-05-01 15:02:53 -040041#include <selinux/android.h>
Stephen Smalleye46f9d52012-01-13 08:48:47 -050042
Elliott Hughes4f713192015-12-04 22:00:26 -080043#include <android-base/file.h>
Tom Cherrye2490972017-03-28 16:40:41 -070044#include <android-base/properties.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080045#include <android-base/stringprintf.h>
46#include <android-base/strings.h>
Alex Klyubin16696e22017-02-28 12:32:20 -080047#include <android-base/unique_fd.h>
bowgotsai76351272017-02-14 22:06:20 +080048#include <libavb/libavb.h>
Colin Crossf83d0b92010-04-21 12:04:20 -070049#include <private/android_filesystem_config.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070050
Elliott Hughes99dae542016-11-10 19:22:18 -080051#include <fstream>
Rom Lemarchand6a524432015-02-28 06:39:11 -080052#include <memory>
Bowgo Tsaid4beed22017-02-18 18:33:13 +080053#include <set>
54#include <vector>
Rom Lemarchand6a524432015-02-28 06:39:11 -080055
Tom Cherryfa0c21c2015-07-23 17:53:11 -070056#include "action.h"
Tom Cherrybac32992015-07-31 12:45:25 -070057#include "bootchart.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070058#include "devices.h"
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +080059#include "fs_mgr.h"
Bowgo Tsai51c02722017-04-06 21:01:40 +080060#include "fs_mgr_avb.h"
Tom Cherryb7349902015-08-26 11:43:36 -070061#include "import_parser.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070062#include "init.h"
Tom Cherrybac32992015-07-31 12:45:25 -070063#include "init_parser.h"
64#include "keychords.h"
Colin Crossed8a7d82010-04-19 17:05:34 -070065#include "log.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070066#include "property_service.h"
Tom Cherry5ceb7b32017-04-17 16:34:20 -070067#include "reboot.h"
Tom Cherrybac32992015-07-31 12:45:25 -070068#include "service.h"
Colin Cross9c5366b2010-04-13 19:48:59 -070069#include "signal_handler.h"
Colin Crossf83d0b92010-04-21 12:04:20 -070070#include "ueventd.h"
Tom Cherrybac32992015-07-31 12:45:25 -070071#include "util.h"
Arve Hjønnevågd97d9072012-06-13 21:51:56 -070072#include "watchdogd.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070073
Tom Cherrye2490972017-03-28 16:40:41 -070074using android::base::GetProperty;
Elliott Hughes9605a942016-11-10 17:43:47 -080075using android::base::StringPrintf;
76
Stephen Smalleye46f9d52012-01-13 08:48:47 -050077struct selabel_handle *sehandle;
rpcraig63207cd2012-08-09 10:05:49 -040078struct selabel_handle *sehandle_prop;
Stephen Smalleye46f9d52012-01-13 08:48:47 -050079
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070080static int property_triggers_enabled = 0;
81
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070082static char qemu[32];
83
Viorel Suman70daa672016-03-21 10:08:07 +020084std::string default_console = "/dev/console";
Elliott Hughes9605a942016-11-10 17:43:47 -080085static time_t process_needs_restart_at;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070086
Tom Cherrybac32992015-07-31 12:45:25 -070087const char *ENV[32];
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070088
Elliott Hughes929f4072015-04-24 21:13:44 -070089static int epoll_fd = -1;
90
Wei Wang132ac312017-01-25 16:27:03 -080091static std::unique_ptr<Timer> waiting_for_prop(nullptr);
92static std::string wait_prop_name;
93static std::string wait_prop_value;
94
Elliott Hughes929f4072015-04-24 21:13:44 -070095void register_epoll_handler(int fd, void (*fn)()) {
96 epoll_event ev;
97 ev.events = EPOLLIN;
98 ev.data.ptr = reinterpret_cast<void*>(fn);
99 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700100 PLOG(ERROR) << "epoll_ctl failed";
Elliott Hughes929f4072015-04-24 21:13:44 -0700101 }
102}
103
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700104/* add_environment - add "key=value" to the current environment */
105int add_environment(const char *key, const char *val)
106{
James Morrissey381341f2014-05-16 11:36:36 +0100107 size_t n;
108 size_t key_len = strlen(key);
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -0700109
James Morrissey381341f2014-05-16 11:36:36 +0100110 /* The last environment entry is reserved to terminate the list */
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700111 for (n = 0; n < (arraysize(ENV) - 1); n++) {
James Morrissey381341f2014-05-16 11:36:36 +0100112
113 /* Delete any existing entry for this key */
114 if (ENV[n] != NULL) {
115 size_t entry_key_len = strcspn(ENV[n], "=");
116 if ((entry_key_len == key_len) && (strncmp(ENV[n], key, entry_key_len) == 0)) {
117 free((char*)ENV[n]);
118 ENV[n] = NULL;
119 }
120 }
121
122 /* Add entry if a free slot is available */
123 if (ENV[n] == NULL) {
Elliott Hughesf3cf4382015-02-03 17:12:07 -0800124 char* entry;
125 asprintf(&entry, "%s=%s", key, val);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700126 ENV[n] = entry;
127 return 0;
128 }
129 }
130
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700131 LOG(ERROR) << "No env. room to store: '" << key << "':'" << val << "'";
James Morrissey381341f2014-05-16 11:36:36 +0100132
133 return -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700134}
135
Wei Wang2d0fdaa2017-02-02 10:52:39 -0800136bool start_waiting_for_property(const char *name, const char *value)
Wei Wang132ac312017-01-25 16:27:03 -0800137{
138 if (waiting_for_prop) {
139 return false;
140 }
Tom Cherrye2490972017-03-28 16:40:41 -0700141 if (GetProperty(name, "") != value) {
Wei Wang132ac312017-01-25 16:27:03 -0800142 // Current property value is not equal to expected value
143 wait_prop_name = name;
144 wait_prop_value = value;
145 waiting_for_prop.reset(new Timer());
146 } else {
Wei Wang2d0fdaa2017-02-02 10:52:39 -0800147 LOG(INFO) << "start_waiting_for_property(\""
148 << name << "\", \"" << value << "\"): already set";
Wei Wang132ac312017-01-25 16:27:03 -0800149 }
150 return true;
151}
152
Tom Cherry5ceb7b32017-04-17 16:34:20 -0700153void property_changed(const std::string& name, const std::string& value) {
154 // If the property is sys.powerctl, we bypass the event queue and immediately handle it.
155 // This is to ensure that init will always and immediately shutdown/reboot, regardless of
156 // if there are other pending events to process or if init is waiting on an exec service or
157 // waiting on a property.
158 if (name == "sys.powerctl") HandlePowerctlMessage(value);
159
Colin Crossebc6ff12010-04-13 19:52:01 -0700160 if (property_triggers_enabled)
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700161 ActionManager::GetInstance().QueuePropertyTrigger(name, value);
Wei Wang132ac312017-01-25 16:27:03 -0800162 if (waiting_for_prop) {
163 if (wait_prop_name == name && wait_prop_value == value) {
164 wait_prop_name.clear();
165 wait_prop_value.clear();
166 LOG(INFO) << "Wait for property took " << *waiting_for_prop;
167 waiting_for_prop.reset();
168 }
169 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700170}
171
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700172static void restart_processes()
173{
Elliott Hughes9605a942016-11-10 17:43:47 -0800174 process_needs_restart_at = 0;
175 ServiceManager::GetInstance().ForEachServiceWithFlags(SVC_RESTARTING, [](Service* s) {
176 s->RestartIfNeeded(&process_needs_restart_at);
177 });
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700178}
179
Elliott Hughesbdeac392016-04-12 15:38:27 -0700180void handle_control_message(const std::string& msg, const std::string& name) {
Tom Cherrybac32992015-07-31 12:45:25 -0700181 Service* svc = ServiceManager::GetInstance().FindServiceByName(name);
Elliott Hughesbdeac392016-04-12 15:38:27 -0700182 if (svc == nullptr) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700183 LOG(ERROR) << "no such service '" << name << "'";
Elliott Hughesbdeac392016-04-12 15:38:27 -0700184 return;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700185 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700186
Tom Cherrybac32992015-07-31 12:45:25 -0700187 if (msg == "start") {
Elliott Hughesbdeac392016-04-12 15:38:27 -0700188 svc->Start();
Tom Cherrybac32992015-07-31 12:45:25 -0700189 } else if (msg == "stop") {
Elliott Hughesbdeac392016-04-12 15:38:27 -0700190 svc->Stop();
Tom Cherrybac32992015-07-31 12:45:25 -0700191 } else if (msg == "restart") {
Elliott Hughesbdeac392016-04-12 15:38:27 -0700192 svc->Restart();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700193 } else {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700194 LOG(ERROR) << "unknown control msg '" << msg << "'";
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700195 }
196}
197
Tom Cherry96f67312015-07-30 13:52:55 -0700198static int wait_for_coldboot_done_action(const std::vector<std::string>& args) {
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700199 Timer t;
200
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700201 LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE "...";
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000202
203 // Historically we had a 1s timeout here because we weren't otherwise
204 // tracking boot time, and many OEMs made their sepolicy regular
205 // expressions too expensive (http://b/19899875).
206
207 // Now we're tracking boot time, just log the time taken to a system
208 // property. We still panic if it takes more than a minute though,
209 // because any build that slow isn't likely to boot at all, and we'd
210 // rather any test lab devices fail back to the bootloader.
211 if (wait_for_file(COLDBOOT_DONE, 60s) < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700212 LOG(ERROR) << "Timed out waiting for " COLDBOOT_DONE;
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000213 panic();
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700214 }
215
James Hawkins27c05222017-01-26 11:55:44 -0800216 property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration_ms()).c_str());
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700217 return 0;
Colin Crossebc6ff12010-04-13 19:52:01 -0700218}
219
Alex Klyubin0d872d82013-08-16 13:19:24 -0700220/*
221 * Writes 512 bytes of output from Hardware RNG (/dev/hw_random, backed
222 * by Linux kernel's hw_random framework) into Linux RNG's via /dev/urandom.
223 * Does nothing if Hardware RNG is not present.
224 *
225 * Since we don't yet trust the quality of Hardware RNG, these bytes are not
226 * mixed into the primary pool of Linux RNG and the entropy estimate is left
227 * unmodified.
228 *
229 * If the HW RNG device /dev/hw_random is present, we require that at least
230 * 512 bytes read from it are written into Linux RNG. QA is expected to catch
231 * devices/configurations where these I/O operations are blocking for a long
232 * time. We do not reboot or halt on failures, as this is a best-effort
233 * attempt.
234 */
Tom Cherry96f67312015-07-30 13:52:55 -0700235static int mix_hwrng_into_linux_rng_action(const std::vector<std::string>& args)
Alex Klyubin0d872d82013-08-16 13:19:24 -0700236{
237 int result = -1;
238 int hwrandom_fd = -1;
239 int urandom_fd = -1;
240 char buf[512];
241 ssize_t chunk_size;
242 size_t total_bytes_written = 0;
243
244 hwrandom_fd = TEMP_FAILURE_RETRY(
Nick Kralevich45a884f2015-02-02 14:37:22 -0800245 open("/dev/hw_random", O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
Alex Klyubin0d872d82013-08-16 13:19:24 -0700246 if (hwrandom_fd == -1) {
247 if (errno == ENOENT) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700248 LOG(ERROR) << "/dev/hw_random not found";
249 // It's not an error to not have a Hardware RNG.
250 result = 0;
Alex Klyubin0d872d82013-08-16 13:19:24 -0700251 } else {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700252 PLOG(ERROR) << "Failed to open /dev/hw_random";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700253 }
254 goto ret;
255 }
256
257 urandom_fd = TEMP_FAILURE_RETRY(
Nick Kralevich45a884f2015-02-02 14:37:22 -0800258 open("/dev/urandom", O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Alex Klyubin0d872d82013-08-16 13:19:24 -0700259 if (urandom_fd == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700260 PLOG(ERROR) << "Failed to open /dev/urandom";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700261 goto ret;
262 }
263
264 while (total_bytes_written < sizeof(buf)) {
265 chunk_size = TEMP_FAILURE_RETRY(
266 read(hwrandom_fd, buf, sizeof(buf) - total_bytes_written));
267 if (chunk_size == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700268 PLOG(ERROR) << "Failed to read from /dev/hw_random";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700269 goto ret;
270 } else if (chunk_size == 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700271 LOG(ERROR) << "Failed to read from /dev/hw_random: EOF";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700272 goto ret;
273 }
274
275 chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size));
276 if (chunk_size == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700277 PLOG(ERROR) << "Failed to write to /dev/urandom";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700278 goto ret;
279 }
280 total_bytes_written += chunk_size;
281 }
282
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700283 LOG(INFO) << "Mixed " << total_bytes_written << " bytes from /dev/hw_random into /dev/urandom";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700284 result = 0;
285
286ret:
287 if (hwrandom_fd != -1) {
288 close(hwrandom_fd);
289 }
290 if (urandom_fd != -1) {
291 close(urandom_fd);
292 }
Alex Klyubin0d872d82013-08-16 13:19:24 -0700293 return result;
294}
295
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000296static void security_failure() {
297 LOG(ERROR) << "Security failure...";
298 panic();
299}
300
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800301static bool set_highest_available_option_value(std::string path, int min, int max)
302{
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000303 std::ifstream inf(path, std::fstream::in);
304 if (!inf) {
305 LOG(ERROR) << "Cannot open for reading: " << path;
306 return false;
307 }
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800308
309 int current = max;
310 while (current >= min) {
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000311 // try to write out new value
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800312 std::string str_val = std::to_string(current);
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000313 std::ofstream of(path, std::fstream::out);
314 if (!of) {
315 LOG(ERROR) << "Cannot open for writing: " << path;
316 return false;
317 }
318 of << str_val << std::endl;
319 of.close();
320
321 // check to make sure it was recorded
322 inf.seekg(0);
323 std::string str_rec;
324 inf >> str_rec;
325 if (str_val.compare(str_rec) == 0) {
326 break;
327 }
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800328 current--;
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000329 }
330 inf.close();
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800331
332 if (current < min) {
333 LOG(ERROR) << "Unable to set minimum option value " << min << " in " << path;
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000334 return false;
335 }
336 return true;
337}
338
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800339#define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits"
340#define MMAP_RND_COMPAT_PATH "/proc/sys/vm/mmap_rnd_compat_bits"
341
342/* __attribute__((unused)) due to lack of mips support: see mips block
343 * in set_mmap_rnd_bits_action */
344static bool __attribute__((unused)) set_mmap_rnd_bits_min(int start, int min, bool compat) {
345 std::string path;
346 if (compat) {
347 path = MMAP_RND_COMPAT_PATH;
348 } else {
349 path = MMAP_RND_PATH;
350 }
351
352 return set_highest_available_option_value(path, min, start);
353}
354
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000355/*
356 * Set /proc/sys/vm/mmap_rnd_bits and potentially
357 * /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values.
358 * Returns -1 if unable to set these to an acceptable value.
359 *
360 * To support this sysctl, the following upstream commits are needed:
361 *
362 * d07e22597d1d mm: mmap: add new /proc tunable for mmap_base ASLR
363 * e0c25d958f78 arm: mm: support ARCH_MMAP_RND_BITS
364 * 8f0d3aa9de57 arm64: mm: support ARCH_MMAP_RND_BITS
365 * 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS
366 * ec9ee4acd97c drivers: char: random: add get_random_long()
367 * 5ef11c35ce86 mm: ASLR: use get_random_long()
368 */
369static int set_mmap_rnd_bits_action(const std::vector<std::string>& args)
370{
371 int ret = -1;
372
373 /* values are arch-dependent */
374#if defined(__aarch64__)
375 /* arm64 supports 18 - 33 bits depending on pagesize and VA_SIZE */
376 if (set_mmap_rnd_bits_min(33, 24, false)
377 && set_mmap_rnd_bits_min(16, 16, true)) {
378 ret = 0;
379 }
380#elif defined(__x86_64__)
381 /* x86_64 supports 28 - 32 bits */
382 if (set_mmap_rnd_bits_min(32, 32, false)
383 && set_mmap_rnd_bits_min(16, 16, true)) {
384 ret = 0;
385 }
386#elif defined(__arm__) || defined(__i386__)
387 /* check to see if we're running on 64-bit kernel */
388 bool h64 = !access(MMAP_RND_COMPAT_PATH, F_OK);
389 /* supported 32-bit architecture must have 16 bits set */
390 if (set_mmap_rnd_bits_min(16, 16, h64)) {
391 ret = 0;
392 }
393#elif defined(__mips__) || defined(__mips64__)
394 // TODO: add mips support b/27788820
395 ret = 0;
396#else
dcashman41d0b6d2016-12-14 08:37:11 -0800397 LOG(ERROR) << "Unknown architecture";
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000398#endif
399
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000400 if (ret == -1) {
401 LOG(ERROR) << "Unable to set adequate mmap entropy value!";
402 security_failure();
403 }
404 return ret;
405}
406
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800407#define KPTR_RESTRICT_PATH "/proc/sys/kernel/kptr_restrict"
408#define KPTR_RESTRICT_MINVALUE 2
409#define KPTR_RESTRICT_MAXVALUE 4
410
411/* Set kptr_restrict to the highest available level.
412 *
413 * Aborts if unable to set this to an acceptable value.
414 */
415static int set_kptr_restrict_action(const std::vector<std::string>& args)
416{
417 std::string path = KPTR_RESTRICT_PATH;
418
419 if (!set_highest_available_option_value(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
420 LOG(ERROR) << "Unable to set adequate kptr_restrict value!";
421 security_failure();
422 }
423 return 0;
424}
425
Tom Cherry96f67312015-07-30 13:52:55 -0700426static int keychord_init_action(const std::vector<std::string>& args)
Colin Crossebc6ff12010-04-13 19:52:01 -0700427{
428 keychord_init();
429 return 0;
430}
431
Tom Cherry96f67312015-07-30 13:52:55 -0700432static int console_init_action(const std::vector<std::string>& args)
Colin Crossebc6ff12010-04-13 19:52:01 -0700433{
Tom Cherrye2490972017-03-28 16:40:41 -0700434 std::string console = GetProperty("ro.boot.console", "");
Viorel Sumanefc72752016-03-21 10:23:43 +0200435 if (!console.empty()) {
Viorel Suman70daa672016-03-21 10:08:07 +0200436 default_console = "/dev/" + console;
Colin Crossebc6ff12010-04-13 19:52:01 -0700437 }
Colin Crossebc6ff12010-04-13 19:52:01 -0700438 return 0;
439}
440
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700441static void import_kernel_nv(const std::string& key, const std::string& value, bool for_emulator) {
442 if (key.empty()) return;
Dima Zavin5511c842011-12-19 11:21:32 -0800443
444 if (for_emulator) {
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700445 // In the emulator, export any kernel option with the "ro.kernel." prefix.
Elliott Hughes9605a942016-11-10 17:43:47 -0800446 property_set(StringPrintf("ro.kernel.%s", key.c_str()).c_str(), value.c_str());
Dima Zavin5511c842011-12-19 11:21:32 -0800447 return;
448 }
449
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700450 if (key == "qemu") {
451 strlcpy(qemu, value.c_str(), sizeof(qemu));
452 } else if (android::base::StartsWith(key, "androidboot.")) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800453 property_set(StringPrintf("ro.boot.%s", key.c_str() + 12).c_str(), value.c_str());
Dima Zavin5511c842011-12-19 11:21:32 -0800454 }
455}
456
Sami Tolvanen9e9efca2015-12-07 12:33:58 +0000457static void export_oem_lock_status() {
Tom Cherrye2490972017-03-28 16:40:41 -0700458 if (!android::base::GetBoolProperty("ro.oem_unlock_supported", false)) {
Sami Tolvanen9e9efca2015-12-07 12:33:58 +0000459 return;
460 }
461
Tom Cherrye2490972017-03-28 16:40:41 -0700462 std::string value = GetProperty("ro.boot.verifiedbootstate", "");
Sami Tolvanen9e9efca2015-12-07 12:33:58 +0000463
464 if (!value.empty()) {
465 property_set("ro.boot.flash.locked", value == "orange" ? "0" : "1");
466 }
467}
468
Elliott Hughesd679bc92015-03-20 08:50:46 -0700469static void export_kernel_boot_props() {
Dima Zavin5511c842011-12-19 11:21:32 -0800470 struct {
471 const char *src_prop;
Elliott Hughesd679bc92015-03-20 08:50:46 -0700472 const char *dst_prop;
473 const char *default_value;
Dima Zavin5511c842011-12-19 11:21:32 -0800474 } prop_map[] = {
Elliott Hughesd679bc92015-03-20 08:50:46 -0700475 { "ro.boot.serialno", "ro.serialno", "", },
476 { "ro.boot.mode", "ro.bootmode", "unknown", },
477 { "ro.boot.baseband", "ro.baseband", "unknown", },
Dima Zavin5511c842011-12-19 11:21:32 -0800478 { "ro.boot.bootloader", "ro.bootloader", "unknown", },
Elliott Hughesd679bc92015-03-20 08:50:46 -0700479 { "ro.boot.hardware", "ro.hardware", "unknown", },
480 { "ro.boot.revision", "ro.revision", "0", },
Dima Zavin5511c842011-12-19 11:21:32 -0800481 };
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700482 for (size_t i = 0; i < arraysize(prop_map); i++) {
Tom Cherrye2490972017-03-28 16:40:41 -0700483 std::string value = GetProperty(prop_map[i].src_prop, "");
Yabin Cui74edcea2015-07-24 10:11:05 -0700484 property_set(prop_map[i].dst_prop, (!value.empty()) ? value.c_str() : prop_map[i].default_value);
Dima Zavin5511c842011-12-19 11:21:32 -0800485 }
Dima Zavin5511c842011-12-19 11:21:32 -0800486}
Colin Crossebc6ff12010-04-13 19:52:01 -0700487
Bowgo Tsai51c02722017-04-06 21:01:40 +0800488/* Reads the content of device tree file into dt_value.
489 * Returns true if the read is success, false otherwise.
490 */
491static bool read_dt_file(const std::string& file_name, std::string* dt_value) {
492 if (android::base::ReadFileToString(file_name, dt_value)) {
493 if (!dt_value->empty()) {
494 dt_value->pop_back(); // Trim the trailing '\0' out.
Sandeep Patilc20c0c22017-02-23 16:09:34 -0800495 return true;
496 }
Rom Lemarchand6a524432015-02-28 06:39:11 -0800497 }
Sandeep Patilc20c0c22017-02-23 16:09:34 -0800498 return false;
Sandeep Patilfc86f242017-02-09 19:19:31 -0800499}
500
Bowgo Tsai51c02722017-04-06 21:01:40 +0800501static const std::string kAndroidDtDir("/proc/device-tree/firmware/android/");
Sandeep Patilfc86f242017-02-09 19:19:31 -0800502
Bowgo Tsai51c02722017-04-06 21:01:40 +0800503static bool is_dt_value_expected(const std::string& dt_file_suffix,
504 const std::string& expected_value) {
505 std::string dt_value;
506 std::string file_name = kAndroidDtDir + dt_file_suffix;
507
508 if (read_dt_file(file_name, &dt_value)) {
509 if (dt_value == expected_value) {
Sandeep Patilc20c0c22017-02-23 16:09:34 -0800510 return true;
511 }
Sandeep Patilfc86f242017-02-09 19:19:31 -0800512 }
Sandeep Patilc20c0c22017-02-23 16:09:34 -0800513 return false;
Sandeep Patilfc86f242017-02-09 19:19:31 -0800514}
515
Bowgo Tsai51c02722017-04-06 21:01:40 +0800516static inline bool is_dt_compatible() {
517 return is_dt_value_expected("compatible", "android,firmware");
518}
519
520static inline bool is_dt_fstab_compatible() {
521 return is_dt_value_expected("fstab/compatible", "android,fstab");
522}
523
524static inline bool is_dt_vbmeta_compatible() {
525 return is_dt_value_expected("vbmeta/compatible", "android,vbmeta");
526}
527
528// Gets the vbmeta config from device tree. Specifically, the 'parts' and 'by_name_prefix'.
529// /{
530// firmware {
531// android {
532// vbmeta {
533// compatible = "android,vbmeta";
534// parts = "vbmeta,boot,system,vendor"
535// by_name_prefix="/dev/block/platform/soc.0/f9824900.sdhci/by-name/"
536// };
537// };
538// };
539// }
540static bool get_vbmeta_config_from_dt(std::string* vbmeta_partitions,
541 std::string* device_file_by_name_prefix) {
542 std::string file_name = kAndroidDtDir + "vbmeta/parts";
543 if (!read_dt_file(file_name, vbmeta_partitions)) return false;
544
545 file_name = kAndroidDtDir + "vbmeta/by_name_prefix";
546 if (!read_dt_file(file_name, device_file_by_name_prefix)) return false;
547
548 return true;
549}
550
Sandeep Patilfc86f242017-02-09 19:19:31 -0800551static void process_kernel_dt() {
552 if (!is_dt_compatible()) return;
553
Bowgo Tsai51c02722017-04-06 21:01:40 +0800554 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(kAndroidDtDir.c_str()), closedir);
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700555 if (!dir) return;
Rom Lemarchand6a524432015-02-28 06:39:11 -0800556
Sandeep Patilfc86f242017-02-09 19:19:31 -0800557 std::string dt_file;
Rom Lemarchand6a524432015-02-28 06:39:11 -0800558 struct dirent *dp;
559 while ((dp = readdir(dir.get())) != NULL) {
Rom Lemarchand1dcf3252015-11-08 17:51:50 -0800560 if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") || !strcmp(dp->d_name, "name")) {
Rom Lemarchand6a524432015-02-28 06:39:11 -0800561 continue;
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700562 }
Rom Lemarchand6a524432015-02-28 06:39:11 -0800563
Bowgo Tsai51c02722017-04-06 21:01:40 +0800564 std::string file_name = kAndroidDtDir + dp->d_name;
Rom Lemarchand6a524432015-02-28 06:39:11 -0800565
566 android::base::ReadFileToString(file_name, &dt_file);
567 std::replace(dt_file.begin(), dt_file.end(), ',', '.');
568
Elliott Hughes9605a942016-11-10 17:43:47 -0800569 std::string property_name = StringPrintf("ro.boot.%s", dp->d_name);
Elliott Hughesdb3f2672015-03-20 09:45:18 -0700570 property_set(property_name.c_str(), dt_file.c_str());
Rom Lemarchand6a524432015-02-28 06:39:11 -0800571 }
572}
573
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700574static void process_kernel_cmdline() {
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700575 // The first pass does the common stuff, and finds if we are in qemu.
576 // The second pass is only necessary for qemu to export all kernel params
577 // as properties.
Nick Kralevichf667a322015-04-25 17:42:52 -0700578 import_kernel_cmdline(false, import_kernel_nv);
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700579 if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv);
Colin Crossebc6ff12010-04-13 19:52:01 -0700580}
581
caozhiyuanb104c502016-11-26 21:14:07 +0800582static int property_enable_triggers_action(const std::vector<std::string>& args)
583{
584 /* Enable property triggers. */
585 property_triggers_enabled = 1;
586 return 0;
587}
588
Tom Cherry96f67312015-07-30 13:52:55 -0700589static int queue_property_triggers_action(const std::vector<std::string>& args)
Colin Crossebc6ff12010-04-13 19:52:01 -0700590{
caozhiyuanb104c502016-11-26 21:14:07 +0800591 ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700592 ActionManager::GetInstance().QueueAllPropertyTriggers();
Colin Crossebc6ff12010-04-13 19:52:01 -0700593 return 0;
594}
595
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700596static void selinux_init_all_handles(void)
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500597{
Stephen Smalleyae6f3d72012-05-01 15:02:53 -0400598 sehandle = selinux_android_file_context_handle();
Stephen Smalleydbd37f22014-01-28 10:34:09 -0500599 selinux_android_set_sehandle(sehandle);
rpcraig63207cd2012-08-09 10:05:49 -0400600 sehandle_prop = selinux_android_prop_context_handle();
Stephen Smalleyae6f3d72012-05-01 15:02:53 -0400601}
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500602
Nick Kralevichd34e4072015-04-28 12:39:41 -0700603enum selinux_enforcing_status { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
Nick Kralevichf667a322015-04-25 17:42:52 -0700604
605static selinux_enforcing_status selinux_status_from_cmdline() {
606 selinux_enforcing_status status = SELINUX_ENFORCING;
607
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700608 import_kernel_cmdline(false, [&](const std::string& key, const std::string& value, bool in_qemu) {
609 if (key == "androidboot.selinux" && value == "permissive") {
610 status = SELINUX_PERMISSIVE;
Nick Kralevichf667a322015-04-25 17:42:52 -0700611 }
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700612 });
Nick Kralevichf667a322015-04-25 17:42:52 -0700613
614 return status;
615}
616
Nick Kralevich935bd3e2013-06-26 15:37:26 -0700617static bool selinux_is_enforcing(void)
618{
Nick Kralevichd34e4072015-04-28 12:39:41 -0700619 if (ALLOW_PERMISSIVE_SELINUX) {
Nick Kralevichf667a322015-04-25 17:42:52 -0700620 return selinux_status_from_cmdline() == SELINUX_ENFORCING;
Nick Kralevich935bd3e2013-06-26 15:37:26 -0700621 }
Nick Kralevich935bd3e2013-06-26 15:37:26 -0700622 return true;
623}
624
Elliott Hughesda40c002015-03-27 23:20:44 -0700625static int audit_callback(void *data, security_class_t /*cls*/, char *buf, size_t len) {
William Robertsd7aea442015-10-01 16:03:47 -0700626
627 property_audit_data *d = reinterpret_cast<property_audit_data*>(data);
628
629 if (!d || !d->name || !d->cr) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700630 LOG(ERROR) << "audit_callback invoked with null data arguments!";
William Robertsd7aea442015-10-01 16:03:47 -0700631 return 0;
632 }
633
634 snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name,
635 d->cr->pid, d->cr->uid, d->cr->gid);
rpcraig63207cd2012-08-09 10:05:49 -0400636 return 0;
637}
638
Alex Klyubin16696e22017-02-28 12:32:20 -0800639/*
640 * Forks, executes the provided program in the child, and waits for the completion in the parent.
Alex Klyubin11850502017-03-05 14:28:27 -0800641 * Child's stderr is captured and logged using LOG(ERROR).
Alex Klyubin16696e22017-02-28 12:32:20 -0800642 *
643 * Returns true if the child exited with status code 0, returns false otherwise.
644 */
645static bool fork_execve_and_wait_for_completion(const char* filename, char* const argv[],
646 char* const envp[]) {
Alex Klyubin11850502017-03-05 14:28:27 -0800647 // Create a pipe used for redirecting child process's output.
648 // * pipe_fds[0] is the FD the parent will use for reading.
649 // * pipe_fds[1] is the FD the child will use for writing.
650 int pipe_fds[2];
651 if (pipe(pipe_fds) == -1) {
652 PLOG(ERROR) << "Failed to create pipe";
653 return false;
654 }
655
Alex Klyubin16696e22017-02-28 12:32:20 -0800656 pid_t child_pid = fork();
657 if (child_pid == -1) {
658 PLOG(ERROR) << "Failed to fork for " << filename;
659 return false;
660 }
661
662 if (child_pid == 0) {
663 // fork succeeded -- this is executing in the child process
Alex Klyubin11850502017-03-05 14:28:27 -0800664
665 // Close the pipe FD not used by this process
666 TEMP_FAILURE_RETRY(close(pipe_fds[0]));
667
668 // Redirect stderr to the pipe FD provided by the parent
669 if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
670 PLOG(ERROR) << "Failed to redirect stderr of " << filename;
671 _exit(127);
672 return false;
673 }
674 TEMP_FAILURE_RETRY(close(pipe_fds[1]));
675
Alex Klyubin16696e22017-02-28 12:32:20 -0800676 if (execve(filename, argv, envp) == -1) {
677 PLOG(ERROR) << "Failed to execve " << filename;
678 return false;
679 }
680 // Unreachable because execve will have succeeded and replaced this code
681 // with child process's code.
682 _exit(127);
683 return false;
684 } else {
685 // fork succeeded -- this is executing in the original/parent process
Alex Klyubin11850502017-03-05 14:28:27 -0800686
687 // Close the pipe FD not used by this process
688 TEMP_FAILURE_RETRY(close(pipe_fds[1]));
689
690 // Log the redirected output of the child process.
691 // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
692 // As a result, we're buffering all output and logging it in one go at the end of the
693 // invocation, instead of logging it as it comes in.
694 const int child_out_fd = pipe_fds[0];
695 std::string child_output;
696 if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
697 PLOG(ERROR) << "Failed to capture full output of " << filename;
698 }
699 TEMP_FAILURE_RETRY(close(child_out_fd));
700 if (!child_output.empty()) {
701 // Log captured output, line by line, because LOG expects to be invoked for each line
702 std::istringstream in(child_output);
703 std::string line;
704 while (std::getline(in, line)) {
705 LOG(ERROR) << filename << ": " << line;
706 }
707 }
708
709 // Wait for child to terminate
Alex Klyubin16696e22017-02-28 12:32:20 -0800710 int status;
711 if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
712 PLOG(ERROR) << "Failed to wait for " << filename;
713 return false;
714 }
715
716 if (WIFEXITED(status)) {
717 int status_code = WEXITSTATUS(status);
718 if (status_code == 0) {
719 return true;
720 } else {
721 LOG(ERROR) << filename << " exited with status " << status_code;
722 }
723 } else if (WIFSIGNALED(status)) {
724 LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
725 } else if (WIFSTOPPED(status)) {
726 LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
727 } else {
728 LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
729 }
730
731 return false;
732 }
733}
734
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800735static bool read_first_line(const char* file, std::string* line) {
736 line->clear();
737
738 std::string contents;
739 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
740 return false;
741 }
742 std::istringstream in(contents);
743 std::getline(in, *line);
744 return true;
745}
746
747static bool selinux_find_precompiled_split_policy(std::string* file) {
748 file->clear();
749
750 static constexpr const char precompiled_sepolicy[] = "/vendor/etc/selinux/precompiled_sepolicy";
751 if (access(precompiled_sepolicy, R_OK) == -1) {
752 return false;
753 }
754 std::string actual_plat_id;
Dan Cashman39ffec72017-04-06 09:51:23 -0700755 if (!read_first_line("/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256",
756 &actual_plat_id)) {
757 PLOG(INFO) << "Failed to read "
758 "/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256";
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800759 return false;
760 }
761 std::string precompiled_plat_id;
Dan Cashman39ffec72017-04-06 09:51:23 -0700762 if (!read_first_line("/vendor/etc/selinux/precompiled_sepolicy.plat_and_mapping.sha256",
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800763 &precompiled_plat_id)) {
Dan Cashman39ffec72017-04-06 09:51:23 -0700764 PLOG(INFO) << "Failed to read "
765 "/vendor/etc/selinux/"
766 "precompiled_sepolicy.plat_and_mapping.sha256";
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800767 return false;
768 }
769 if ((actual_plat_id.empty()) || (actual_plat_id != precompiled_plat_id)) {
770 return false;
771 }
772
773 *file = precompiled_sepolicy;
774 return true;
775}
776
Dan Cashman692c3e42017-04-10 12:20:01 -0700777static bool selinux_get_vendor_mapping_version(std::string* plat_vers) {
778 if (!read_first_line("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
779 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
780 return false;
781 }
782 if (plat_vers->empty()) {
783 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
784 return false;
785 }
786 return true;
787}
788
Alex Klyubinc2a4c9a2017-03-02 12:43:10 -0800789static constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
Alex Klyubin16696e22017-02-28 12:32:20 -0800790
791static bool selinux_is_split_policy_device() { return access(plat_policy_cil_file, R_OK) != -1; }
792
793/*
794 * Loads SELinux policy split across platform/system and non-platform/vendor files.
795 *
796 * Returns true upon success, false otherwise (failure cause is logged).
797 */
798static bool selinux_load_split_policy() {
799 // IMPLEMENTATION NOTE: Split policy consists of three CIL files:
800 // * platform -- policy needed due to logic contained in the system image,
801 // * non-platform -- policy needed due to logic contained in the vendor image,
802 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
803 // with newer versions of platform policy.
804 //
805 // secilc is invoked to compile the above three policy files into a single monolithic policy
806 // file. This file is then loaded into the kernel.
807
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800808 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
809 // must match the platform policy on the system image.
810 std::string precompiled_sepolicy_file;
811 if (selinux_find_precompiled_split_policy(&precompiled_sepolicy_file)) {
812 android::base::unique_fd fd(
813 open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
814 if (fd != -1) {
815 if (selinux_android_load_policy_from_fd(fd, precompiled_sepolicy_file.c_str()) < 0) {
816 LOG(ERROR) << "Failed to load SELinux policy from " << precompiled_sepolicy_file;
817 return false;
818 }
819 return true;
820 }
821 }
822 // No suitable precompiled policy could be loaded
823
Alex Klyubin16696e22017-02-28 12:32:20 -0800824 LOG(INFO) << "Compiling SELinux policy";
825
Alex Klyubina71dfec2017-03-09 10:56:58 -0800826 // Determine the highest policy language version supported by the kernel
827 set_selinuxmnt("/sys/fs/selinux");
828 int max_policy_version = security_policyvers();
829 if (max_policy_version == -1) {
830 PLOG(ERROR) << "Failed to determine highest policy version supported by kernel";
831 return false;
832 }
833
Alex Klyubin16696e22017-02-28 12:32:20 -0800834 // We store the output of the compilation on /dev because this is the most convenient tmpfs
835 // storage mount available this early in the boot sequence.
836 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
837 android::base::unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
838 if (compiled_sepolicy_fd < 0) {
839 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
840 return false;
841 }
842
Dan Cashman692c3e42017-04-10 12:20:01 -0700843 // Determine which mapping file to include
844 std::string vend_plat_vers;
845 if (!selinux_get_vendor_mapping_version(&vend_plat_vers)) {
846 return false;
847 }
848 std::string mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
Alex Klyubina71dfec2017-03-09 10:56:58 -0800849 // clang-format off
850 const char* compile_args[] = {
851 "/system/bin/secilc",
852 plat_policy_cil_file,
Jeff Vander Stoep955e3642017-04-21 16:35:43 -0700853 "-M", "true", "-G", "-N",
Alex Klyubina71dfec2017-03-09 10:56:58 -0800854 // Target the highest policy language version supported by the kernel
855 "-c", std::to_string(max_policy_version).c_str(),
Dan Cashman692c3e42017-04-10 12:20:01 -0700856 mapping_file.c_str(),
Alex Klyubina71dfec2017-03-09 10:56:58 -0800857 "/vendor/etc/selinux/nonplat_sepolicy.cil",
858 "-o", compiled_sepolicy,
859 // We don't care about file_contexts output by the compiler
860 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
861 nullptr};
862 // clang-format on
Alex Klyubin16696e22017-02-28 12:32:20 -0800863
864 if (!fork_execve_and_wait_for_completion(compile_args[0], (char**)compile_args, (char**)ENV)) {
865 unlink(compiled_sepolicy);
866 return false;
867 }
868 unlink(compiled_sepolicy);
869
870 LOG(INFO) << "Loading compiled SELinux policy";
871 if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) {
872 LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy;
873 return false;
874 }
875
876 return true;
877}
878
879/*
880 * Loads SELinux policy from a monolithic file.
881 *
882 * Returns true upon success, false otherwise (failure cause is logged).
883 */
884static bool selinux_load_monolithic_policy() {
885 LOG(VERBOSE) << "Loading SELinux policy from monolithic file";
886 if (selinux_android_load_policy() < 0) {
887 PLOG(ERROR) << "Failed to load monolithic SELinux policy";
888 return false;
889 }
890 return true;
891}
892
893/*
894 * Loads SELinux policy into the kernel.
895 *
896 * Returns true upon success, false otherwise (failure cause is logged).
897 */
898static bool selinux_load_policy() {
899 return selinux_is_split_policy_device() ? selinux_load_split_policy()
900 : selinux_load_monolithic_policy();
901}
902
Elliott Hughesf65730e2015-04-24 18:38:17 +0000903static void selinux_initialize(bool in_kernel_domain) {
Elliott Hughesda40c002015-03-27 23:20:44 -0700904 Timer t;
Stephen Smalleyeb3f4212014-02-12 16:17:00 -0500905
Elliott Hughesda40c002015-03-27 23:20:44 -0700906 selinux_callback cb;
907 cb.func_log = selinux_klog_callback;
908 selinux_set_callback(SELINUX_CB_LOG, cb);
909 cb.func_audit = audit_callback;
910 selinux_set_callback(SELINUX_CB_AUDIT, cb);
911
Elliott Hughesf65730e2015-04-24 18:38:17 +0000912 if (in_kernel_domain) {
Alex Klyubin16696e22017-02-28 12:32:20 -0800913 LOG(INFO) << "Loading SELinux policy";
914 if (!selinux_load_policy()) {
915 panic();
Elliott Hughesf65730e2015-04-24 18:38:17 +0000916 }
917
Nick Kralevichd34e4072015-04-28 12:39:41 -0700918 bool kernel_enforcing = (security_getenforce() == 1);
Elliott Hughesf65730e2015-04-24 18:38:17 +0000919 bool is_enforcing = selinux_is_enforcing();
Nick Kralevichd34e4072015-04-28 12:39:41 -0700920 if (kernel_enforcing != is_enforcing) {
921 if (security_setenforce(is_enforcing)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700922 PLOG(ERROR) << "security_setenforce(%s) failed" << (is_enforcing ? "true" : "false");
Nick Kralevichd34e4072015-04-28 12:39:41 -0700923 security_failure();
924 }
925 }
Elliott Hughesf65730e2015-04-24 18:38:17 +0000926
Jorge Lucangeli Obes77f0e9f2016-12-28 14:07:02 -0500927 if (!write_file("/sys/fs/selinux/checkreqprot", "0")) {
Nick Kralevicheedbe812015-04-25 14:10:03 -0700928 security_failure();
929 }
930
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000931 // init's first stage can't set properties, so pass the time to the second stage.
James Hawkins27c05222017-01-26 11:55:44 -0800932 setenv("INIT_SELINUX_TOOK", std::to_string(t.duration_ms()).c_str(), 1);
Elliott Hughesf65730e2015-04-24 18:38:17 +0000933 } else {
934 selinux_init_all_handles();
Nick Kralevich56fa0ac2013-06-24 17:41:40 -0700935 }
Nick Kralevich56fa0ac2013-06-24 17:41:40 -0700936}
937
Sandeep Patil74df5ba2017-03-29 10:31:26 -0700938// The files and directories that were created before initial sepolicy load
939// need to have their security context restored to the proper value.
940// This must happen before /dev is populated by ueventd.
941static void selinux_restore_context() {
942 LOG(INFO) << "Running restorecon...";
943 restorecon("/dev");
944 restorecon("/dev/kmsg");
945 restorecon("/dev/socket");
946 restorecon("/dev/random");
947 restorecon("/dev/urandom");
948 restorecon("/dev/__properties__");
Sandeep Patilf5b99d42017-03-29 10:33:41 -0700949
950 restorecon("/file_contexts.bin");
951 restorecon("/plat_file_contexts");
952 restorecon("/nonplat_file_contexts");
Sandeep Patil74df5ba2017-03-29 10:31:26 -0700953 restorecon("/plat_property_contexts");
954 restorecon("/nonplat_property_contexts");
Sandeep Patilf5b99d42017-03-29 10:33:41 -0700955 restorecon("/plat_seapp_contexts");
956 restorecon("/nonplat_seapp_contexts");
957 restorecon("/plat_service_contexts");
958 restorecon("/nonplat_service_contexts");
Martijn Coenen68872732017-04-12 18:02:33 -0700959 restorecon("/plat_hwservice_contexts");
960 restorecon("/nonplat_hwservice_contexts");
Sandeep Patilf5b99d42017-03-29 10:33:41 -0700961 restorecon("/sepolicy");
Martijn Coenen7c1e0d82017-04-03 11:08:20 -0700962 restorecon("/vndservice_contexts");
Sandeep Patilf5b99d42017-03-29 10:33:41 -0700963
Sandeep Patil74df5ba2017-03-29 10:31:26 -0700964 restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE);
965 restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
966 restorecon("/dev/device-mapper");
967}
968
Amit Pundird2e74db2016-06-29 19:00:00 +0530969// Set the UDC controller for the ConfigFS USB Gadgets.
970// Read the UDC controller in use from "/sys/class/udc".
971// In case of multiple UDC controllers select the first one.
972static void set_usb_controller() {
973 std::unique_ptr<DIR, decltype(&closedir)>dir(opendir("/sys/class/udc"), closedir);
974 if (!dir) return;
975
976 dirent* dp;
977 while ((dp = readdir(dir.get())) != nullptr) {
978 if (dp->d_name[0] == '.') continue;
979
980 property_set("sys.usb.controller", dp->d_name);
981 break;
982 }
983}
984
Bowgo Tsai51c02722017-04-06 21:01:40 +0800985// Creates "/dev/block/dm-XX" for dm-verity by running coldboot on /sys/block/dm-XX.
986static void device_init_dm_device(const std::string& dm_device) {
987 const std::string device_name(basename(dm_device.c_str()));
988 const std::string syspath = "/sys/block/" + device_name;
989
990 device_init(syspath.c_str(), [&](uevent* uevent) -> coldboot_action_t {
991 if (uevent->device_name && device_name == uevent->device_name) {
992 LOG(VERBOSE) << "early_mount: creating dm-verity device : " << dm_device;
993 return COLDBOOT_STOP;
994 }
995 return COLDBOOT_CONTINUE;
996 });
997 device_close();
998}
999
1000static bool vboot_1_0_mount_partitions(const std::vector<fstab_rec*>& fstab_recs) {
1001 if (fstab_recs.empty()) return false;
1002
1003 for (auto rec : fstab_recs) {
1004 bool need_create_dm_device = false;
1005 if (fs_mgr_is_verified(rec)) {
1006 // setup verity and create the dm-XX block device
1007 // needed to mount this partition
1008 int ret = fs_mgr_setup_verity(rec, false /* wait_for_verity_dev */);
1009 if (ret == FS_MGR_SETUP_VERITY_DISABLED) {
1010 LOG(INFO) << "verity disabled for '" << rec->mount_point << "'";
1011 } else if (ret == FS_MGR_SETUP_VERITY_SUCCESS) {
1012 need_create_dm_device = true;
1013 } else {
1014 PLOG(ERROR) << "early_mount: failed to setup verity for '" << rec->mount_point
1015 << "'";
1016 return false;
1017 }
1018 }
1019 if (need_create_dm_device) {
1020 // The exact block device name (rec->blk_device) is changed to "/dev/block/dm-XX".
1021 // Need to create it because ueventd isn't started during early mount.
1022 device_init_dm_device(rec->blk_device);
1023 }
1024 if (fs_mgr_do_mount_one(rec)) {
1025 PLOG(ERROR) << "early_mount: failed to mount '" << rec->mount_point << "'";
Sandeep Patil0a3e36f2017-02-15 15:45:01 -08001026 return false;
1027 }
Sandeep Patil0a3e36f2017-02-15 15:45:01 -08001028 }
1029
1030 return true;
1031}
1032
Bowgo Tsai51c02722017-04-06 21:01:40 +08001033static bool vboot_2_0_mount_partitions(const std::vector<fstab_rec*>& fstab_recs,
1034 const std::string& device_file_by_name_prefix) {
1035 if (fstab_recs.empty()) return false;
1036
1037 FsManagerAvbUniquePtr avb_handle = FsManagerAvbHandle::Open(device_file_by_name_prefix);
1038 if (!avb_handle) {
1039 LOG(INFO) << "Failed to Open FsManagerAvbHandle";
1040 return false;
1041 }
1042
Bowgo Tsai45180122017-04-13 21:17:48 +08001043 setenv("INIT_AVB_VERSION", avb_handle->avb_version().c_str(), 1);
Bowgo Tsai51c02722017-04-06 21:01:40 +08001044 for (auto rec : fstab_recs) {
1045 bool need_create_dm_device = false;
1046 if (fs_mgr_is_avb(rec)) {
Bowgo Tsai45180122017-04-13 21:17:48 +08001047 if (avb_handle->hashtree_disabled()) {
Bowgo Tsai51c02722017-04-06 21:01:40 +08001048 LOG(INFO) << "avb hashtree disabled for '" << rec->mount_point << "'";
1049 } else if (avb_handle->SetUpAvb(rec, false /* wait_for_verity_dev */)) {
1050 need_create_dm_device = true;
1051 } else {
1052 PLOG(ERROR) << "early_mount: failed to set up AVB on partition: '"
1053 << rec->mount_point << "'";
1054 return false;
1055 }
1056 }
1057 if (need_create_dm_device) {
1058 // The exact block device name (rec->blk_device) is changed to "/dev/block/dm-XX".
1059 // Need to create it because ueventd isn't started during early mount.
1060 device_init_dm_device(rec->blk_device);
1061 }
1062 if (fs_mgr_do_mount_one(rec)) {
1063 PLOG(ERROR) << "early_mount: failed to mount '" << rec->mount_point << "'";
1064 return false;
1065 }
1066 }
1067
1068 return true;
1069}
1070
1071static bool mount_early_partitions(const std::vector<fstab_rec*>& fstab_recs,
1072 const std::string& device_file_by_name_prefix) {
1073 if (is_dt_vbmeta_compatible()) { // AVB (external/avb) is used to setup dm-verity.
1074 return vboot_2_0_mount_partitions(fstab_recs, device_file_by_name_prefix);
1075 } else {
1076 return vboot_1_0_mount_partitions(fstab_recs);
1077 }
1078}
1079
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001080// Creates devices with uevent->partition_name matching one in the in/out
1081// partition_names. Note that the partition_names MUST have A/B suffix
1082// when A/B is used. Found partitions will then be removed from the
1083// partition_names for caller to check which devices are NOT created.
1084static void early_device_init(std::set<std::string>* partition_names) {
1085 if (partition_names->empty()) {
1086 return;
1087 }
1088 device_init(nullptr, [=](uevent* uevent) -> coldboot_action_t {
1089 if (!strncmp(uevent->subsystem, "firmware", 8)) {
1090 return COLDBOOT_CONTINUE;
1091 }
1092
1093 // we need platform devices to create symlinks
1094 if (!strncmp(uevent->subsystem, "platform", 8)) {
1095 return COLDBOOT_CREATE;
1096 }
1097
1098 // Ignore everything that is not a block device
1099 if (strncmp(uevent->subsystem, "block", 5)) {
1100 return COLDBOOT_CONTINUE;
1101 }
1102
1103 if (uevent->partition_name) {
1104 // match partition names to create device nodes for partitions
1105 // both partition_names and uevent->partition_name have A/B suffix when A/B is used
1106 auto iter = partition_names->find(uevent->partition_name);
1107 if (iter != partition_names->end()) {
1108 LOG(VERBOSE) << "early_mount: found partition: " << *iter;
1109 partition_names->erase(iter);
1110 if (partition_names->empty()) {
1111 return COLDBOOT_STOP; // found all partitions, stop coldboot
1112 } else {
1113 return COLDBOOT_CREATE; // create this device and continue to find others
1114 }
1115 }
1116 }
1117 // Not found a partition or find an unneeded partition, continue to find others
1118 return COLDBOOT_CONTINUE;
1119 });
1120}
1121
Bowgo Tsai51c02722017-04-06 21:01:40 +08001122static bool vboot_1_0_early_partitions(const std::vector<fstab_rec*>& early_fstab_recs,
1123 std::set<std::string>* out_partitions,
1124 bool* out_need_verity) {
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001125 std::string meta_partition;
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001126 for (auto fstab_rec : early_fstab_recs) {
1127 // don't allow verifyatboot for early mounted partitions
1128 if (fs_mgr_is_verifyatboot(fstab_rec)) {
1129 LOG(ERROR) << "early_mount: partitions can't be verified at boot";
1130 return false;
1131 }
1132 // check for verified partitions
1133 if (fs_mgr_is_verified(fstab_rec)) {
1134 *out_need_verity = true;
1135 }
1136 // check if verity metadata is on a separate partition and get partition
1137 // name from the end of the ->verity_loc path. verity state is not partition
1138 // specific, so there must be only 1 additional partition that carries
1139 // verity state.
1140 if (fstab_rec->verity_loc) {
1141 if (!meta_partition.empty()) {
1142 LOG(ERROR) << "early_mount: more than one meta partition found: " << meta_partition
1143 << ", " << basename(fstab_rec->verity_loc);
1144 return false;
1145 } else {
1146 meta_partition = basename(fstab_rec->verity_loc);
1147 }
1148 }
1149 }
1150
1151 // includes those early mount partitions and meta_partition (if any)
1152 // note that fstab_rec->blk_device has A/B suffix updated by fs_mgr when A/B is used
1153 for (auto fstab_rec : early_fstab_recs) {
1154 out_partitions->emplace(basename(fstab_rec->blk_device));
1155 }
1156
1157 if (!meta_partition.empty()) {
1158 out_partitions->emplace(std::move(meta_partition));
1159 }
1160
1161 return true;
1162}
1163
Bowgo Tsai51c02722017-04-06 21:01:40 +08001164// a.k.a. AVB (external/avb)
1165static bool vboot_2_0_early_partitions(std::set<std::string>* out_partitions, bool* out_need_verity,
1166 std::string* out_device_file_by_name_prefix) {
1167 std::string vbmeta_partitions;
1168 if (!get_vbmeta_config_from_dt(&vbmeta_partitions, out_device_file_by_name_prefix)) {
1169 return false;
1170 }
1171 // libavb verifies AVB metadata on all verified partitions at once.
1172 // e.g., The vbmeta_partitions will be "vbmeta,boot,system,vendor"
1173 // for libavb to verify metadata, even if we only need to early mount /vendor.
1174 std::vector<std::string> partitions = android::base::Split(vbmeta_partitions, ",");
1175 std::string ab_suffix = fs_mgr_get_slot_suffix();
1176 for (const auto& partition : partitions) {
1177 out_partitions->emplace(partition + ab_suffix);
1178 }
1179 *out_need_verity = true;
1180 return true;
1181}
1182
1183static bool get_early_partitions(const std::vector<fstab_rec*>& early_fstab_recs,
1184 std::set<std::string>* out_partitions, bool* out_need_verity,
1185 std::string* out_device_file_by_name_prefix) {
1186 *out_need_verity = false;
1187 out_partitions->clear();
1188 out_device_file_by_name_prefix->clear();
1189
1190 if (is_dt_vbmeta_compatible()) { // AVB (external/avb) is used to setup dm-verity.
1191 return vboot_2_0_early_partitions(out_partitions, out_need_verity,
1192 out_device_file_by_name_prefix);
1193 } else {
1194 return vboot_1_0_early_partitions(early_fstab_recs, out_partitions, out_need_verity);
1195 }
1196}
1197
Sandeep Patilfc86f242017-02-09 19:19:31 -08001198/* Early mount vendor and ODM partitions. The fstab is read from device-tree. */
Sandeep Patil35403eb2017-02-08 20:27:12 -08001199static bool early_mount() {
Bowgo Tsai32232722017-03-01 18:24:46 +08001200 // skip early mount if we're in recovery mode
1201 if (access("/sbin/recovery", F_OK) == 0) {
1202 LOG(INFO) << "Early mount skipped (recovery mode)";
1203 return true;
1204 }
1205
Sandeep Patilc20c0c22017-02-23 16:09:34 -08001206 // first check if device tree fstab entries are compatible
1207 if (!is_dt_fstab_compatible()) {
1208 LOG(INFO) << "Early mount skipped (missing/incompatible fstab in device tree)";
Sandeep Patil35403eb2017-02-08 20:27:12 -08001209 return true;
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +08001210 }
Sandeep Patil35403eb2017-02-08 20:27:12 -08001211
Sandeep Patilc20c0c22017-02-23 16:09:34 -08001212 std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> tab(
1213 fs_mgr_read_fstab_dt(), fs_mgr_free_fstab);
Sandeep Patil35403eb2017-02-08 20:27:12 -08001214 if (!tab) {
Sandeep Patilc20c0c22017-02-23 16:09:34 -08001215 LOG(ERROR) << "Early mount failed to read fstab from device tree";
Sandeep Patilfc86f242017-02-09 19:19:31 -08001216 return false;
Sandeep Patil35403eb2017-02-08 20:27:12 -08001217 }
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +08001218
Sandeep Patil35403eb2017-02-08 20:27:12 -08001219 // find out fstab records for odm, system and vendor
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001220 std::vector<fstab_rec*> early_fstab_recs;
1221 for (auto mount_point : {"/odm", "/system", "/vendor"}) {
1222 fstab_rec* fstab_rec = fs_mgr_get_entry_for_mount_point(tab.get(), mount_point);
1223 if (fstab_rec != nullptr) {
1224 early_fstab_recs.push_back(fstab_rec);
1225 }
Sandeep Patil35403eb2017-02-08 20:27:12 -08001226 }
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +08001227
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001228 // nothing to early mount
1229 if (early_fstab_recs.empty()) return true;
1230
1231 bool need_verity;
Bowgo Tsai51c02722017-04-06 21:01:40 +08001232 std::string device_file_by_name_prefix;
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001233 std::set<std::string> partition_names;
1234 // partition_names MUST have A/B suffix when A/B is used
Bowgo Tsai51c02722017-04-06 21:01:40 +08001235 if (!get_early_partitions(early_fstab_recs, &partition_names, &need_verity,
1236 &device_file_by_name_prefix)) {
Sandeep Patil05ff38b2017-02-16 17:04:11 -08001237 return false;
1238 }
1239
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001240 bool success = false;
Sandeep Patil35403eb2017-02-08 20:27:12 -08001241 // create the devices we need..
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001242 early_device_init(&partition_names);
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +08001243
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001244 // early_device_init will remove found partitions from partition_names
1245 // So if the partition_names is not empty here, means some partitions
1246 // are not found
1247 if (!partition_names.empty()) {
1248 LOG(ERROR) << "early_mount: partition(s) not found: "
1249 << android::base::Join(partition_names, ", ");
1250 goto done;
1251 }
Sandeep Patil35403eb2017-02-08 20:27:12 -08001252
Sandeep Patil0a3e36f2017-02-15 15:45:01 -08001253 if (need_verity) {
1254 // create /dev/device mapper
1255 device_init("/sys/devices/virtual/misc/device-mapper",
1256 [&](uevent* uevent) -> coldboot_action_t { return COLDBOOT_STOP; });
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +08001257 }
Sandeep Patil35403eb2017-02-08 20:27:12 -08001258
Bowgo Tsai51c02722017-04-06 21:01:40 +08001259 if (mount_early_partitions(early_fstab_recs, device_file_by_name_prefix)) {
1260 success = true;
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001261 }
Sandeep Patil35403eb2017-02-08 20:27:12 -08001262
Sandeep Patil0a3e36f2017-02-15 15:45:01 -08001263done:
Sandeep Patil35403eb2017-02-08 20:27:12 -08001264 device_close();
Sandeep Patil0a3e36f2017-02-15 15:45:01 -08001265 return success;
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +08001266}
1267
Tom Cherry663fdfc2017-03-10 14:46:38 -08001268static void install_reboot_signal_handlers() {
1269 // Instead of panic'ing the kernel as is the default behavior when init crashes,
1270 // we prefer to reboot to bootloader on development builds, as this will prevent
1271 // boot looping bad configurations and allow both developers and test farms to easily
1272 // recover.
1273 struct sigaction action;
1274 memset(&action, 0, sizeof(action));
1275 sigfillset(&action.sa_mask);
1276 action.sa_handler = [](int) {
1277 // panic() reboots to bootloader
1278 panic();
1279 };
1280 action.sa_flags = SA_RESTART;
1281 sigaction(SIGABRT, &action, nullptr);
1282 sigaction(SIGBUS, &action, nullptr);
1283 sigaction(SIGFPE, &action, nullptr);
1284 sigaction(SIGILL, &action, nullptr);
1285 sigaction(SIGSEGV, &action, nullptr);
1286#if defined(SIGSTKFLT)
1287 sigaction(SIGSTKFLT, &action, nullptr);
1288#endif
1289 sigaction(SIGSYS, &action, nullptr);
1290 sigaction(SIGTRAP, &action, nullptr);
1291}
1292
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001293int main(int argc, char** argv) {
Elliott Hughesda40c002015-03-27 23:20:44 -07001294 if (!strcmp(basename(argv[0]), "ueventd")) {
Colin Crossf83d0b92010-04-21 12:04:20 -07001295 return ueventd_main(argc, argv);
Elliott Hughesda40c002015-03-27 23:20:44 -07001296 }
Colin Crossf83d0b92010-04-21 12:04:20 -07001297
Elliott Hughesda40c002015-03-27 23:20:44 -07001298 if (!strcmp(basename(argv[0]), "watchdogd")) {
Arve Hjønnevågd97d9072012-06-13 21:51:56 -07001299 return watchdogd_main(argc, argv);
Elliott Hughesda40c002015-03-27 23:20:44 -07001300 }
Arve Hjønnevågd97d9072012-06-13 21:51:56 -07001301
Tom Cherry663fdfc2017-03-10 14:46:38 -08001302 if (REBOOT_BOOTLOADER_ON_PANIC) {
1303 install_reboot_signal_handlers();
1304 }
1305
Elliott Hughescc86fb22015-03-17 20:01:13 -07001306 add_environment("PATH", _PATH_DEFPATH);
1307
Elliott Hughes9605a942016-11-10 17:43:47 -08001308 bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);
Nick Kralevich9dec93b2015-04-25 15:50:03 -07001309
Nick Kralevich9dec93b2015-04-25 15:50:03 -07001310 if (is_first_stage) {
Tom Cherry34e70412017-03-16 18:08:56 -07001311 boot_clock::time_point start_time = boot_clock::now();
1312
1313 // Clear the umask.
1314 umask(0);
1315
1316 // Get the basic filesystem setup we need put together in the initramdisk
1317 // on / and then we'll let the rc file figure out the rest.
Nick Kralevichf667a322015-04-25 17:42:52 -07001318 mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
1319 mkdir("/dev/pts", 0755);
1320 mkdir("/dev/socket", 0755);
1321 mount("devpts", "/dev/pts", "devpts", 0, NULL);
Nick Kralevichc39ba5a2015-11-07 16:52:17 -08001322 #define MAKE_STR(x) __STRING(x)
1323 mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
Tom Cherry34e70412017-03-16 18:08:56 -07001324 // Don't expose the raw commandline to unprivileged processes.
1325 chmod("/proc/cmdline", 0440);
Nick Kralevich80960d22016-10-29 12:20:00 -07001326 gid_t groups[] = { AID_READPROC };
1327 setgroups(arraysize(groups), groups);
Nick Kralevich9dec93b2015-04-25 15:50:03 -07001328 mount("sysfs", "/sys", "sysfs", 0, NULL);
Nick Kralevich3d9e2732016-03-03 10:40:12 -08001329 mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL);
Elliott Hughes35f5d042016-07-26 09:32:33 -07001330 mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11));
Evgenii Stepanov102daa32016-11-18 14:58:40 -08001331 mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8));
1332 mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9));
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001333
Tom Cherry34e70412017-03-16 18:08:56 -07001334 // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually
1335 // talk to the outside world...
1336 InitKernelLogging(argv);
Elliott Hughesda40c002015-03-27 23:20:44 -07001337
Tom Cherry34e70412017-03-16 18:08:56 -07001338 LOG(INFO) << "init first stage started!";
Elliott Hughesda40c002015-03-27 23:20:44 -07001339
Sandeep Patil35403eb2017-02-08 20:27:12 -08001340 if (!early_mount()) {
1341 LOG(ERROR) << "Failed to mount required partitions early ...";
1342 panic();
1343 }
Wei Wang313b3522016-10-28 12:22:32 -07001344
Elliott Hughes9605a942016-11-10 17:43:47 -08001345 // Set up SELinux, loading the SELinux policy.
Wei Wang313b3522016-10-28 12:22:32 -07001346 selinux_initialize(true);
1347
Elliott Hughes9605a942016-11-10 17:43:47 -08001348 // We're in the kernel domain, so re-exec init to transition to the init domain now
Wei Wang313b3522016-10-28 12:22:32 -07001349 // that the SELinux policy has been loaded.
Wei Wang313b3522016-10-28 12:22:32 -07001350 if (restorecon("/init") == -1) {
1351 PLOG(ERROR) << "restorecon failed";
1352 security_failure();
1353 }
Elliott Hughes9605a942016-11-10 17:43:47 -08001354
1355 setenv("INIT_SECOND_STAGE", "true", 1);
1356
James Hawkins27c05222017-01-26 11:55:44 -08001357 static constexpr uint32_t kNanosecondsPerMillisecond = 1e6;
1358 uint64_t start_ms = start_time.time_since_epoch().count() / kNanosecondsPerMillisecond;
1359 setenv("INIT_STARTED_AT", StringPrintf("%" PRIu64, start_ms).c_str(), 1);
Elliott Hughes9605a942016-11-10 17:43:47 -08001360
Wei Wang313b3522016-10-28 12:22:32 -07001361 char* path = argv[0];
Elliott Hughes9605a942016-11-10 17:43:47 -08001362 char* args[] = { path, nullptr };
Tom Cherry34e70412017-03-16 18:08:56 -07001363 execv(path, args);
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -07001364
Tom Cherry34e70412017-03-16 18:08:56 -07001365 // execv() only returns if an error happened, in which case we
1366 // panic and never fall through this conditional.
1367 PLOG(ERROR) << "execv(\"" << path << "\") failed";
1368 security_failure();
Elliott Hughesf65730e2015-04-24 18:38:17 +00001369 }
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001370
Tom Cherry34e70412017-03-16 18:08:56 -07001371 // At this point we're in the second stage of init.
1372 InitKernelLogging(argv);
1373 LOG(INFO) << "init second stage started!";
1374
1375 // Indicate that booting is in progress to background fw loaders, etc.
1376 close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
1377
1378 property_init();
1379
1380 // If arguments are passed both on the command line and in DT,
1381 // properties set in DT always have priority over the command-line ones.
1382 process_kernel_dt();
1383 process_kernel_cmdline();
1384
1385 // Propagate the kernel variables to internal variables
1386 // used by init as well as the current required properties.
1387 export_kernel_boot_props();
1388
1389 // Make the time that init started available for bootstat to log.
1390 property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
1391 property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
1392
1393 // Set libavb version for Framework-only OTA match in Treble build.
Bowgo Tsai45180122017-04-13 21:17:48 +08001394 const char* avb_version = getenv("INIT_AVB_VERSION");
1395 if (avb_version) property_set("ro.boot.avb_version", avb_version);
Tom Cherry34e70412017-03-16 18:08:56 -07001396
1397 // Clean up our environment.
1398 unsetenv("INIT_SECOND_STAGE");
1399 unsetenv("INIT_STARTED_AT");
1400 unsetenv("INIT_SELINUX_TOOK");
Bowgo Tsai45180122017-04-13 21:17:48 +08001401 unsetenv("INIT_AVB_VERSION");
Tom Cherry34e70412017-03-16 18:08:56 -07001402
1403 // Now set up SELinux for second stage.
1404 selinux_initialize(false);
Sandeep Patil74df5ba2017-03-29 10:31:26 -07001405 selinux_restore_context();
Stephen Smalleye46f9d52012-01-13 08:48:47 -05001406
Elliott Hughes929f4072015-04-24 21:13:44 -07001407 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
1408 if (epoll_fd == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001409 PLOG(ERROR) << "epoll_create1 failed";
Elliott Hughes929f4072015-04-24 21:13:44 -07001410 exit(1);
1411 }
1412
1413 signal_handler_init();
Elliott Hughes9042cae2015-04-24 17:43:21 -07001414
Riley Andrewse4b7b292014-06-16 15:06:21 -07001415 property_load_boot_defaults();
Sami Tolvanen9e9efca2015-12-07 12:33:58 +00001416 export_oem_lock_status();
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001417 start_property_service();
Amit Pundird2e74db2016-06-29 19:00:00 +05301418 set_usb_controller();
Dima Zavind7634c92011-12-16 14:18:06 -08001419
Tom Cherryb7349902015-08-26 11:43:36 -07001420 const BuiltinFunctionMap function_map;
1421 Action::set_function_map(&function_map);
1422
1423 Parser& parser = Parser::GetInstance();
1424 parser.AddSectionParser("service",std::make_unique<ServiceParser>());
1425 parser.AddSectionParser("on", std::make_unique<ActionParser>());
1426 parser.AddSectionParser("import", std::make_unique<ImportParser>());
Tom Cherrye2490972017-03-28 16:40:41 -07001427 std::string bootscript = GetProperty("ro.boot.init_rc", "");
Hung-ying Tyan959aeb12017-01-18 09:39:36 +08001428 if (bootscript.empty()) {
1429 parser.ParseConfig("/init.rc");
Jaekyun Seok4ec72cc2017-02-22 20:37:57 +09001430 parser.set_is_system_etc_init_loaded(
1431 parser.ParseConfig("/system/etc/init"));
1432 parser.set_is_vendor_etc_init_loaded(
1433 parser.ParseConfig("/vendor/etc/init"));
1434 parser.set_is_odm_etc_init_loaded(parser.ParseConfig("/odm/etc/init"));
Hung-ying Tyan959aeb12017-01-18 09:39:36 +08001435 } else {
1436 parser.ParseConfig(bootscript);
Jaekyun Seok4ec72cc2017-02-22 20:37:57 +09001437 parser.set_is_system_etc_init_loaded(true);
1438 parser.set_is_vendor_etc_init_loaded(true);
1439 parser.set_is_odm_etc_init_loaded(true);
Hung-ying Tyan959aeb12017-01-18 09:39:36 +08001440 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001441
Tom Cherryd8a72572017-03-13 12:24:49 -07001442 // Turning this on and letting the INFO logging be discarded adds 0.2s to
1443 // Nexus 9 boot time, so it's disabled by default.
1444 if (false) parser.DumpState();
1445
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001446 ActionManager& am = ActionManager::GetInstance();
1447
1448 am.QueueEventTrigger("early-init");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001449
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001450 // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001451 am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001452 // ... so that we can start queuing up actions that require stuff from /dev.
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001453 am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
Daniel Cashmanbaccc402016-03-25 23:49:05 +00001454 am.QueueBuiltinAction(set_mmap_rnd_bits_action, "set_mmap_rnd_bits");
Dave Weinstein44f7e4f2017-01-19 18:03:34 -08001455 am.QueueBuiltinAction(set_kptr_restrict_action, "set_kptr_restrict");
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001456 am.QueueBuiltinAction(keychord_init_action, "keychord_init");
1457 am.QueueBuiltinAction(console_init_action, "console_init");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001458
Elliott Hughesda40c002015-03-27 23:20:44 -07001459 // Trigger all the boot actions to get us started.
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001460 am.QueueEventTrigger("init");
Dima Zavinca47cef2011-08-24 15:28:23 -07001461
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001462 // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
1463 // wasn't ready immediately after wait_for_coldboot_done
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001464 am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001465
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001466 // Don't mount filesystems or start core system services in charger mode.
Tom Cherrye2490972017-03-28 16:40:41 -07001467 std::string bootmode = GetProperty("ro.bootmode", "");
Yabin Cui74edcea2015-07-24 10:11:05 -07001468 if (bootmode == "charger") {
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001469 am.QueueEventTrigger("charger");
Dima Zavinca47cef2011-08-24 15:28:23 -07001470 } else {
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001471 am.QueueEventTrigger("late-init");
Dima Zavinca47cef2011-08-24 15:28:23 -07001472 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001473
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001474 // Run all property triggers based on current state of the properties.
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001475 am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001476
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001477 while (true) {
Elliott Hughes9605a942016-11-10 17:43:47 -08001478 // By default, sleep until something happens.
1479 int epoll_timeout_ms = -1;
1480
Tom Cherry2d804672017-03-27 16:27:30 -07001481 if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) {
Tom Cherry77ddcd52017-03-23 16:54:38 -07001482 am.ExecuteOneCommand();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001483 }
Tom Cherry2d804672017-03-27 16:27:30 -07001484 if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) {
Tom Cherry77ddcd52017-03-23 16:54:38 -07001485 restart_processes();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001486
Tom Cherry77ddcd52017-03-23 16:54:38 -07001487 // If there's a process that needs restarting, wake up in time for that.
1488 if (process_needs_restart_at != 0) {
1489 epoll_timeout_ms = (process_needs_restart_at - time(nullptr)) * 1000;
1490 if (epoll_timeout_ms < 0) epoll_timeout_ms = 0;
1491 }
1492
1493 // If there's more work to do, wake up again immediately.
1494 if (am.HasMoreCommands()) epoll_timeout_ms = 0;
1495 }
Wei Wang16db4342016-11-30 15:43:42 -08001496
Elliott Hughes929f4072015-04-24 21:13:44 -07001497 epoll_event ev;
Elliott Hughes9605a942016-11-10 17:43:47 -08001498 int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms));
Elliott Hughes929f4072015-04-24 21:13:44 -07001499 if (nr == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001500 PLOG(ERROR) << "epoll_wait failed";
Elliott Hughes929f4072015-04-24 21:13:44 -07001501 } else if (nr == 1) {
1502 ((void (*)()) ev.data.ptr)();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001503 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001504 }
1505
1506 return 0;
1507}