blob: 2f728ea7af1581ec73225c11422315b4eef7134d [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 Cherrybac32992015-07-31 12:45:25 -070067#include "service.h"
Colin Cross9c5366b2010-04-13 19:48:59 -070068#include "signal_handler.h"
Colin Crossf83d0b92010-04-21 12:04:20 -070069#include "ueventd.h"
Tom Cherrybac32992015-07-31 12:45:25 -070070#include "util.h"
Arve Hjønnevågd97d9072012-06-13 21:51:56 -070071#include "watchdogd.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070072
Tom Cherrye2490972017-03-28 16:40:41 -070073using android::base::GetProperty;
Elliott Hughes9605a942016-11-10 17:43:47 -080074using android::base::StringPrintf;
75
Stephen Smalleye46f9d52012-01-13 08:48:47 -050076struct selabel_handle *sehandle;
rpcraig63207cd2012-08-09 10:05:49 -040077struct selabel_handle *sehandle_prop;
Stephen Smalleye46f9d52012-01-13 08:48:47 -050078
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070079static int property_triggers_enabled = 0;
80
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070081static char qemu[32];
82
Viorel Suman70daa672016-03-21 10:08:07 +020083std::string default_console = "/dev/console";
Elliott Hughes9605a942016-11-10 17:43:47 -080084static time_t process_needs_restart_at;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070085
Tom Cherrybac32992015-07-31 12:45:25 -070086const char *ENV[32];
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070087
Elliott Hughes929f4072015-04-24 21:13:44 -070088static int epoll_fd = -1;
89
Wei Wang132ac312017-01-25 16:27:03 -080090static std::unique_ptr<Timer> waiting_for_prop(nullptr);
91static std::string wait_prop_name;
92static std::string wait_prop_value;
93
Elliott Hughes929f4072015-04-24 21:13:44 -070094void register_epoll_handler(int fd, void (*fn)()) {
95 epoll_event ev;
96 ev.events = EPOLLIN;
97 ev.data.ptr = reinterpret_cast<void*>(fn);
98 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -070099 PLOG(ERROR) << "epoll_ctl failed";
Elliott Hughes929f4072015-04-24 21:13:44 -0700100 }
101}
102
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700103/* add_environment - add "key=value" to the current environment */
104int add_environment(const char *key, const char *val)
105{
James Morrissey381341f2014-05-16 11:36:36 +0100106 size_t n;
107 size_t key_len = strlen(key);
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -0700108
James Morrissey381341f2014-05-16 11:36:36 +0100109 /* The last environment entry is reserved to terminate the list */
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700110 for (n = 0; n < (arraysize(ENV) - 1); n++) {
James Morrissey381341f2014-05-16 11:36:36 +0100111
112 /* Delete any existing entry for this key */
113 if (ENV[n] != NULL) {
114 size_t entry_key_len = strcspn(ENV[n], "=");
115 if ((entry_key_len == key_len) && (strncmp(ENV[n], key, entry_key_len) == 0)) {
116 free((char*)ENV[n]);
117 ENV[n] = NULL;
118 }
119 }
120
121 /* Add entry if a free slot is available */
122 if (ENV[n] == NULL) {
Elliott Hughesf3cf4382015-02-03 17:12:07 -0800123 char* entry;
124 asprintf(&entry, "%s=%s", key, val);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700125 ENV[n] = entry;
126 return 0;
127 }
128 }
129
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700130 LOG(ERROR) << "No env. room to store: '" << key << "':'" << val << "'";
James Morrissey381341f2014-05-16 11:36:36 +0100131
132 return -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700133}
134
Wei Wang2d0fdaa2017-02-02 10:52:39 -0800135bool start_waiting_for_property(const char *name, const char *value)
Wei Wang132ac312017-01-25 16:27:03 -0800136{
137 if (waiting_for_prop) {
138 return false;
139 }
Tom Cherrye2490972017-03-28 16:40:41 -0700140 if (GetProperty(name, "") != value) {
Wei Wang132ac312017-01-25 16:27:03 -0800141 // Current property value is not equal to expected value
142 wait_prop_name = name;
143 wait_prop_value = value;
144 waiting_for_prop.reset(new Timer());
145 } else {
Wei Wang2d0fdaa2017-02-02 10:52:39 -0800146 LOG(INFO) << "start_waiting_for_property(\""
147 << name << "\", \"" << value << "\"): already set";
Wei Wang132ac312017-01-25 16:27:03 -0800148 }
149 return true;
150}
151
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700152void property_changed(const char *name, const char *value)
153{
Colin Crossebc6ff12010-04-13 19:52:01 -0700154 if (property_triggers_enabled)
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700155 ActionManager::GetInstance().QueuePropertyTrigger(name, value);
Wei Wang132ac312017-01-25 16:27:03 -0800156 if (waiting_for_prop) {
157 if (wait_prop_name == name && wait_prop_value == value) {
158 wait_prop_name.clear();
159 wait_prop_value.clear();
160 LOG(INFO) << "Wait for property took " << *waiting_for_prop;
161 waiting_for_prop.reset();
162 }
163 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700164}
165
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700166static void restart_processes()
167{
Elliott Hughes9605a942016-11-10 17:43:47 -0800168 process_needs_restart_at = 0;
169 ServiceManager::GetInstance().ForEachServiceWithFlags(SVC_RESTARTING, [](Service* s) {
170 s->RestartIfNeeded(&process_needs_restart_at);
171 });
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700172}
173
Elliott Hughesbdeac392016-04-12 15:38:27 -0700174void handle_control_message(const std::string& msg, const std::string& name) {
Tom Cherrybac32992015-07-31 12:45:25 -0700175 Service* svc = ServiceManager::GetInstance().FindServiceByName(name);
Elliott Hughesbdeac392016-04-12 15:38:27 -0700176 if (svc == nullptr) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700177 LOG(ERROR) << "no such service '" << name << "'";
Elliott Hughesbdeac392016-04-12 15:38:27 -0700178 return;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700179 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700180
Tom Cherrybac32992015-07-31 12:45:25 -0700181 if (msg == "start") {
Elliott Hughesbdeac392016-04-12 15:38:27 -0700182 svc->Start();
Tom Cherrybac32992015-07-31 12:45:25 -0700183 } else if (msg == "stop") {
Elliott Hughesbdeac392016-04-12 15:38:27 -0700184 svc->Stop();
Tom Cherrybac32992015-07-31 12:45:25 -0700185 } else if (msg == "restart") {
Elliott Hughesbdeac392016-04-12 15:38:27 -0700186 svc->Restart();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700187 } else {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700188 LOG(ERROR) << "unknown control msg '" << msg << "'";
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700189 }
190}
191
Tom Cherry96f67312015-07-30 13:52:55 -0700192static int wait_for_coldboot_done_action(const std::vector<std::string>& args) {
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700193 Timer t;
194
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700195 LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE "...";
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000196
197 // Historically we had a 1s timeout here because we weren't otherwise
198 // tracking boot time, and many OEMs made their sepolicy regular
199 // expressions too expensive (http://b/19899875).
200
201 // Now we're tracking boot time, just log the time taken to a system
202 // property. We still panic if it takes more than a minute though,
203 // because any build that slow isn't likely to boot at all, and we'd
204 // rather any test lab devices fail back to the bootloader.
205 if (wait_for_file(COLDBOOT_DONE, 60s) < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700206 LOG(ERROR) << "Timed out waiting for " COLDBOOT_DONE;
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000207 panic();
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700208 }
209
James Hawkins27c05222017-01-26 11:55:44 -0800210 property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration_ms()).c_str());
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700211 return 0;
Colin Crossebc6ff12010-04-13 19:52:01 -0700212}
213
Alex Klyubin0d872d82013-08-16 13:19:24 -0700214/*
215 * Writes 512 bytes of output from Hardware RNG (/dev/hw_random, backed
216 * by Linux kernel's hw_random framework) into Linux RNG's via /dev/urandom.
217 * Does nothing if Hardware RNG is not present.
218 *
219 * Since we don't yet trust the quality of Hardware RNG, these bytes are not
220 * mixed into the primary pool of Linux RNG and the entropy estimate is left
221 * unmodified.
222 *
223 * If the HW RNG device /dev/hw_random is present, we require that at least
224 * 512 bytes read from it are written into Linux RNG. QA is expected to catch
225 * devices/configurations where these I/O operations are blocking for a long
226 * time. We do not reboot or halt on failures, as this is a best-effort
227 * attempt.
228 */
Tom Cherry96f67312015-07-30 13:52:55 -0700229static int mix_hwrng_into_linux_rng_action(const std::vector<std::string>& args)
Alex Klyubin0d872d82013-08-16 13:19:24 -0700230{
231 int result = -1;
232 int hwrandom_fd = -1;
233 int urandom_fd = -1;
234 char buf[512];
235 ssize_t chunk_size;
236 size_t total_bytes_written = 0;
237
238 hwrandom_fd = TEMP_FAILURE_RETRY(
Nick Kralevich45a884f2015-02-02 14:37:22 -0800239 open("/dev/hw_random", O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
Alex Klyubin0d872d82013-08-16 13:19:24 -0700240 if (hwrandom_fd == -1) {
241 if (errno == ENOENT) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700242 LOG(ERROR) << "/dev/hw_random not found";
243 // It's not an error to not have a Hardware RNG.
244 result = 0;
Alex Klyubin0d872d82013-08-16 13:19:24 -0700245 } else {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700246 PLOG(ERROR) << "Failed to open /dev/hw_random";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700247 }
248 goto ret;
249 }
250
251 urandom_fd = TEMP_FAILURE_RETRY(
Nick Kralevich45a884f2015-02-02 14:37:22 -0800252 open("/dev/urandom", O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Alex Klyubin0d872d82013-08-16 13:19:24 -0700253 if (urandom_fd == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700254 PLOG(ERROR) << "Failed to open /dev/urandom";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700255 goto ret;
256 }
257
258 while (total_bytes_written < sizeof(buf)) {
259 chunk_size = TEMP_FAILURE_RETRY(
260 read(hwrandom_fd, buf, sizeof(buf) - total_bytes_written));
261 if (chunk_size == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700262 PLOG(ERROR) << "Failed to read from /dev/hw_random";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700263 goto ret;
264 } else if (chunk_size == 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700265 LOG(ERROR) << "Failed to read from /dev/hw_random: EOF";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700266 goto ret;
267 }
268
269 chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size));
270 if (chunk_size == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700271 PLOG(ERROR) << "Failed to write to /dev/urandom";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700272 goto ret;
273 }
274 total_bytes_written += chunk_size;
275 }
276
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700277 LOG(INFO) << "Mixed " << total_bytes_written << " bytes from /dev/hw_random into /dev/urandom";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700278 result = 0;
279
280ret:
281 if (hwrandom_fd != -1) {
282 close(hwrandom_fd);
283 }
284 if (urandom_fd != -1) {
285 close(urandom_fd);
286 }
Alex Klyubin0d872d82013-08-16 13:19:24 -0700287 return result;
288}
289
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000290static void security_failure() {
291 LOG(ERROR) << "Security failure...";
292 panic();
293}
294
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800295static bool set_highest_available_option_value(std::string path, int min, int max)
296{
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000297 std::ifstream inf(path, std::fstream::in);
298 if (!inf) {
299 LOG(ERROR) << "Cannot open for reading: " << path;
300 return false;
301 }
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800302
303 int current = max;
304 while (current >= min) {
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000305 // try to write out new value
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800306 std::string str_val = std::to_string(current);
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000307 std::ofstream of(path, std::fstream::out);
308 if (!of) {
309 LOG(ERROR) << "Cannot open for writing: " << path;
310 return false;
311 }
312 of << str_val << std::endl;
313 of.close();
314
315 // check to make sure it was recorded
316 inf.seekg(0);
317 std::string str_rec;
318 inf >> str_rec;
319 if (str_val.compare(str_rec) == 0) {
320 break;
321 }
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800322 current--;
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000323 }
324 inf.close();
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800325
326 if (current < min) {
327 LOG(ERROR) << "Unable to set minimum option value " << min << " in " << path;
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000328 return false;
329 }
330 return true;
331}
332
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800333#define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits"
334#define MMAP_RND_COMPAT_PATH "/proc/sys/vm/mmap_rnd_compat_bits"
335
336/* __attribute__((unused)) due to lack of mips support: see mips block
337 * in set_mmap_rnd_bits_action */
338static bool __attribute__((unused)) set_mmap_rnd_bits_min(int start, int min, bool compat) {
339 std::string path;
340 if (compat) {
341 path = MMAP_RND_COMPAT_PATH;
342 } else {
343 path = MMAP_RND_PATH;
344 }
345
346 return set_highest_available_option_value(path, min, start);
347}
348
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000349/*
350 * Set /proc/sys/vm/mmap_rnd_bits and potentially
351 * /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values.
352 * Returns -1 if unable to set these to an acceptable value.
353 *
354 * To support this sysctl, the following upstream commits are needed:
355 *
356 * d07e22597d1d mm: mmap: add new /proc tunable for mmap_base ASLR
357 * e0c25d958f78 arm: mm: support ARCH_MMAP_RND_BITS
358 * 8f0d3aa9de57 arm64: mm: support ARCH_MMAP_RND_BITS
359 * 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS
360 * ec9ee4acd97c drivers: char: random: add get_random_long()
361 * 5ef11c35ce86 mm: ASLR: use get_random_long()
362 */
363static int set_mmap_rnd_bits_action(const std::vector<std::string>& args)
364{
365 int ret = -1;
366
367 /* values are arch-dependent */
368#if defined(__aarch64__)
369 /* arm64 supports 18 - 33 bits depending on pagesize and VA_SIZE */
370 if (set_mmap_rnd_bits_min(33, 24, false)
371 && set_mmap_rnd_bits_min(16, 16, true)) {
372 ret = 0;
373 }
374#elif defined(__x86_64__)
375 /* x86_64 supports 28 - 32 bits */
376 if (set_mmap_rnd_bits_min(32, 32, false)
377 && set_mmap_rnd_bits_min(16, 16, true)) {
378 ret = 0;
379 }
380#elif defined(__arm__) || defined(__i386__)
381 /* check to see if we're running on 64-bit kernel */
382 bool h64 = !access(MMAP_RND_COMPAT_PATH, F_OK);
383 /* supported 32-bit architecture must have 16 bits set */
384 if (set_mmap_rnd_bits_min(16, 16, h64)) {
385 ret = 0;
386 }
387#elif defined(__mips__) || defined(__mips64__)
388 // TODO: add mips support b/27788820
389 ret = 0;
390#else
dcashman41d0b6d2016-12-14 08:37:11 -0800391 LOG(ERROR) << "Unknown architecture";
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000392#endif
393
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000394 if (ret == -1) {
395 LOG(ERROR) << "Unable to set adequate mmap entropy value!";
396 security_failure();
397 }
398 return ret;
399}
400
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800401#define KPTR_RESTRICT_PATH "/proc/sys/kernel/kptr_restrict"
402#define KPTR_RESTRICT_MINVALUE 2
403#define KPTR_RESTRICT_MAXVALUE 4
404
405/* Set kptr_restrict to the highest available level.
406 *
407 * Aborts if unable to set this to an acceptable value.
408 */
409static int set_kptr_restrict_action(const std::vector<std::string>& args)
410{
411 std::string path = KPTR_RESTRICT_PATH;
412
413 if (!set_highest_available_option_value(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
414 LOG(ERROR) << "Unable to set adequate kptr_restrict value!";
415 security_failure();
416 }
417 return 0;
418}
419
Tom Cherry96f67312015-07-30 13:52:55 -0700420static int keychord_init_action(const std::vector<std::string>& args)
Colin Crossebc6ff12010-04-13 19:52:01 -0700421{
422 keychord_init();
423 return 0;
424}
425
Tom Cherry96f67312015-07-30 13:52:55 -0700426static int console_init_action(const std::vector<std::string>& args)
Colin Crossebc6ff12010-04-13 19:52:01 -0700427{
Tom Cherrye2490972017-03-28 16:40:41 -0700428 std::string console = GetProperty("ro.boot.console", "");
Viorel Sumanefc72752016-03-21 10:23:43 +0200429 if (!console.empty()) {
Viorel Suman70daa672016-03-21 10:08:07 +0200430 default_console = "/dev/" + console;
Colin Crossebc6ff12010-04-13 19:52:01 -0700431 }
Colin Crossebc6ff12010-04-13 19:52:01 -0700432 return 0;
433}
434
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700435static void import_kernel_nv(const std::string& key, const std::string& value, bool for_emulator) {
436 if (key.empty()) return;
Dima Zavin5511c842011-12-19 11:21:32 -0800437
438 if (for_emulator) {
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700439 // In the emulator, export any kernel option with the "ro.kernel." prefix.
Elliott Hughes9605a942016-11-10 17:43:47 -0800440 property_set(StringPrintf("ro.kernel.%s", key.c_str()).c_str(), value.c_str());
Dima Zavin5511c842011-12-19 11:21:32 -0800441 return;
442 }
443
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700444 if (key == "qemu") {
445 strlcpy(qemu, value.c_str(), sizeof(qemu));
446 } else if (android::base::StartsWith(key, "androidboot.")) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800447 property_set(StringPrintf("ro.boot.%s", key.c_str() + 12).c_str(), value.c_str());
Dima Zavin5511c842011-12-19 11:21:32 -0800448 }
449}
450
Sami Tolvanen9e9efca2015-12-07 12:33:58 +0000451static void export_oem_lock_status() {
Tom Cherrye2490972017-03-28 16:40:41 -0700452 if (!android::base::GetBoolProperty("ro.oem_unlock_supported", false)) {
Sami Tolvanen9e9efca2015-12-07 12:33:58 +0000453 return;
454 }
455
Tom Cherrye2490972017-03-28 16:40:41 -0700456 std::string value = GetProperty("ro.boot.verifiedbootstate", "");
Sami Tolvanen9e9efca2015-12-07 12:33:58 +0000457
458 if (!value.empty()) {
459 property_set("ro.boot.flash.locked", value == "orange" ? "0" : "1");
460 }
461}
462
Elliott Hughesd679bc92015-03-20 08:50:46 -0700463static void export_kernel_boot_props() {
Dima Zavin5511c842011-12-19 11:21:32 -0800464 struct {
465 const char *src_prop;
Elliott Hughesd679bc92015-03-20 08:50:46 -0700466 const char *dst_prop;
467 const char *default_value;
Dima Zavin5511c842011-12-19 11:21:32 -0800468 } prop_map[] = {
Elliott Hughesd679bc92015-03-20 08:50:46 -0700469 { "ro.boot.serialno", "ro.serialno", "", },
470 { "ro.boot.mode", "ro.bootmode", "unknown", },
471 { "ro.boot.baseband", "ro.baseband", "unknown", },
Dima Zavin5511c842011-12-19 11:21:32 -0800472 { "ro.boot.bootloader", "ro.bootloader", "unknown", },
Elliott Hughesd679bc92015-03-20 08:50:46 -0700473 { "ro.boot.hardware", "ro.hardware", "unknown", },
474 { "ro.boot.revision", "ro.revision", "0", },
Dima Zavin5511c842011-12-19 11:21:32 -0800475 };
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700476 for (size_t i = 0; i < arraysize(prop_map); i++) {
Tom Cherrye2490972017-03-28 16:40:41 -0700477 std::string value = GetProperty(prop_map[i].src_prop, "");
Yabin Cui74edcea2015-07-24 10:11:05 -0700478 property_set(prop_map[i].dst_prop, (!value.empty()) ? value.c_str() : prop_map[i].default_value);
Dima Zavin5511c842011-12-19 11:21:32 -0800479 }
Dima Zavin5511c842011-12-19 11:21:32 -0800480}
Colin Crossebc6ff12010-04-13 19:52:01 -0700481
Bowgo Tsai51c02722017-04-06 21:01:40 +0800482/* Reads the content of device tree file into dt_value.
483 * Returns true if the read is success, false otherwise.
484 */
485static bool read_dt_file(const std::string& file_name, std::string* dt_value) {
486 if (android::base::ReadFileToString(file_name, dt_value)) {
487 if (!dt_value->empty()) {
488 dt_value->pop_back(); // Trim the trailing '\0' out.
Sandeep Patilc20c0c22017-02-23 16:09:34 -0800489 return true;
490 }
Rom Lemarchand6a524432015-02-28 06:39:11 -0800491 }
Sandeep Patilc20c0c22017-02-23 16:09:34 -0800492 return false;
Sandeep Patilfc86f242017-02-09 19:19:31 -0800493}
494
Bowgo Tsai51c02722017-04-06 21:01:40 +0800495static const std::string kAndroidDtDir("/proc/device-tree/firmware/android/");
Sandeep Patilfc86f242017-02-09 19:19:31 -0800496
Bowgo Tsai51c02722017-04-06 21:01:40 +0800497static bool is_dt_value_expected(const std::string& dt_file_suffix,
498 const std::string& expected_value) {
499 std::string dt_value;
500 std::string file_name = kAndroidDtDir + dt_file_suffix;
501
502 if (read_dt_file(file_name, &dt_value)) {
503 if (dt_value == expected_value) {
Sandeep Patilc20c0c22017-02-23 16:09:34 -0800504 return true;
505 }
Sandeep Patilfc86f242017-02-09 19:19:31 -0800506 }
Sandeep Patilc20c0c22017-02-23 16:09:34 -0800507 return false;
Sandeep Patilfc86f242017-02-09 19:19:31 -0800508}
509
Bowgo Tsai51c02722017-04-06 21:01:40 +0800510static inline bool is_dt_compatible() {
511 return is_dt_value_expected("compatible", "android,firmware");
512}
513
514static inline bool is_dt_fstab_compatible() {
515 return is_dt_value_expected("fstab/compatible", "android,fstab");
516}
517
518static inline bool is_dt_vbmeta_compatible() {
519 return is_dt_value_expected("vbmeta/compatible", "android,vbmeta");
520}
521
522// Gets the vbmeta config from device tree. Specifically, the 'parts' and 'by_name_prefix'.
523// /{
524// firmware {
525// android {
526// vbmeta {
527// compatible = "android,vbmeta";
528// parts = "vbmeta,boot,system,vendor"
529// by_name_prefix="/dev/block/platform/soc.0/f9824900.sdhci/by-name/"
530// };
531// };
532// };
533// }
534static bool get_vbmeta_config_from_dt(std::string* vbmeta_partitions,
535 std::string* device_file_by_name_prefix) {
536 std::string file_name = kAndroidDtDir + "vbmeta/parts";
537 if (!read_dt_file(file_name, vbmeta_partitions)) return false;
538
539 file_name = kAndroidDtDir + "vbmeta/by_name_prefix";
540 if (!read_dt_file(file_name, device_file_by_name_prefix)) return false;
541
542 return true;
543}
544
Sandeep Patilfc86f242017-02-09 19:19:31 -0800545static void process_kernel_dt() {
546 if (!is_dt_compatible()) return;
547
Bowgo Tsai51c02722017-04-06 21:01:40 +0800548 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(kAndroidDtDir.c_str()), closedir);
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700549 if (!dir) return;
Rom Lemarchand6a524432015-02-28 06:39:11 -0800550
Sandeep Patilfc86f242017-02-09 19:19:31 -0800551 std::string dt_file;
Rom Lemarchand6a524432015-02-28 06:39:11 -0800552 struct dirent *dp;
553 while ((dp = readdir(dir.get())) != NULL) {
Rom Lemarchand1dcf3252015-11-08 17:51:50 -0800554 if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") || !strcmp(dp->d_name, "name")) {
Rom Lemarchand6a524432015-02-28 06:39:11 -0800555 continue;
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700556 }
Rom Lemarchand6a524432015-02-28 06:39:11 -0800557
Bowgo Tsai51c02722017-04-06 21:01:40 +0800558 std::string file_name = kAndroidDtDir + dp->d_name;
Rom Lemarchand6a524432015-02-28 06:39:11 -0800559
560 android::base::ReadFileToString(file_name, &dt_file);
561 std::replace(dt_file.begin(), dt_file.end(), ',', '.');
562
Elliott Hughes9605a942016-11-10 17:43:47 -0800563 std::string property_name = StringPrintf("ro.boot.%s", dp->d_name);
Elliott Hughesdb3f2672015-03-20 09:45:18 -0700564 property_set(property_name.c_str(), dt_file.c_str());
Rom Lemarchand6a524432015-02-28 06:39:11 -0800565 }
566}
567
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700568static void process_kernel_cmdline() {
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700569 // The first pass does the common stuff, and finds if we are in qemu.
570 // The second pass is only necessary for qemu to export all kernel params
571 // as properties.
Nick Kralevichf667a322015-04-25 17:42:52 -0700572 import_kernel_cmdline(false, import_kernel_nv);
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700573 if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv);
Colin Crossebc6ff12010-04-13 19:52:01 -0700574}
575
caozhiyuanb104c502016-11-26 21:14:07 +0800576static int property_enable_triggers_action(const std::vector<std::string>& args)
577{
578 /* Enable property triggers. */
579 property_triggers_enabled = 1;
580 return 0;
581}
582
Tom Cherry96f67312015-07-30 13:52:55 -0700583static int queue_property_triggers_action(const std::vector<std::string>& args)
Colin Crossebc6ff12010-04-13 19:52:01 -0700584{
caozhiyuanb104c502016-11-26 21:14:07 +0800585 ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700586 ActionManager::GetInstance().QueueAllPropertyTriggers();
Colin Crossebc6ff12010-04-13 19:52:01 -0700587 return 0;
588}
589
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700590static void selinux_init_all_handles(void)
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500591{
Stephen Smalleyae6f3d72012-05-01 15:02:53 -0400592 sehandle = selinux_android_file_context_handle();
Stephen Smalleydbd37f22014-01-28 10:34:09 -0500593 selinux_android_set_sehandle(sehandle);
rpcraig63207cd2012-08-09 10:05:49 -0400594 sehandle_prop = selinux_android_prop_context_handle();
Stephen Smalleyae6f3d72012-05-01 15:02:53 -0400595}
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500596
Nick Kralevichd34e4072015-04-28 12:39:41 -0700597enum selinux_enforcing_status { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
Nick Kralevichf667a322015-04-25 17:42:52 -0700598
599static selinux_enforcing_status selinux_status_from_cmdline() {
600 selinux_enforcing_status status = SELINUX_ENFORCING;
601
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700602 import_kernel_cmdline(false, [&](const std::string& key, const std::string& value, bool in_qemu) {
603 if (key == "androidboot.selinux" && value == "permissive") {
604 status = SELINUX_PERMISSIVE;
Nick Kralevichf667a322015-04-25 17:42:52 -0700605 }
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700606 });
Nick Kralevichf667a322015-04-25 17:42:52 -0700607
608 return status;
609}
610
Nick Kralevich935bd3e2013-06-26 15:37:26 -0700611static bool selinux_is_enforcing(void)
612{
Nick Kralevichd34e4072015-04-28 12:39:41 -0700613 if (ALLOW_PERMISSIVE_SELINUX) {
Nick Kralevichf667a322015-04-25 17:42:52 -0700614 return selinux_status_from_cmdline() == SELINUX_ENFORCING;
Nick Kralevich935bd3e2013-06-26 15:37:26 -0700615 }
Nick Kralevich935bd3e2013-06-26 15:37:26 -0700616 return true;
617}
618
Elliott Hughesda40c002015-03-27 23:20:44 -0700619static int audit_callback(void *data, security_class_t /*cls*/, char *buf, size_t len) {
William Robertsd7aea442015-10-01 16:03:47 -0700620
621 property_audit_data *d = reinterpret_cast<property_audit_data*>(data);
622
623 if (!d || !d->name || !d->cr) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700624 LOG(ERROR) << "audit_callback invoked with null data arguments!";
William Robertsd7aea442015-10-01 16:03:47 -0700625 return 0;
626 }
627
628 snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name,
629 d->cr->pid, d->cr->uid, d->cr->gid);
rpcraig63207cd2012-08-09 10:05:49 -0400630 return 0;
631}
632
Alex Klyubin16696e22017-02-28 12:32:20 -0800633/*
634 * Forks, executes the provided program in the child, and waits for the completion in the parent.
Alex Klyubin11850502017-03-05 14:28:27 -0800635 * Child's stderr is captured and logged using LOG(ERROR).
Alex Klyubin16696e22017-02-28 12:32:20 -0800636 *
637 * Returns true if the child exited with status code 0, returns false otherwise.
638 */
639static bool fork_execve_and_wait_for_completion(const char* filename, char* const argv[],
640 char* const envp[]) {
Alex Klyubin11850502017-03-05 14:28:27 -0800641 // Create a pipe used for redirecting child process's output.
642 // * pipe_fds[0] is the FD the parent will use for reading.
643 // * pipe_fds[1] is the FD the child will use for writing.
644 int pipe_fds[2];
645 if (pipe(pipe_fds) == -1) {
646 PLOG(ERROR) << "Failed to create pipe";
647 return false;
648 }
649
Alex Klyubin16696e22017-02-28 12:32:20 -0800650 pid_t child_pid = fork();
651 if (child_pid == -1) {
652 PLOG(ERROR) << "Failed to fork for " << filename;
653 return false;
654 }
655
656 if (child_pid == 0) {
657 // fork succeeded -- this is executing in the child process
Alex Klyubin11850502017-03-05 14:28:27 -0800658
659 // Close the pipe FD not used by this process
660 TEMP_FAILURE_RETRY(close(pipe_fds[0]));
661
662 // Redirect stderr to the pipe FD provided by the parent
663 if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
664 PLOG(ERROR) << "Failed to redirect stderr of " << filename;
665 _exit(127);
666 return false;
667 }
668 TEMP_FAILURE_RETRY(close(pipe_fds[1]));
669
Alex Klyubin16696e22017-02-28 12:32:20 -0800670 if (execve(filename, argv, envp) == -1) {
671 PLOG(ERROR) << "Failed to execve " << filename;
672 return false;
673 }
674 // Unreachable because execve will have succeeded and replaced this code
675 // with child process's code.
676 _exit(127);
677 return false;
678 } else {
679 // fork succeeded -- this is executing in the original/parent process
Alex Klyubin11850502017-03-05 14:28:27 -0800680
681 // Close the pipe FD not used by this process
682 TEMP_FAILURE_RETRY(close(pipe_fds[1]));
683
684 // Log the redirected output of the child process.
685 // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
686 // As a result, we're buffering all output and logging it in one go at the end of the
687 // invocation, instead of logging it as it comes in.
688 const int child_out_fd = pipe_fds[0];
689 std::string child_output;
690 if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
691 PLOG(ERROR) << "Failed to capture full output of " << filename;
692 }
693 TEMP_FAILURE_RETRY(close(child_out_fd));
694 if (!child_output.empty()) {
695 // Log captured output, line by line, because LOG expects to be invoked for each line
696 std::istringstream in(child_output);
697 std::string line;
698 while (std::getline(in, line)) {
699 LOG(ERROR) << filename << ": " << line;
700 }
701 }
702
703 // Wait for child to terminate
Alex Klyubin16696e22017-02-28 12:32:20 -0800704 int status;
705 if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
706 PLOG(ERROR) << "Failed to wait for " << filename;
707 return false;
708 }
709
710 if (WIFEXITED(status)) {
711 int status_code = WEXITSTATUS(status);
712 if (status_code == 0) {
713 return true;
714 } else {
715 LOG(ERROR) << filename << " exited with status " << status_code;
716 }
717 } else if (WIFSIGNALED(status)) {
718 LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
719 } else if (WIFSTOPPED(status)) {
720 LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
721 } else {
722 LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
723 }
724
725 return false;
726 }
727}
728
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800729static bool read_first_line(const char* file, std::string* line) {
730 line->clear();
731
732 std::string contents;
733 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
734 return false;
735 }
736 std::istringstream in(contents);
737 std::getline(in, *line);
738 return true;
739}
740
741static bool selinux_find_precompiled_split_policy(std::string* file) {
742 file->clear();
743
744 static constexpr const char precompiled_sepolicy[] = "/vendor/etc/selinux/precompiled_sepolicy";
745 if (access(precompiled_sepolicy, R_OK) == -1) {
746 return false;
747 }
748 std::string actual_plat_id;
Dan Cashman39ffec72017-04-06 09:51:23 -0700749 if (!read_first_line("/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256",
750 &actual_plat_id)) {
751 PLOG(INFO) << "Failed to read "
752 "/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256";
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800753 return false;
754 }
755 std::string precompiled_plat_id;
Dan Cashman39ffec72017-04-06 09:51:23 -0700756 if (!read_first_line("/vendor/etc/selinux/precompiled_sepolicy.plat_and_mapping.sha256",
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800757 &precompiled_plat_id)) {
Dan Cashman39ffec72017-04-06 09:51:23 -0700758 PLOG(INFO) << "Failed to read "
759 "/vendor/etc/selinux/"
760 "precompiled_sepolicy.plat_and_mapping.sha256";
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800761 return false;
762 }
763 if ((actual_plat_id.empty()) || (actual_plat_id != precompiled_plat_id)) {
764 return false;
765 }
766
767 *file = precompiled_sepolicy;
768 return true;
769}
770
Dan Cashman692c3e42017-04-10 12:20:01 -0700771static bool selinux_get_vendor_mapping_version(std::string* plat_vers) {
772 if (!read_first_line("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
773 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
774 return false;
775 }
776 if (plat_vers->empty()) {
777 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
778 return false;
779 }
780 return true;
781}
782
Alex Klyubinc2a4c9a2017-03-02 12:43:10 -0800783static constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
Alex Klyubin16696e22017-02-28 12:32:20 -0800784
785static bool selinux_is_split_policy_device() { return access(plat_policy_cil_file, R_OK) != -1; }
786
787/*
788 * Loads SELinux policy split across platform/system and non-platform/vendor files.
789 *
790 * Returns true upon success, false otherwise (failure cause is logged).
791 */
792static bool selinux_load_split_policy() {
793 // IMPLEMENTATION NOTE: Split policy consists of three CIL files:
794 // * platform -- policy needed due to logic contained in the system image,
795 // * non-platform -- policy needed due to logic contained in the vendor image,
796 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
797 // with newer versions of platform policy.
798 //
799 // secilc is invoked to compile the above three policy files into a single monolithic policy
800 // file. This file is then loaded into the kernel.
801
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800802 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
803 // must match the platform policy on the system image.
804 std::string precompiled_sepolicy_file;
805 if (selinux_find_precompiled_split_policy(&precompiled_sepolicy_file)) {
806 android::base::unique_fd fd(
807 open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
808 if (fd != -1) {
809 if (selinux_android_load_policy_from_fd(fd, precompiled_sepolicy_file.c_str()) < 0) {
810 LOG(ERROR) << "Failed to load SELinux policy from " << precompiled_sepolicy_file;
811 return false;
812 }
813 return true;
814 }
815 }
816 // No suitable precompiled policy could be loaded
817
Alex Klyubin16696e22017-02-28 12:32:20 -0800818 LOG(INFO) << "Compiling SELinux policy";
819
Alex Klyubina71dfec2017-03-09 10:56:58 -0800820 // Determine the highest policy language version supported by the kernel
821 set_selinuxmnt("/sys/fs/selinux");
822 int max_policy_version = security_policyvers();
823 if (max_policy_version == -1) {
824 PLOG(ERROR) << "Failed to determine highest policy version supported by kernel";
825 return false;
826 }
827
Alex Klyubin16696e22017-02-28 12:32:20 -0800828 // We store the output of the compilation on /dev because this is the most convenient tmpfs
829 // storage mount available this early in the boot sequence.
830 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
831 android::base::unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
832 if (compiled_sepolicy_fd < 0) {
833 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
834 return false;
835 }
836
Dan Cashman692c3e42017-04-10 12:20:01 -0700837 // Determine which mapping file to include
838 std::string vend_plat_vers;
839 if (!selinux_get_vendor_mapping_version(&vend_plat_vers)) {
840 return false;
841 }
842 std::string mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
Alex Klyubina71dfec2017-03-09 10:56:58 -0800843 // clang-format off
844 const char* compile_args[] = {
845 "/system/bin/secilc",
846 plat_policy_cil_file,
Jeff Vander Stoepd2782532017-04-12 16:44:26 -0700847 "-M", "true", "-G",
Alex Klyubina71dfec2017-03-09 10:56:58 -0800848 // Target the highest policy language version supported by the kernel
849 "-c", std::to_string(max_policy_version).c_str(),
Dan Cashman692c3e42017-04-10 12:20:01 -0700850 mapping_file.c_str(),
Alex Klyubina71dfec2017-03-09 10:56:58 -0800851 "/vendor/etc/selinux/nonplat_sepolicy.cil",
852 "-o", compiled_sepolicy,
853 // We don't care about file_contexts output by the compiler
854 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
855 nullptr};
856 // clang-format on
Alex Klyubin16696e22017-02-28 12:32:20 -0800857
858 if (!fork_execve_and_wait_for_completion(compile_args[0], (char**)compile_args, (char**)ENV)) {
859 unlink(compiled_sepolicy);
860 return false;
861 }
862 unlink(compiled_sepolicy);
863
864 LOG(INFO) << "Loading compiled SELinux policy";
865 if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) {
866 LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy;
867 return false;
868 }
869
870 return true;
871}
872
873/*
874 * Loads SELinux policy from a monolithic file.
875 *
876 * Returns true upon success, false otherwise (failure cause is logged).
877 */
878static bool selinux_load_monolithic_policy() {
879 LOG(VERBOSE) << "Loading SELinux policy from monolithic file";
880 if (selinux_android_load_policy() < 0) {
881 PLOG(ERROR) << "Failed to load monolithic SELinux policy";
882 return false;
883 }
884 return true;
885}
886
887/*
888 * Loads SELinux policy into the kernel.
889 *
890 * Returns true upon success, false otherwise (failure cause is logged).
891 */
892static bool selinux_load_policy() {
893 return selinux_is_split_policy_device() ? selinux_load_split_policy()
894 : selinux_load_monolithic_policy();
895}
896
Elliott Hughesf65730e2015-04-24 18:38:17 +0000897static void selinux_initialize(bool in_kernel_domain) {
Elliott Hughesda40c002015-03-27 23:20:44 -0700898 Timer t;
Stephen Smalleyeb3f4212014-02-12 16:17:00 -0500899
Elliott Hughesda40c002015-03-27 23:20:44 -0700900 selinux_callback cb;
901 cb.func_log = selinux_klog_callback;
902 selinux_set_callback(SELINUX_CB_LOG, cb);
903 cb.func_audit = audit_callback;
904 selinux_set_callback(SELINUX_CB_AUDIT, cb);
905
Elliott Hughesf65730e2015-04-24 18:38:17 +0000906 if (in_kernel_domain) {
Alex Klyubin16696e22017-02-28 12:32:20 -0800907 LOG(INFO) << "Loading SELinux policy";
908 if (!selinux_load_policy()) {
909 panic();
Elliott Hughesf65730e2015-04-24 18:38:17 +0000910 }
911
Nick Kralevichd34e4072015-04-28 12:39:41 -0700912 bool kernel_enforcing = (security_getenforce() == 1);
Elliott Hughesf65730e2015-04-24 18:38:17 +0000913 bool is_enforcing = selinux_is_enforcing();
Nick Kralevichd34e4072015-04-28 12:39:41 -0700914 if (kernel_enforcing != is_enforcing) {
915 if (security_setenforce(is_enforcing)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700916 PLOG(ERROR) << "security_setenforce(%s) failed" << (is_enforcing ? "true" : "false");
Nick Kralevichd34e4072015-04-28 12:39:41 -0700917 security_failure();
918 }
919 }
Elliott Hughesf65730e2015-04-24 18:38:17 +0000920
Jorge Lucangeli Obes77f0e9f2016-12-28 14:07:02 -0500921 if (!write_file("/sys/fs/selinux/checkreqprot", "0")) {
Nick Kralevicheedbe812015-04-25 14:10:03 -0700922 security_failure();
923 }
924
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000925 // init's first stage can't set properties, so pass the time to the second stage.
James Hawkins27c05222017-01-26 11:55:44 -0800926 setenv("INIT_SELINUX_TOOK", std::to_string(t.duration_ms()).c_str(), 1);
Elliott Hughesf65730e2015-04-24 18:38:17 +0000927 } else {
928 selinux_init_all_handles();
Nick Kralevich56fa0ac2013-06-24 17:41:40 -0700929 }
Nick Kralevich56fa0ac2013-06-24 17:41:40 -0700930}
931
Sandeep Patil74df5ba2017-03-29 10:31:26 -0700932// The files and directories that were created before initial sepolicy load
933// need to have their security context restored to the proper value.
934// This must happen before /dev is populated by ueventd.
935static void selinux_restore_context() {
936 LOG(INFO) << "Running restorecon...";
937 restorecon("/dev");
938 restorecon("/dev/kmsg");
939 restorecon("/dev/socket");
940 restorecon("/dev/random");
941 restorecon("/dev/urandom");
942 restorecon("/dev/__properties__");
Sandeep Patilf5b99d42017-03-29 10:33:41 -0700943
944 restorecon("/file_contexts.bin");
945 restorecon("/plat_file_contexts");
946 restorecon("/nonplat_file_contexts");
Sandeep Patil74df5ba2017-03-29 10:31:26 -0700947 restorecon("/plat_property_contexts");
948 restorecon("/nonplat_property_contexts");
Sandeep Patilf5b99d42017-03-29 10:33:41 -0700949 restorecon("/plat_seapp_contexts");
950 restorecon("/nonplat_seapp_contexts");
951 restorecon("/plat_service_contexts");
952 restorecon("/nonplat_service_contexts");
Martijn Coenen68872732017-04-12 18:02:33 -0700953 restorecon("/plat_hwservice_contexts");
954 restorecon("/nonplat_hwservice_contexts");
Sandeep Patilf5b99d42017-03-29 10:33:41 -0700955 restorecon("/sepolicy");
Martijn Coenen7c1e0d82017-04-03 11:08:20 -0700956 restorecon("/vndservice_contexts");
Sandeep Patilf5b99d42017-03-29 10:33:41 -0700957
Sandeep Patil74df5ba2017-03-29 10:31:26 -0700958 restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE);
959 restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
960 restorecon("/dev/device-mapper");
961}
962
Amit Pundird2e74db2016-06-29 19:00:00 +0530963// Set the UDC controller for the ConfigFS USB Gadgets.
964// Read the UDC controller in use from "/sys/class/udc".
965// In case of multiple UDC controllers select the first one.
966static void set_usb_controller() {
967 std::unique_ptr<DIR, decltype(&closedir)>dir(opendir("/sys/class/udc"), closedir);
968 if (!dir) return;
969
970 dirent* dp;
971 while ((dp = readdir(dir.get())) != nullptr) {
972 if (dp->d_name[0] == '.') continue;
973
974 property_set("sys.usb.controller", dp->d_name);
975 break;
976 }
977}
978
Bowgo Tsai51c02722017-04-06 21:01:40 +0800979// Creates "/dev/block/dm-XX" for dm-verity by running coldboot on /sys/block/dm-XX.
980static void device_init_dm_device(const std::string& dm_device) {
981 const std::string device_name(basename(dm_device.c_str()));
982 const std::string syspath = "/sys/block/" + device_name;
983
984 device_init(syspath.c_str(), [&](uevent* uevent) -> coldboot_action_t {
985 if (uevent->device_name && device_name == uevent->device_name) {
986 LOG(VERBOSE) << "early_mount: creating dm-verity device : " << dm_device;
987 return COLDBOOT_STOP;
988 }
989 return COLDBOOT_CONTINUE;
990 });
991 device_close();
992}
993
994static bool vboot_1_0_mount_partitions(const std::vector<fstab_rec*>& fstab_recs) {
995 if (fstab_recs.empty()) return false;
996
997 for (auto rec : fstab_recs) {
998 bool need_create_dm_device = false;
999 if (fs_mgr_is_verified(rec)) {
1000 // setup verity and create the dm-XX block device
1001 // needed to mount this partition
1002 int ret = fs_mgr_setup_verity(rec, false /* wait_for_verity_dev */);
1003 if (ret == FS_MGR_SETUP_VERITY_DISABLED) {
1004 LOG(INFO) << "verity disabled for '" << rec->mount_point << "'";
1005 } else if (ret == FS_MGR_SETUP_VERITY_SUCCESS) {
1006 need_create_dm_device = true;
1007 } else {
1008 PLOG(ERROR) << "early_mount: failed to setup verity for '" << rec->mount_point
1009 << "'";
1010 return false;
1011 }
1012 }
1013 if (need_create_dm_device) {
1014 // The exact block device name (rec->blk_device) is changed to "/dev/block/dm-XX".
1015 // Need to create it because ueventd isn't started during early mount.
1016 device_init_dm_device(rec->blk_device);
1017 }
1018 if (fs_mgr_do_mount_one(rec)) {
1019 PLOG(ERROR) << "early_mount: failed to mount '" << rec->mount_point << "'";
Sandeep Patil0a3e36f2017-02-15 15:45:01 -08001020 return false;
1021 }
Sandeep Patil0a3e36f2017-02-15 15:45:01 -08001022 }
1023
1024 return true;
1025}
1026
Bowgo Tsai51c02722017-04-06 21:01:40 +08001027static bool vboot_2_0_mount_partitions(const std::vector<fstab_rec*>& fstab_recs,
1028 const std::string& device_file_by_name_prefix) {
1029 if (fstab_recs.empty()) return false;
1030
1031 FsManagerAvbUniquePtr avb_handle = FsManagerAvbHandle::Open(device_file_by_name_prefix);
1032 if (!avb_handle) {
1033 LOG(INFO) << "Failed to Open FsManagerAvbHandle";
1034 return false;
1035 }
1036
Bowgo Tsai45180122017-04-13 21:17:48 +08001037 setenv("INIT_AVB_VERSION", avb_handle->avb_version().c_str(), 1);
Bowgo Tsai51c02722017-04-06 21:01:40 +08001038 for (auto rec : fstab_recs) {
1039 bool need_create_dm_device = false;
1040 if (fs_mgr_is_avb(rec)) {
Bowgo Tsai45180122017-04-13 21:17:48 +08001041 if (avb_handle->hashtree_disabled()) {
Bowgo Tsai51c02722017-04-06 21:01:40 +08001042 LOG(INFO) << "avb hashtree disabled for '" << rec->mount_point << "'";
1043 } else if (avb_handle->SetUpAvb(rec, false /* wait_for_verity_dev */)) {
1044 need_create_dm_device = true;
1045 } else {
1046 PLOG(ERROR) << "early_mount: failed to set up AVB on partition: '"
1047 << rec->mount_point << "'";
1048 return false;
1049 }
1050 }
1051 if (need_create_dm_device) {
1052 // The exact block device name (rec->blk_device) is changed to "/dev/block/dm-XX".
1053 // Need to create it because ueventd isn't started during early mount.
1054 device_init_dm_device(rec->blk_device);
1055 }
1056 if (fs_mgr_do_mount_one(rec)) {
1057 PLOG(ERROR) << "early_mount: failed to mount '" << rec->mount_point << "'";
1058 return false;
1059 }
1060 }
1061
1062 return true;
1063}
1064
1065static bool mount_early_partitions(const std::vector<fstab_rec*>& fstab_recs,
1066 const std::string& device_file_by_name_prefix) {
1067 if (is_dt_vbmeta_compatible()) { // AVB (external/avb) is used to setup dm-verity.
1068 return vboot_2_0_mount_partitions(fstab_recs, device_file_by_name_prefix);
1069 } else {
1070 return vboot_1_0_mount_partitions(fstab_recs);
1071 }
1072}
1073
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001074// Creates devices with uevent->partition_name matching one in the in/out
1075// partition_names. Note that the partition_names MUST have A/B suffix
1076// when A/B is used. Found partitions will then be removed from the
1077// partition_names for caller to check which devices are NOT created.
1078static void early_device_init(std::set<std::string>* partition_names) {
1079 if (partition_names->empty()) {
1080 return;
1081 }
1082 device_init(nullptr, [=](uevent* uevent) -> coldboot_action_t {
1083 if (!strncmp(uevent->subsystem, "firmware", 8)) {
1084 return COLDBOOT_CONTINUE;
1085 }
1086
1087 // we need platform devices to create symlinks
1088 if (!strncmp(uevent->subsystem, "platform", 8)) {
1089 return COLDBOOT_CREATE;
1090 }
1091
1092 // Ignore everything that is not a block device
1093 if (strncmp(uevent->subsystem, "block", 5)) {
1094 return COLDBOOT_CONTINUE;
1095 }
1096
1097 if (uevent->partition_name) {
1098 // match partition names to create device nodes for partitions
1099 // both partition_names and uevent->partition_name have A/B suffix when A/B is used
1100 auto iter = partition_names->find(uevent->partition_name);
1101 if (iter != partition_names->end()) {
1102 LOG(VERBOSE) << "early_mount: found partition: " << *iter;
1103 partition_names->erase(iter);
1104 if (partition_names->empty()) {
1105 return COLDBOOT_STOP; // found all partitions, stop coldboot
1106 } else {
1107 return COLDBOOT_CREATE; // create this device and continue to find others
1108 }
1109 }
1110 }
1111 // Not found a partition or find an unneeded partition, continue to find others
1112 return COLDBOOT_CONTINUE;
1113 });
1114}
1115
Bowgo Tsai51c02722017-04-06 21:01:40 +08001116static bool vboot_1_0_early_partitions(const std::vector<fstab_rec*>& early_fstab_recs,
1117 std::set<std::string>* out_partitions,
1118 bool* out_need_verity) {
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001119 std::string meta_partition;
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001120 for (auto fstab_rec : early_fstab_recs) {
1121 // don't allow verifyatboot for early mounted partitions
1122 if (fs_mgr_is_verifyatboot(fstab_rec)) {
1123 LOG(ERROR) << "early_mount: partitions can't be verified at boot";
1124 return false;
1125 }
1126 // check for verified partitions
1127 if (fs_mgr_is_verified(fstab_rec)) {
1128 *out_need_verity = true;
1129 }
1130 // check if verity metadata is on a separate partition and get partition
1131 // name from the end of the ->verity_loc path. verity state is not partition
1132 // specific, so there must be only 1 additional partition that carries
1133 // verity state.
1134 if (fstab_rec->verity_loc) {
1135 if (!meta_partition.empty()) {
1136 LOG(ERROR) << "early_mount: more than one meta partition found: " << meta_partition
1137 << ", " << basename(fstab_rec->verity_loc);
1138 return false;
1139 } else {
1140 meta_partition = basename(fstab_rec->verity_loc);
1141 }
1142 }
1143 }
1144
1145 // includes those early mount partitions and meta_partition (if any)
1146 // note that fstab_rec->blk_device has A/B suffix updated by fs_mgr when A/B is used
1147 for (auto fstab_rec : early_fstab_recs) {
1148 out_partitions->emplace(basename(fstab_rec->blk_device));
1149 }
1150
1151 if (!meta_partition.empty()) {
1152 out_partitions->emplace(std::move(meta_partition));
1153 }
1154
1155 return true;
1156}
1157
Bowgo Tsai51c02722017-04-06 21:01:40 +08001158// a.k.a. AVB (external/avb)
1159static bool vboot_2_0_early_partitions(std::set<std::string>* out_partitions, bool* out_need_verity,
1160 std::string* out_device_file_by_name_prefix) {
1161 std::string vbmeta_partitions;
1162 if (!get_vbmeta_config_from_dt(&vbmeta_partitions, out_device_file_by_name_prefix)) {
1163 return false;
1164 }
1165 // libavb verifies AVB metadata on all verified partitions at once.
1166 // e.g., The vbmeta_partitions will be "vbmeta,boot,system,vendor"
1167 // for libavb to verify metadata, even if we only need to early mount /vendor.
1168 std::vector<std::string> partitions = android::base::Split(vbmeta_partitions, ",");
1169 std::string ab_suffix = fs_mgr_get_slot_suffix();
1170 for (const auto& partition : partitions) {
1171 out_partitions->emplace(partition + ab_suffix);
1172 }
1173 *out_need_verity = true;
1174 return true;
1175}
1176
1177static bool get_early_partitions(const std::vector<fstab_rec*>& early_fstab_recs,
1178 std::set<std::string>* out_partitions, bool* out_need_verity,
1179 std::string* out_device_file_by_name_prefix) {
1180 *out_need_verity = false;
1181 out_partitions->clear();
1182 out_device_file_by_name_prefix->clear();
1183
1184 if (is_dt_vbmeta_compatible()) { // AVB (external/avb) is used to setup dm-verity.
1185 return vboot_2_0_early_partitions(out_partitions, out_need_verity,
1186 out_device_file_by_name_prefix);
1187 } else {
1188 return vboot_1_0_early_partitions(early_fstab_recs, out_partitions, out_need_verity);
1189 }
1190}
1191
Sandeep Patilfc86f242017-02-09 19:19:31 -08001192/* Early mount vendor and ODM partitions. The fstab is read from device-tree. */
Sandeep Patil35403eb2017-02-08 20:27:12 -08001193static bool early_mount() {
Bowgo Tsai32232722017-03-01 18:24:46 +08001194 // skip early mount if we're in recovery mode
1195 if (access("/sbin/recovery", F_OK) == 0) {
1196 LOG(INFO) << "Early mount skipped (recovery mode)";
1197 return true;
1198 }
1199
Sandeep Patilc20c0c22017-02-23 16:09:34 -08001200 // first check if device tree fstab entries are compatible
1201 if (!is_dt_fstab_compatible()) {
1202 LOG(INFO) << "Early mount skipped (missing/incompatible fstab in device tree)";
Sandeep Patil35403eb2017-02-08 20:27:12 -08001203 return true;
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +08001204 }
Sandeep Patil35403eb2017-02-08 20:27:12 -08001205
Sandeep Patilc20c0c22017-02-23 16:09:34 -08001206 std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> tab(
1207 fs_mgr_read_fstab_dt(), fs_mgr_free_fstab);
Sandeep Patil35403eb2017-02-08 20:27:12 -08001208 if (!tab) {
Sandeep Patilc20c0c22017-02-23 16:09:34 -08001209 LOG(ERROR) << "Early mount failed to read fstab from device tree";
Sandeep Patilfc86f242017-02-09 19:19:31 -08001210 return false;
Sandeep Patil35403eb2017-02-08 20:27:12 -08001211 }
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +08001212
Sandeep Patil35403eb2017-02-08 20:27:12 -08001213 // find out fstab records for odm, system and vendor
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001214 std::vector<fstab_rec*> early_fstab_recs;
1215 for (auto mount_point : {"/odm", "/system", "/vendor"}) {
1216 fstab_rec* fstab_rec = fs_mgr_get_entry_for_mount_point(tab.get(), mount_point);
1217 if (fstab_rec != nullptr) {
1218 early_fstab_recs.push_back(fstab_rec);
1219 }
Sandeep Patil35403eb2017-02-08 20:27:12 -08001220 }
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +08001221
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001222 // nothing to early mount
1223 if (early_fstab_recs.empty()) return true;
1224
1225 bool need_verity;
Bowgo Tsai51c02722017-04-06 21:01:40 +08001226 std::string device_file_by_name_prefix;
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001227 std::set<std::string> partition_names;
1228 // partition_names MUST have A/B suffix when A/B is used
Bowgo Tsai51c02722017-04-06 21:01:40 +08001229 if (!get_early_partitions(early_fstab_recs, &partition_names, &need_verity,
1230 &device_file_by_name_prefix)) {
Sandeep Patil05ff38b2017-02-16 17:04:11 -08001231 return false;
1232 }
1233
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001234 bool success = false;
Sandeep Patil35403eb2017-02-08 20:27:12 -08001235 // create the devices we need..
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001236 early_device_init(&partition_names);
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +08001237
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001238 // early_device_init will remove found partitions from partition_names
1239 // So if the partition_names is not empty here, means some partitions
1240 // are not found
1241 if (!partition_names.empty()) {
1242 LOG(ERROR) << "early_mount: partition(s) not found: "
1243 << android::base::Join(partition_names, ", ");
1244 goto done;
1245 }
Sandeep Patil35403eb2017-02-08 20:27:12 -08001246
Sandeep Patil0a3e36f2017-02-15 15:45:01 -08001247 if (need_verity) {
1248 // create /dev/device mapper
1249 device_init("/sys/devices/virtual/misc/device-mapper",
1250 [&](uevent* uevent) -> coldboot_action_t { return COLDBOOT_STOP; });
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +08001251 }
Sandeep Patil35403eb2017-02-08 20:27:12 -08001252
Bowgo Tsai51c02722017-04-06 21:01:40 +08001253 if (mount_early_partitions(early_fstab_recs, device_file_by_name_prefix)) {
1254 success = true;
Bowgo Tsaid4beed22017-02-18 18:33:13 +08001255 }
Sandeep Patil35403eb2017-02-08 20:27:12 -08001256
Sandeep Patil0a3e36f2017-02-15 15:45:01 -08001257done:
Sandeep Patil35403eb2017-02-08 20:27:12 -08001258 device_close();
Sandeep Patil0a3e36f2017-02-15 15:45:01 -08001259 return success;
Hung-ying Tyan99c4a8a2016-02-01 15:07:40 +08001260}
1261
Tom Cherry663fdfc2017-03-10 14:46:38 -08001262static void install_reboot_signal_handlers() {
1263 // Instead of panic'ing the kernel as is the default behavior when init crashes,
1264 // we prefer to reboot to bootloader on development builds, as this will prevent
1265 // boot looping bad configurations and allow both developers and test farms to easily
1266 // recover.
1267 struct sigaction action;
1268 memset(&action, 0, sizeof(action));
1269 sigfillset(&action.sa_mask);
1270 action.sa_handler = [](int) {
1271 // panic() reboots to bootloader
1272 panic();
1273 };
1274 action.sa_flags = SA_RESTART;
1275 sigaction(SIGABRT, &action, nullptr);
1276 sigaction(SIGBUS, &action, nullptr);
1277 sigaction(SIGFPE, &action, nullptr);
1278 sigaction(SIGILL, &action, nullptr);
1279 sigaction(SIGSEGV, &action, nullptr);
1280#if defined(SIGSTKFLT)
1281 sigaction(SIGSTKFLT, &action, nullptr);
1282#endif
1283 sigaction(SIGSYS, &action, nullptr);
1284 sigaction(SIGTRAP, &action, nullptr);
1285}
1286
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001287int main(int argc, char** argv) {
Elliott Hughesda40c002015-03-27 23:20:44 -07001288 if (!strcmp(basename(argv[0]), "ueventd")) {
Colin Crossf83d0b92010-04-21 12:04:20 -07001289 return ueventd_main(argc, argv);
Elliott Hughesda40c002015-03-27 23:20:44 -07001290 }
Colin Crossf83d0b92010-04-21 12:04:20 -07001291
Elliott Hughesda40c002015-03-27 23:20:44 -07001292 if (!strcmp(basename(argv[0]), "watchdogd")) {
Arve Hjønnevågd97d9072012-06-13 21:51:56 -07001293 return watchdogd_main(argc, argv);
Elliott Hughesda40c002015-03-27 23:20:44 -07001294 }
Arve Hjønnevågd97d9072012-06-13 21:51:56 -07001295
Tom Cherry663fdfc2017-03-10 14:46:38 -08001296 if (REBOOT_BOOTLOADER_ON_PANIC) {
1297 install_reboot_signal_handlers();
1298 }
1299
Elliott Hughescc86fb22015-03-17 20:01:13 -07001300 add_environment("PATH", _PATH_DEFPATH);
1301
Elliott Hughes9605a942016-11-10 17:43:47 -08001302 bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);
Nick Kralevich9dec93b2015-04-25 15:50:03 -07001303
Nick Kralevich9dec93b2015-04-25 15:50:03 -07001304 if (is_first_stage) {
Tom Cherry34e70412017-03-16 18:08:56 -07001305 boot_clock::time_point start_time = boot_clock::now();
1306
1307 // Clear the umask.
1308 umask(0);
1309
1310 // Get the basic filesystem setup we need put together in the initramdisk
1311 // on / and then we'll let the rc file figure out the rest.
Nick Kralevichf667a322015-04-25 17:42:52 -07001312 mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
1313 mkdir("/dev/pts", 0755);
1314 mkdir("/dev/socket", 0755);
1315 mount("devpts", "/dev/pts", "devpts", 0, NULL);
Nick Kralevichc39ba5a2015-11-07 16:52:17 -08001316 #define MAKE_STR(x) __STRING(x)
1317 mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
Tom Cherry34e70412017-03-16 18:08:56 -07001318 // Don't expose the raw commandline to unprivileged processes.
1319 chmod("/proc/cmdline", 0440);
Nick Kralevich80960d22016-10-29 12:20:00 -07001320 gid_t groups[] = { AID_READPROC };
1321 setgroups(arraysize(groups), groups);
Nick Kralevich9dec93b2015-04-25 15:50:03 -07001322 mount("sysfs", "/sys", "sysfs", 0, NULL);
Nick Kralevich3d9e2732016-03-03 10:40:12 -08001323 mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL);
Elliott Hughes35f5d042016-07-26 09:32:33 -07001324 mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11));
Evgenii Stepanov102daa32016-11-18 14:58:40 -08001325 mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8));
1326 mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9));
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001327
Tom Cherry34e70412017-03-16 18:08:56 -07001328 // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually
1329 // talk to the outside world...
1330 InitKernelLogging(argv);
Elliott Hughesda40c002015-03-27 23:20:44 -07001331
Tom Cherry34e70412017-03-16 18:08:56 -07001332 LOG(INFO) << "init first stage started!";
Elliott Hughesda40c002015-03-27 23:20:44 -07001333
Sandeep Patil35403eb2017-02-08 20:27:12 -08001334 if (!early_mount()) {
1335 LOG(ERROR) << "Failed to mount required partitions early ...";
1336 panic();
1337 }
Wei Wang313b3522016-10-28 12:22:32 -07001338
Elliott Hughes9605a942016-11-10 17:43:47 -08001339 // Set up SELinux, loading the SELinux policy.
Wei Wang313b3522016-10-28 12:22:32 -07001340 selinux_initialize(true);
1341
Elliott Hughes9605a942016-11-10 17:43:47 -08001342 // We're in the kernel domain, so re-exec init to transition to the init domain now
Wei Wang313b3522016-10-28 12:22:32 -07001343 // that the SELinux policy has been loaded.
Wei Wang313b3522016-10-28 12:22:32 -07001344 if (restorecon("/init") == -1) {
1345 PLOG(ERROR) << "restorecon failed";
1346 security_failure();
1347 }
Elliott Hughes9605a942016-11-10 17:43:47 -08001348
1349 setenv("INIT_SECOND_STAGE", "true", 1);
1350
James Hawkins27c05222017-01-26 11:55:44 -08001351 static constexpr uint32_t kNanosecondsPerMillisecond = 1e6;
1352 uint64_t start_ms = start_time.time_since_epoch().count() / kNanosecondsPerMillisecond;
1353 setenv("INIT_STARTED_AT", StringPrintf("%" PRIu64, start_ms).c_str(), 1);
Elliott Hughes9605a942016-11-10 17:43:47 -08001354
Wei Wang313b3522016-10-28 12:22:32 -07001355 char* path = argv[0];
Elliott Hughes9605a942016-11-10 17:43:47 -08001356 char* args[] = { path, nullptr };
Tom Cherry34e70412017-03-16 18:08:56 -07001357 execv(path, args);
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -07001358
Tom Cherry34e70412017-03-16 18:08:56 -07001359 // execv() only returns if an error happened, in which case we
1360 // panic and never fall through this conditional.
1361 PLOG(ERROR) << "execv(\"" << path << "\") failed";
1362 security_failure();
Elliott Hughesf65730e2015-04-24 18:38:17 +00001363 }
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001364
Tom Cherry34e70412017-03-16 18:08:56 -07001365 // At this point we're in the second stage of init.
1366 InitKernelLogging(argv);
1367 LOG(INFO) << "init second stage started!";
1368
1369 // Indicate that booting is in progress to background fw loaders, etc.
1370 close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
1371
1372 property_init();
1373
1374 // If arguments are passed both on the command line and in DT,
1375 // properties set in DT always have priority over the command-line ones.
1376 process_kernel_dt();
1377 process_kernel_cmdline();
1378
1379 // Propagate the kernel variables to internal variables
1380 // used by init as well as the current required properties.
1381 export_kernel_boot_props();
1382
1383 // Make the time that init started available for bootstat to log.
1384 property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
1385 property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
1386
1387 // Set libavb version for Framework-only OTA match in Treble build.
Bowgo Tsai45180122017-04-13 21:17:48 +08001388 const char* avb_version = getenv("INIT_AVB_VERSION");
1389 if (avb_version) property_set("ro.boot.avb_version", avb_version);
Tom Cherry34e70412017-03-16 18:08:56 -07001390
1391 // Clean up our environment.
1392 unsetenv("INIT_SECOND_STAGE");
1393 unsetenv("INIT_STARTED_AT");
1394 unsetenv("INIT_SELINUX_TOOK");
Bowgo Tsai45180122017-04-13 21:17:48 +08001395 unsetenv("INIT_AVB_VERSION");
Tom Cherry34e70412017-03-16 18:08:56 -07001396
1397 // Now set up SELinux for second stage.
1398 selinux_initialize(false);
Sandeep Patil74df5ba2017-03-29 10:31:26 -07001399 selinux_restore_context();
Stephen Smalleye46f9d52012-01-13 08:48:47 -05001400
Elliott Hughes929f4072015-04-24 21:13:44 -07001401 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
1402 if (epoll_fd == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001403 PLOG(ERROR) << "epoll_create1 failed";
Elliott Hughes929f4072015-04-24 21:13:44 -07001404 exit(1);
1405 }
1406
1407 signal_handler_init();
Elliott Hughes9042cae2015-04-24 17:43:21 -07001408
Riley Andrewse4b7b292014-06-16 15:06:21 -07001409 property_load_boot_defaults();
Sami Tolvanen9e9efca2015-12-07 12:33:58 +00001410 export_oem_lock_status();
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001411 start_property_service();
Amit Pundird2e74db2016-06-29 19:00:00 +05301412 set_usb_controller();
Dima Zavind7634c92011-12-16 14:18:06 -08001413
Tom Cherryb7349902015-08-26 11:43:36 -07001414 const BuiltinFunctionMap function_map;
1415 Action::set_function_map(&function_map);
1416
1417 Parser& parser = Parser::GetInstance();
1418 parser.AddSectionParser("service",std::make_unique<ServiceParser>());
1419 parser.AddSectionParser("on", std::make_unique<ActionParser>());
1420 parser.AddSectionParser("import", std::make_unique<ImportParser>());
Tom Cherrye2490972017-03-28 16:40:41 -07001421 std::string bootscript = GetProperty("ro.boot.init_rc", "");
Hung-ying Tyan959aeb12017-01-18 09:39:36 +08001422 if (bootscript.empty()) {
1423 parser.ParseConfig("/init.rc");
Jaekyun Seok4ec72cc2017-02-22 20:37:57 +09001424 parser.set_is_system_etc_init_loaded(
1425 parser.ParseConfig("/system/etc/init"));
1426 parser.set_is_vendor_etc_init_loaded(
1427 parser.ParseConfig("/vendor/etc/init"));
1428 parser.set_is_odm_etc_init_loaded(parser.ParseConfig("/odm/etc/init"));
Hung-ying Tyan959aeb12017-01-18 09:39:36 +08001429 } else {
1430 parser.ParseConfig(bootscript);
Jaekyun Seok4ec72cc2017-02-22 20:37:57 +09001431 parser.set_is_system_etc_init_loaded(true);
1432 parser.set_is_vendor_etc_init_loaded(true);
1433 parser.set_is_odm_etc_init_loaded(true);
Hung-ying Tyan959aeb12017-01-18 09:39:36 +08001434 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001435
Tom Cherryd8a72572017-03-13 12:24:49 -07001436 // Turning this on and letting the INFO logging be discarded adds 0.2s to
1437 // Nexus 9 boot time, so it's disabled by default.
1438 if (false) parser.DumpState();
1439
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001440 ActionManager& am = ActionManager::GetInstance();
1441
1442 am.QueueEventTrigger("early-init");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001443
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001444 // 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 -07001445 am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001446 // ... so that we can start queuing up actions that require stuff from /dev.
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001447 am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
Daniel Cashmanbaccc402016-03-25 23:49:05 +00001448 am.QueueBuiltinAction(set_mmap_rnd_bits_action, "set_mmap_rnd_bits");
Dave Weinstein44f7e4f2017-01-19 18:03:34 -08001449 am.QueueBuiltinAction(set_kptr_restrict_action, "set_kptr_restrict");
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001450 am.QueueBuiltinAction(keychord_init_action, "keychord_init");
1451 am.QueueBuiltinAction(console_init_action, "console_init");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001452
Elliott Hughesda40c002015-03-27 23:20:44 -07001453 // Trigger all the boot actions to get us started.
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001454 am.QueueEventTrigger("init");
Dima Zavinca47cef2011-08-24 15:28:23 -07001455
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001456 // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
1457 // wasn't ready immediately after wait_for_coldboot_done
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001458 am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001459
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001460 // Don't mount filesystems or start core system services in charger mode.
Tom Cherrye2490972017-03-28 16:40:41 -07001461 std::string bootmode = GetProperty("ro.bootmode", "");
Yabin Cui74edcea2015-07-24 10:11:05 -07001462 if (bootmode == "charger") {
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001463 am.QueueEventTrigger("charger");
Dima Zavinca47cef2011-08-24 15:28:23 -07001464 } else {
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001465 am.QueueEventTrigger("late-init");
Dima Zavinca47cef2011-08-24 15:28:23 -07001466 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001467
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001468 // Run all property triggers based on current state of the properties.
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001469 am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001470
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001471 while (true) {
Elliott Hughes9605a942016-11-10 17:43:47 -08001472 // By default, sleep until something happens.
1473 int epoll_timeout_ms = -1;
1474
Tom Cherry2d804672017-03-27 16:27:30 -07001475 if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) {
Tom Cherry77ddcd52017-03-23 16:54:38 -07001476 am.ExecuteOneCommand();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001477 }
Tom Cherry2d804672017-03-27 16:27:30 -07001478 if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) {
Tom Cherry77ddcd52017-03-23 16:54:38 -07001479 restart_processes();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001480
Tom Cherry77ddcd52017-03-23 16:54:38 -07001481 // If there's a process that needs restarting, wake up in time for that.
1482 if (process_needs_restart_at != 0) {
1483 epoll_timeout_ms = (process_needs_restart_at - time(nullptr)) * 1000;
1484 if (epoll_timeout_ms < 0) epoll_timeout_ms = 0;
1485 }
1486
1487 // If there's more work to do, wake up again immediately.
1488 if (am.HasMoreCommands()) epoll_timeout_ms = 0;
1489 }
Wei Wang16db4342016-11-30 15:43:42 -08001490
Elliott Hughes929f4072015-04-24 21:13:44 -07001491 epoll_event ev;
Elliott Hughes9605a942016-11-10 17:43:47 -08001492 int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms));
Elliott Hughes929f4072015-04-24 21:13:44 -07001493 if (nr == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001494 PLOG(ERROR) << "epoll_wait failed";
Elliott Hughes929f4072015-04-24 21:13:44 -07001495 } else if (nr == 1) {
1496 ((void (*)()) ev.data.ptr)();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001497 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001498 }
1499
1500 return 0;
1501}