blob: c4af5b50342319bf74d0355f0a9b80f460990bed [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
Tom Cherryb7349902015-08-26 11:43:36 -070017#include "builtins.h"
18
Tom Cherry3041a512019-05-21 17:48:33 -070019#include <android/api-level.h>
Mark Salyzyna98cc9c2016-04-05 13:43:40 -070020#include <dirent.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070021#include <errno.h>
Elliott Hughesdb3f2672015-03-20 09:45:18 -070022#include <fcntl.h>
Wei Wang542aae42017-08-04 13:22:36 -070023#include <fts.h>
Jiyong Parkc2404402018-11-08 17:14:35 +090024#include <glob.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070025#include <linux/loop.h>
26#include <linux/module.h>
Yusuke Sato0df08272015-07-08 14:57:07 -070027#include <mntent.h>
Elliott Hughesdb3f2672015-03-20 09:45:18 -070028#include <net/if.h>
Mark Salyzynad575e02016-04-05 08:10:25 -070029#include <sched.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070030#include <signal.h>
Ray Essick35ffd692021-10-07 15:48:11 -070031#include <stdint.h>
Elliott Hughesdb3f2672015-03-20 09:45:18 -070032#include <stdio.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070033#include <stdlib.h>
Elliott Hughesdb3f2672015-03-20 09:45:18 -070034#include <string.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070035#include <sys/mount.h>
36#include <sys/resource.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070037#include <sys/socket.h>
38#include <sys/stat.h>
terryguan43997542024-09-05 17:35:41 -070039#include <sys/swap.h>
Nick Kralevich124a9c92016-03-27 16:55:59 -070040#include <sys/syscall.h>
Tom Cherryf57c0bf2017-04-07 13:46:21 -070041#include <sys/system_properties.h>
Elliott Hughes3d74d7a2015-01-29 21:31:23 -080042#include <sys/time.h>
Elliott Hughesdb3f2672015-03-20 09:45:18 -070043#include <sys/types.h>
Ken Sumrall0e9dd902012-04-17 17:20:16 -070044#include <sys/wait.h>
Elliott Hughesdb3f2672015-03-20 09:45:18 -070045#include <unistd.h>
Stephen Smalleye46f9d52012-01-13 08:48:47 -050046
Ray Essick35ffd692021-10-07 15:48:11 -070047#include <map>
Nikita Ioffe12a36072019-10-23 20:11:32 +010048#include <memory>
49
Tom Cherryede0d532017-07-06 14:20:11 -070050#include <android-base/chrono_utils.h>
Mark Salyzyna98cc9c2016-04-05 13:43:40 -070051#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070052#include <android-base/logging.h>
Mark Salyzynffa52e92020-05-14 09:20:30 -070053#include <android-base/parsedouble.h>
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -080054#include <android-base/parseint.h>
Tom Cherryccf23532017-03-28 16:40:41 -070055#include <android-base/properties.h>
Tom Cherry70379912017-08-01 14:10:11 -070056#include <android-base/stringprintf.h>
Tom Cherryccf23532017-03-28 16:40:41 -070057#include <android-base/strings.h>
Tom Cherry70379912017-08-01 14:10:11 -070058#include <android-base/unique_fd.h>
Yabin Cui0b1252c2016-06-24 18:28:03 -070059#include <bootloader_message/bootloader_message.h>
Elliott Hughesdb3f2672015-03-20 09:45:18 -070060#include <cutils/android_reboot.h>
Tom Cherryccf23532017-03-28 16:40:41 -070061#include <fs_mgr.h>
Eric Biggersf05da4a2018-10-23 13:10:33 -070062#include <fscrypt/fscrypt.h>
tangjie12b26bdf2023-04-13 17:15:23 +080063#include <libdm/dm.h>
64#include <libdm/loop_control.h>
David Anderson0e330f12019-01-03 18:16:56 -080065#include <libgsi/libgsi.h>
Kiyoung Kime4d3f212019-12-16 14:31:04 +090066#include <logwrap/logwrap.h>
Oli Landc516722020-01-03 10:04:31 +000067#include <private/android_filesystem_config.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070068#include <selinux/android.h>
69#include <selinux/label.h>
70#include <selinux/selinux.h>
Wei Wang02628f32017-08-16 11:34:50 -070071#include <system/thread_defs.h>
Elliott Hughesdb3f2672015-03-20 09:45:18 -070072
Tom Cherry7fd3bc22018-02-13 15:36:14 -080073#include "action_manager.h"
Deyao Ren238e9092022-07-21 23:05:13 +000074#include "apex_init_util.h"
Tom Cherryb7349902015-08-26 11:43:36 -070075#include "bootchart.h"
Nikita Ioffec0df1872019-11-13 21:47:06 +000076#include "builtin_arguments.h"
Paul Crowley052f31c2019-08-26 10:33:17 -070077#include "fscrypt_init_extensions.h"
Tom Cherrybac32992015-07-31 12:45:25 -070078#include "init.h"
Jiyong Park68660412019-01-16 23:00:59 +090079#include "mount_namespace.h"
Tom Cherry67dee622017-07-27 12:54:48 -070080#include "parser.h"
Tom Cherrybac32992015-07-31 12:45:25 -070081#include "property_service.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070082#include "reboot.h"
Tom Cherry7ac013d2017-08-25 10:39:25 -070083#include "rlimit_parser.h"
Vic Yang92c236e2019-05-28 15:58:35 -070084#include "selabel.h"
Joel Galenson4b591f12017-11-27 14:45:26 -080085#include "selinux.h"
Tom Cherrybac32992015-07-31 12:45:25 -070086#include "service.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070087#include "service_list.h"
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070088#include "subcontext.h"
Tom Cherrybac32992015-07-31 12:45:25 -070089#include "util.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070090
Paul Crowley0b8b2302016-12-19 13:03:47 -080091using namespace std::literals::string_literals;
92
Tom Cherrycf80b6d2019-01-07 14:25:31 -080093using android::base::Basename;
Jiyong Parkd185d4a2021-12-11 10:45:20 +090094using android::base::ResultError;
Tom Cherryc88d8f92019-08-19 15:21:25 -070095using android::base::SetProperty;
Wei Wang49d25982020-11-18 15:56:14 -080096using android::base::Split;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070097using android::base::StartsWith;
Tom Cherry7896e7a2019-09-04 15:26:52 -070098using android::base::StringPrintf;
Tom Cherry70379912017-08-01 14:10:11 -070099using android::base::unique_fd;
Tom Cherrya3530e62019-01-30 13:25:35 -0800100using android::fs_mgr::Fstab;
101using android::fs_mgr::ReadFstabFromFile;
Tom Cherry70379912017-08-01 14:10:11 -0700102
Nick Kralevichbc609542015-01-31 21:39:46 -0800103#define chmod DO_NOT_USE_CHMOD_USE_FCHMODAT_SYMLINK_NOFOLLOW
104
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700105namespace android {
106namespace init {
107
Tom Cherryd17c3792019-07-30 10:51:59 -0700108// There are many legacy paths in rootdir/init.rc that will virtually never exist on a new
109// device, such as '/sys/class/leds/jogball-backlight/brightness'. As of this writing, there
110// are 81 such failures on cuttlefish. Instead of spamming the log reporting them, we do not
111// report such failures unless we're running at the DEBUG log level.
112class ErrorIgnoreEnoent {
113 public:
114 ErrorIgnoreEnoent()
115 : ignore_error_(errno == ENOENT &&
116 android::base::GetMinimumLogSeverity() > android::base::DEBUG) {}
117 explicit ErrorIgnoreEnoent(int errno_to_append)
118 : error_(errno_to_append),
119 ignore_error_(errno_to_append == ENOENT &&
120 android::base::GetMinimumLogSeverity() > android::base::DEBUG) {}
121
122 template <typename T>
Jiyong Park705abe22021-12-14 22:55:34 +0900123 operator android::base::expected<T, ResultError<android::base::Errno>>() {
Tom Cherryd17c3792019-07-30 10:51:59 -0700124 if (ignore_error_) {
125 return {};
126 }
127 return error_;
128 }
129
130 template <typename T>
131 ErrorIgnoreEnoent& operator<<(T&& t) {
132 error_ << t;
133 return *this;
134 }
135
136 private:
Jiyong Parkd185d4a2021-12-11 10:45:20 +0900137 Error<> error_;
Tom Cherryd17c3792019-07-30 10:51:59 -0700138 bool ignore_error_;
139};
140
141inline ErrorIgnoreEnoent ErrnoErrorIgnoreEnoent() {
142 return ErrorIgnoreEnoent(errno);
143}
144
Tom Cherry172c83f2019-06-26 14:44:37 -0700145std::vector<std::string> late_import_paths;
146
Elliott Hughes9605a942016-11-10 17:43:47 -0800147static constexpr std::chrono::nanoseconds kCommandRetryTimeout = 5s;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800148
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700149static Result<void> reboot_into_recovery(const std::vector<std::string>& options) {
Paul Crowleyc73b2152018-04-13 17:38:57 +0000150 LOG(ERROR) << "Rebooting into recovery";
Paul Crowleyaf8be582016-05-10 08:52:06 -0700151 std::string err;
152 if (!write_bootloader_message(options, &err)) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700153 return Error() << "Failed to set bootloader message: " << err;
Paul Crowleyaf8be582016-05-10 08:52:06 -0700154 }
Tom Cherry18278d22019-11-12 16:21:20 -0800155 trigger_shutdown("reboot,recovery");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700156 return {};
Yusuke Sato0df08272015-07-08 14:57:07 -0700157}
158
Tom Cherry911b9b12017-07-27 16:20:58 -0700159template <typename F>
160static void ForEachServiceInClass(const std::string& classname, F function) {
161 for (const auto& service : ServiceList::GetInstance()) {
162 if (service->classnames().count(classname)) std::invoke(function, service);
163 }
164}
165
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700166static Result<void> do_class_start(const BuiltinArguments& args) {
Daniel Rosenbergca00b0e2018-11-27 22:08:02 -0800167 // Do not start a class if it has a property persist.dont_start_class.CLASS set to 1.
Martijn Coenenacc45aa2019-05-15 22:04:13 +0200168 if (android::base::GetBoolProperty("persist.init.dont_start_class." + args[1], false))
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700169 return {};
Tom Cherry911b9b12017-07-27 16:20:58 -0700170 // Starting a class does not start services which are explicitly disabled.
171 // They must be started individually.
Tom Cherry20acdef2017-10-03 13:15:03 -0700172 for (const auto& service : ServiceList::GetInstance()) {
Martijn Coenenacc45aa2019-05-15 22:04:13 +0200173 if (service->classnames().count(args[1])) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900174 if (auto result = service->StartIfNotDisabled(); !result.ok()) {
Tom Cherry20acdef2017-10-03 13:15:03 -0700175 LOG(ERROR) << "Could not start service '" << service->name()
Martijn Coenenacc45aa2019-05-15 22:04:13 +0200176 << "' as part of class '" << args[1] << "': " << result.error();
Tom Cherry20acdef2017-10-03 13:15:03 -0700177 }
178 }
179 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700180 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700181}
182
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700183static Result<void> do_class_stop(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700184 ForEachServiceInClass(args[1], &Service::Stop);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700185 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700186}
187
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700188static Result<void> do_class_reset(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700189 ForEachServiceInClass(args[1], &Service::Reset);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700190 return {};
Ken Sumrall752923c2010-12-03 16:33:31 -0800191}
192
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700193static Result<void> do_class_restart(const BuiltinArguments& args) {
Daniel Rosenbergca00b0e2018-11-27 22:08:02 -0800194 // Do not restart a class if it has a property persist.dont_start_class.CLASS set to 1.
195 if (android::base::GetBoolProperty("persist.init.dont_start_class." + args[1], false))
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700196 return {};
David Anderson2285b522021-11-09 18:26:39 -0800197
198 std::string classname;
199
200 CHECK(args.size() == 2 || args.size() == 3);
201
202 bool only_enabled = false;
203 if (args.size() == 3) {
204 if (args[1] != "--only-enabled") {
205 return Error() << "Unexpected argument: " << args[1];
206 }
207 only_enabled = true;
208 classname = args[2];
209 } else if (args.size() == 2) {
210 classname = args[1];
211 }
212
213 for (const auto& service : ServiceList::GetInstance()) {
214 if (!service->classnames().count(classname)) {
215 continue;
216 }
217 if (only_enabled && !service->IsEnabled()) {
218 continue;
219 }
220 service->Restart();
221 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700222 return {};
Steven Moreland2b63d542017-03-10 14:04:37 -0800223}
224
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700225static Result<void> do_domainname(const BuiltinArguments& args) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900226 if (auto result = WriteFile("/proc/sys/kernel/domainname", args[1]); !result.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700227 return Error() << "Unable to write to /proc/sys/kernel/domainname: " << result.error();
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700228 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700229 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700230}
231
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700232static Result<void> do_enable(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700233 Service* svc = ServiceList::GetInstance().FindService(args[1]);
Tom Cherry7fa62c52017-08-01 13:50:23 -0700234 if (!svc) return Error() << "Could not find service";
235
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900236 if (auto result = svc->Enable(); !result.ok()) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700237 return Error() << "Could not enable service: " << result.error();
238 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700239
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700240 return {};
JP Abgrall3beec7e2014-05-02 21:14:29 -0700241}
242
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700243static Result<void> do_exec(const BuiltinArguments& args) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700244 auto service = Service::MakeTemporaryOneshotService(args.args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900245 if (!service.ok()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -0700246 return Error() << "Could not create exec service: " << service.error();
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700247 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900248 if (auto result = (*service)->ExecStart(); !result.ok()) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700249 return Error() << "Could not start exec service: " << result.error();
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700250 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700251
Tom Cherry4772f1d2019-07-30 09:34:41 -0700252 ServiceList::GetInstance().AddService(std::move(*service));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700253 return {};
Tom Cherryb27004a2017-03-27 16:27:30 -0700254}
255
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700256static Result<void> do_exec_background(const BuiltinArguments& args) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700257 auto service = Service::MakeTemporaryOneshotService(args.args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900258 if (!service.ok()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -0700259 return Error() << "Could not create exec background service: " << service.error();
Tom Cherry3631c542017-09-18 12:16:27 -0700260 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900261 if (auto result = (*service)->Start(); !result.ok()) {
Tom Cherry3631c542017-09-18 12:16:27 -0700262 return Error() << "Could not start exec background service: " << result.error();
263 }
264
Tom Cherry4772f1d2019-07-30 09:34:41 -0700265 ServiceList::GetInstance().AddService(std::move(*service));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700266 return {};
Tom Cherry3631c542017-09-18 12:16:27 -0700267}
268
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700269static Result<void> do_exec_start(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700270 Service* service = ServiceList::GetInstance().FindService(args[1]);
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700271 if (!service) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700272 return Error() << "Service not found";
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700273 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700274
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900275 if (auto result = service->ExecStart(); !result.ok()) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700276 return Error() << "Could not start exec service: " << result.error();
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700277 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700278
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700279 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700280}
281
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700282static Result<void> do_export(const BuiltinArguments& args) {
Tom Cherry6de21f12017-08-22 15:41:03 -0700283 if (setenv(args[1].c_str(), args[2].c_str(), 1) == -1) {
284 return ErrnoError() << "setenv() failed";
Tom Cherry7fa62c52017-08-01 13:50:23 -0700285 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700286 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700287}
288
Artur Satayev500946b2021-02-15 20:48:49 +0000289static Result<void> do_load_exports(const BuiltinArguments& args) {
290 auto file_contents = ReadFile(args[1]);
291 if (!file_contents.ok()) {
292 return Error() << "Could not read input file '" << args[1]
293 << "': " << file_contents.error();
294 }
295
296 auto lines = Split(*file_contents, "\n");
297 for (const auto& line : lines) {
298 if (line.empty()) {
299 continue;
300 }
301
302 auto env = Split(line, " ");
303
304 if (env.size() != 3) {
305 return ErrnoError() << "Expected a line as `export <name> <value>`, found: `" << line
306 << "`";
307 }
308
309 if (env[0] != "export") {
310 return ErrnoError() << "Unknown action: '" << env[0] << "', expected 'export'";
311 }
312
313 if (setenv(env[1].c_str(), env[2].c_str(), 1) == -1) {
314 return ErrnoError() << "Failed to export '" << line << "' from " << args[1];
315 }
316 }
317
318 return {};
319}
320
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700321static Result<void> do_hostname(const BuiltinArguments& args) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900322 if (auto result = WriteFile("/proc/sys/kernel/hostname", args[1]); !result.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700323 return Error() << "Unable to write to /proc/sys/kernel/hostname: " << result.error();
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700324 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700325 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700326}
327
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700328static Result<void> do_ifup(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700329 struct ifreq ifr;
330
331 strlcpy(ifr.ifr_name, args[1].c_str(), IFNAMSIZ);
332
Tom Cherry247ffbf2019-07-08 15:09:36 -0700333 unique_fd s(TEMP_FAILURE_RETRY(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0)));
Tom Cherry7fa62c52017-08-01 13:50:23 -0700334 if (s < 0) return ErrnoError() << "opening socket failed";
335
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800336 if (ioctl(s.get(), SIOCGIFFLAGS, &ifr) < 0) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700337 return ErrnoError() << "ioctl(..., SIOCGIFFLAGS, ...) failed";
338 }
339
340 ifr.ifr_flags |= IFF_UP;
341
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800342 if (ioctl(s.get(), SIOCSIFFLAGS, &ifr) < 0) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700343 return ErrnoError() << "ioctl(..., SIOCSIFFLAGS, ...) failed";
344 }
345
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700346 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700347}
348
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700349static Result<void> do_insmod(const BuiltinArguments& args) {
Hung-ying Tyanbfa6d752016-05-17 18:49:10 +0800350 int flags = 0;
351 auto it = args.begin() + 1;
The Android Open Source Project35237d12008-12-17 18:08:08 -0800352
Hung-ying Tyanbfa6d752016-05-17 18:49:10 +0800353 if (!(*it).compare("-f")) {
354 flags = MODULE_INIT_IGNORE_VERMAGIC | MODULE_INIT_IGNORE_MODVERSIONS;
355 it++;
The Android Open Source Project35237d12008-12-17 18:08:08 -0800356 }
357
Hung-ying Tyanbfa6d752016-05-17 18:49:10 +0800358 std::string filename = *it++;
359 std::string options = android::base::Join(std::vector<std::string>(it, args.end()), ' ');
Tom Cherry7fa62c52017-08-01 13:50:23 -0700360
361 unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
362 if (fd == -1) return ErrnoError() << "open(\"" << filename << "\") failed";
363
364 int rc = syscall(__NR_finit_module, fd.get(), options.c_str(), flags);
365 if (rc == -1) return ErrnoError() << "finit_module for \"" << filename << "\" failed";
366
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700367 return {};
The Android Open Source Project35237d12008-12-17 18:08:08 -0800368}
369
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700370static Result<void> do_interface_restart(const BuiltinArguments& args) {
Steven Moreland612d7a42018-05-08 11:21:37 -0700371 Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
372 if (!svc) return Error() << "interface " << args[1] << " not found";
373 svc->Restart();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700374 return {};
Steven Moreland612d7a42018-05-08 11:21:37 -0700375}
376
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700377static Result<void> do_interface_start(const BuiltinArguments& args) {
Steven Moreland612d7a42018-05-08 11:21:37 -0700378 Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
379 if (!svc) return Error() << "interface " << args[1] << " not found";
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900380 if (auto result = svc->Start(); !result.ok()) {
Steven Moreland612d7a42018-05-08 11:21:37 -0700381 return Error() << "Could not start interface: " << result.error();
382 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700383 return {};
Steven Moreland612d7a42018-05-08 11:21:37 -0700384}
385
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700386static Result<void> do_interface_stop(const BuiltinArguments& args) {
Steven Moreland612d7a42018-05-08 11:21:37 -0700387 Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
388 if (!svc) return Error() << "interface " << args[1] << " not found";
389 svc->Stop();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700390 return {};
Steven Moreland612d7a42018-05-08 11:21:37 -0700391}
392
Oli Lan13e51e72019-11-19 18:08:45 +0000393static Result<void> make_dir_with_options(const MkdirOptions& options) {
Paul Crowley68258e82019-10-28 07:55:03 -0700394 std::string ref_basename;
Oli Lan13e51e72019-11-19 18:08:45 +0000395 if (options.ref_option == "ref") {
Paul Crowley68258e82019-10-28 07:55:03 -0700396 ref_basename = fscrypt_key_ref;
Oli Lan13e51e72019-11-19 18:08:45 +0000397 } else if (options.ref_option == "per_boot_ref") {
Paul Crowley68258e82019-10-28 07:55:03 -0700398 ref_basename = fscrypt_key_per_boot_ref;
399 } else {
Oli Lan13e51e72019-11-19 18:08:45 +0000400 return Error() << "Unknown key option: '" << options.ref_option << "'";
Paul Crowley1b4e7322019-08-25 12:18:43 -0700401 }
Paul Crowley68258e82019-10-28 07:55:03 -0700402
Paul Crowley1b4e7322019-08-25 12:18:43 -0700403 struct stat mstat;
Oli Lan13e51e72019-11-19 18:08:45 +0000404 if (lstat(options.target.c_str(), &mstat) != 0) {
Paul Crowley1b4e7322019-08-25 12:18:43 -0700405 if (errno != ENOENT) {
Oli Lan13e51e72019-11-19 18:08:45 +0000406 return ErrnoError() << "lstat() failed on " << options.target;
Paul Crowley1b4e7322019-08-25 12:18:43 -0700407 }
Oli Lan13e51e72019-11-19 18:08:45 +0000408 if (!make_dir(options.target, options.mode)) {
409 return ErrnoErrorIgnoreEnoent() << "mkdir() failed on " << options.target;
Paul Crowley1b4e7322019-08-25 12:18:43 -0700410 }
Oli Lan13e51e72019-11-19 18:08:45 +0000411 if (lstat(options.target.c_str(), &mstat) != 0) {
412 return ErrnoError() << "lstat() failed on new " << options.target;
Benoit Goby5c8574b2012-08-14 15:43:46 -0700413 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700414 }
Paul Crowley1b4e7322019-08-25 12:18:43 -0700415 if (!S_ISDIR(mstat.st_mode)) {
Oli Lan13e51e72019-11-19 18:08:45 +0000416 return Error() << "Not a directory on " << options.target;
Paul Crowley1b4e7322019-08-25 12:18:43 -0700417 }
Oli Lan13e51e72019-11-19 18:08:45 +0000418 bool needs_chmod = (mstat.st_mode & ~S_IFMT) != options.mode;
419 if ((options.uid != static_cast<uid_t>(-1) && options.uid != mstat.st_uid) ||
420 (options.gid != static_cast<gid_t>(-1) && options.gid != mstat.st_gid)) {
421 if (lchown(options.target.c_str(), options.uid, options.gid) == -1) {
422 return ErrnoError() << "lchown failed on " << options.target;
Paul Crowley1b4e7322019-08-25 12:18:43 -0700423 }
424 // chown may have cleared S_ISUID and S_ISGID, chmod again
425 needs_chmod = true;
426 }
427 if (needs_chmod) {
Oli Lan13e51e72019-11-19 18:08:45 +0000428 if (fchmodat(AT_FDCWD, options.target.c_str(), options.mode, AT_SYMLINK_NOFOLLOW) == -1) {
429 return ErrnoError() << "fchmodat() failed on " << options.target;
Paul Crowley1b4e7322019-08-25 12:18:43 -0700430 }
431 }
Eric Biggers893b1ae2022-06-15 18:52:39 +0000432 if (IsFbeEnabled()) {
Oli Lan13e51e72019-11-19 18:08:45 +0000433 if (!FscryptSetDirectoryPolicy(ref_basename, options.fscrypt_action, options.target)) {
Paul Crowleyc73b2152018-04-13 17:38:57 +0000434 return reboot_into_recovery(
Oli Lan13e51e72019-11-19 18:08:45 +0000435 {"--prompt_and_wipe_data", "--reason=set_policy_failed:"s + options.target});
Paul Crowleyaf8be582016-05-10 08:52:06 -0700436 }
437 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700438 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700439}
440
Oli Lan13e51e72019-11-19 18:08:45 +0000441// mkdir <path> [mode] [owner] [group] [<option> ...]
442static Result<void> do_mkdir(const BuiltinArguments& args) {
443 auto options = ParseMkdir(args.args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900444 if (!options.ok()) return options.error();
Oli Lan13e51e72019-11-19 18:08:45 +0000445 return make_dir_with_options(*options);
446}
447
Alex Light68ab20f2016-06-23 11:11:39 -0700448/* umount <path> */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700449static Result<void> do_umount(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700450 if (umount(args[1].c_str()) < 0) {
451 return ErrnoError() << "umount() failed";
452 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700453 return {};
Alex Light68ab20f2016-06-23 11:11:39 -0700454}
455
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700456static struct {
457 const char *name;
458 unsigned flag;
459} mount_flags[] = {
460 { "noatime", MS_NOATIME },
Lars Svenssonb6ee25e2011-07-14 13:39:09 +0200461 { "noexec", MS_NOEXEC },
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700462 { "nosuid", MS_NOSUID },
463 { "nodev", MS_NODEV },
464 { "nodiratime", MS_NODIRATIME },
465 { "ro", MS_RDONLY },
466 { "rw", 0 },
467 { "remount", MS_REMOUNT },
Jeff Sharkeye50ac5f2012-08-14 11:34:34 -0700468 { "bind", MS_BIND },
469 { "rec", MS_REC },
470 { "unbindable", MS_UNBINDABLE },
471 { "private", MS_PRIVATE },
472 { "slave", MS_SLAVE },
473 { "shared", MS_SHARED },
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700474 { "defaults", 0 },
475 { 0, 0 },
476};
477
478/* mount <type> <device> <path> <flags ...> <options> */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700479static Result<void> do_mount(const BuiltinArguments& args) {
Tom Cherry70379912017-08-01 14:10:11 -0700480 const char* options = nullptr;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700481 unsigned flags = 0;
Tom Cherry70379912017-08-01 14:10:11 -0700482 bool wait = false;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700483
Tom Cherry70379912017-08-01 14:10:11 -0700484 for (size_t na = 4; na < args.size(); na++) {
485 size_t i;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700486 for (i = 0; mount_flags[i].name; i++) {
Tom Cherry96f67312015-07-30 13:52:55 -0700487 if (!args[na].compare(mount_flags[i].name)) {
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700488 flags |= mount_flags[i].flag;
489 break;
490 }
491 }
492
Colin Crosscd0f1732010-04-19 17:10:24 -0700493 if (!mount_flags[i].name) {
Tom Cherry70379912017-08-01 14:10:11 -0700494 if (!args[na].compare("wait")) {
495 wait = true;
496 // If our last argument isn't a flag, wolf it up as an option string.
497 } else if (na + 1 == args.size()) {
Tom Cherry96f67312015-07-30 13:52:55 -0700498 options = args[na].c_str();
Tom Cherry70379912017-08-01 14:10:11 -0700499 }
Colin Crosscd0f1732010-04-19 17:10:24 -0700500 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700501 }
502
Tom Cherry70379912017-08-01 14:10:11 -0700503 const char* system = args[1].c_str();
504 const char* source = args[2].c_str();
505 const char* target = args[3].c_str();
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000506
Tom Cherry70379912017-08-01 14:10:11 -0700507 if (android::base::StartsWith(source, "loop@")) {
508 int mode = (flags & MS_RDONLY) ? O_RDONLY : O_RDWR;
tangjie12b26bdf2023-04-13 17:15:23 +0800509 const char* file_path = source + strlen("loop@");
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000510
tangjie12b26bdf2023-04-13 17:15:23 +0800511 // Open source file
512 if (wait) {
513 wait_for_file(file_path, kCommandRetryTimeout);
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000514 }
515
tangjie12b26bdf2023-04-13 17:15:23 +0800516 unique_fd fd(TEMP_FAILURE_RETRY(open(file_path, mode | O_CLOEXEC)));
517 if (fd < 0) {
518 return ErrnoError() << "open(" << file_path << ", " << mode << ") failed";
519 }
520
521 // Allocate loop device and attach it to file_path.
522 android::dm::LoopControl loop_control;
523 std::string loop_device;
524 if (!loop_control.Attach(fd.get(), 5s, &loop_device)) {
525 return ErrnoError() << "loop_control.Attach " << file_path << " failed";
526 }
527
528 if (mount(loop_device.c_str(), target, system, flags, options) < 0) {
529 loop_control.Detach(loop_device);
530 return ErrnoError() << "mount() failed";
531 }
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000532 } else {
Colin Crosscd0f1732010-04-19 17:10:24 -0700533 if (wait)
Elliott Hughes9605a942016-11-10 17:43:47 -0800534 wait_for_file(source, kCommandRetryTimeout);
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000535 if (mount(source, target, system, flags, options) < 0) {
Tom Cherryd17c3792019-07-30 10:51:59 -0700536 return ErrnoErrorIgnoreEnoent() << "mount() failed";
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000537 }
538
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700539 }
Ken Sumralldd4d7862011-02-17 18:09:47 -0800540
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700541 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700542}
543
Hung-ying Tyandc738ea2016-01-14 11:18:21 +0800544/* Imports .rc files from the specified paths. Default ones are applied if none is given.
545 *
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700546 * rc_paths: list of paths to rc files to import
Hung-ying Tyandc738ea2016-01-14 11:18:21 +0800547 */
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700548static void import_late(const std::vector<std::string>& rc_paths) {
Tom Cherry67dee622017-07-27 12:54:48 -0700549 auto& action_manager = ActionManager::GetInstance();
Tom Cherry911b9b12017-07-27 16:20:58 -0700550 auto& service_list = ServiceList::GetInstance();
551 Parser parser = CreateParser(action_manager, service_list);
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700552 if (rc_paths.empty()) {
Jaekyun Seok4ec72cc2017-02-22 20:37:57 +0900553 // Fallbacks for partitions on which early mount isn't enabled.
Tom Cherry67dee622017-07-27 12:54:48 -0700554 for (const auto& path : late_import_paths) {
555 parser.ParseConfig(path);
Jaekyun Seok4ec72cc2017-02-22 20:37:57 +0900556 }
Tom Cherry67dee622017-07-27 12:54:48 -0700557 late_import_paths.clear();
Hung-ying Tyandc738ea2016-01-14 11:18:21 +0800558 } else {
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700559 for (const auto& rc_path : rc_paths) {
560 parser.ParseConfig(rc_path);
Hung-ying Tyandc738ea2016-01-14 11:18:21 +0800561 }
Tom Cherryb8dd0272015-07-22 14:23:33 -0700562 }
Tom Cherryd8a72572017-03-13 12:24:49 -0700563
564 // Turning this on and letting the INFO logging be discarded adds 0.2s to
565 // Nexus 9 boot time, so it's disabled by default.
Tom Cherry30a6f272017-04-19 15:31:58 -0700566 if (false) DumpState();
Tom Cherryb8dd0272015-07-22 14:23:33 -0700567}
568
Wei Wangd61a7e22016-08-23 11:58:09 -0700569/* Queue event based on fs_mgr return code.
570 *
571 * code: return code of fs_mgr_mount_all
572 *
573 * This function might request a reboot, in which case it will
574 * not return.
575 *
576 * return code is processed based on input code
577 */
Eric Biggersab74dbb2023-07-10 17:58:33 +0000578static Result<void> queue_fs_event(int code) {
Eric Biggerse5b5e372021-11-08 16:38:54 -0800579 if (code == FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700580 SetProperty("ro.crypto.state", "unsupported");
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700581 ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700582 return {};
Wei Wangd61a7e22016-08-23 11:58:09 -0700583 } else if (code == FS_MGR_MNTALL_DEV_NEEDS_RECOVERY) {
JP Abgrallcee20682014-07-02 14:26:54 -0700584 /* Setup a wipe via recovery, and reboot into recovery */
David Anderson0e330f12019-01-03 18:16:56 -0800585 if (android::gsi::IsGsiRunning()) {
586 return Error() << "cannot wipe within GSI";
587 }
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700588 PLOG(ERROR) << "fs_mgr_mount_all suggested recovery, so wiping data via recovery.";
Paul Crowley0b8b2302016-12-19 13:03:47 -0800589 const std::vector<std::string> options = {"--wipe_data", "--reason=fs_mgr_mount_all" };
Paul Crowleyc73b2152018-04-13 17:38:57 +0000590 return reboot_into_recovery(options);
JP Abgrallcee20682014-07-02 14:26:54 -0700591 /* If reboot worked, there is no return. */
Eric Biggersab74dbb2023-07-10 17:58:33 +0000592 } else if (code == FS_MGR_MNTALL_DEV_FILE_ENCRYPTED ||
593 code == FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED ||
594 code == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700595 SetProperty("ro.crypto.state", "encrypted");
Paul Lawrence9dbe97b2017-04-21 12:41:48 -0700596
Paul Crowleyc6846962018-01-30 09:56:03 -0800597 // Although encrypted, vold has already set the device up, so we do not need to
598 // do anything different from the nonencrypted case.
599 ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700600 return {};
Wei Wangd61a7e22016-08-23 11:58:09 -0700601 } else if (code > 0) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700602 Error() << "fs_mgr_mount_all() returned unexpected error " << code;
Ken Sumrall0e9dd902012-04-17 17:20:16 -0700603 }
JP Abgrallf22b7452014-07-02 13:16:04 -0700604 /* else ... < 0: error */
Ken Sumrall0e9dd902012-04-17 17:20:16 -0700605
Tom Cherry7fa62c52017-08-01 13:50:23 -0700606 return Error() << "Invalid code: " << code;
Ken Sumrall0e9dd902012-04-17 17:20:16 -0700607}
608
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700609/* <= Q: mount_all <fstab> [ <path> ]* [--<options>]*
610 * >= R: mount_all [ <fstab> ] [--<options>]*
Wei Wangd61a7e22016-08-23 11:58:09 -0700611 *
612 * This function might request a reboot, in which case it will
613 * not return.
614 */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700615static Result<void> do_mount_all(const BuiltinArguments& args) {
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700616 auto mount_all = ParseMountAll(args.args);
617 if (!mount_all.ok()) return mount_all.error();
Wei Wangd61a7e22016-08-23 11:58:09 -0700618
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700619 const char* prop_post_fix = "default";
620 bool queue_event = true;
621 if (mount_all->mode == MOUNT_MODE_EARLY) {
622 prop_post_fix = "early";
623 queue_event = false;
624 } else if (mount_all->mode == MOUNT_MODE_LATE) {
625 prop_post_fix = "late";
Wei Wangd61a7e22016-08-23 11:58:09 -0700626 }
627
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700628 std::string prop_name = "ro.boottime.init.mount_all."s + prop_post_fix;
Tom Cherryede0d532017-07-06 14:20:11 -0700629 android::base::Timer t;
Tom Cherry990483d2019-04-17 12:55:50 -0700630
631 Fstab fstab;
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700632 if (mount_all->fstab_path.empty()) {
633 if (!ReadDefaultFstab(&fstab)) {
634 return Error() << "Could not read default fstab";
635 }
636 } else {
637 if (!ReadFstabFromFile(mount_all->fstab_path, &fstab)) {
638 return Error() << "Could not read fstab";
639 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700640 }
Nikita Ioffe12a36072019-10-23 20:11:32 +0100641
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +0100642 auto mount_fstab_result = fs_mgr_mount_all(&fstab, mount_all->mode);
Tom Cherryc88d8f92019-08-19 15:21:25 -0700643 SetProperty(prop_name, std::to_string(t.duration().count()));
Wei Wangd61a7e22016-08-23 11:58:09 -0700644
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700645 if (mount_all->import_rc) {
646 import_late(mount_all->rc_paths);
Wei Wangd61a7e22016-08-23 11:58:09 -0700647 }
648
649 if (queue_event) {
650 /* queue_fs_event will queue event based on mount_fstab return code
651 * and return processed return code*/
Jooyung Hane34549a2024-08-09 15:58:53 +0900652 auto queue_fs_result = queue_fs_event(mount_fstab_result);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900653 if (!queue_fs_result.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700654 return Error() << "queue_fs_event() failed: " << queue_fs_result.error();
655 }
Wei Wangd61a7e22016-08-23 11:58:09 -0700656 }
657
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700658 return {};
Wei Wangd61a7e22016-08-23 11:58:09 -0700659}
660
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700661/* umount_all [ <fstab> ] */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700662static Result<void> do_umount_all(const BuiltinArguments& args) {
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700663 auto umount_all = ParseUmountAll(args.args);
664 if (!umount_all.ok()) return umount_all.error();
665
Tom Cherry990483d2019-04-17 12:55:50 -0700666 Fstab fstab;
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700667 if (umount_all->empty()) {
668 if (!ReadDefaultFstab(&fstab)) {
669 return Error() << "Could not read default fstab";
670 }
671 } else {
672 if (!ReadFstabFromFile(*umount_all, &fstab)) {
673 return Error() << "Could not read fstab";
674 }
Tom Cherry990483d2019-04-17 12:55:50 -0700675 }
676
Tom Cherry3707d322019-08-15 13:07:24 -0700677 if (auto result = fs_mgr_umount_all(&fstab); result != 0) {
678 return Error() << "umount_fstab() failed " << result;
Yifan Hong402633d2019-04-09 10:11:34 -0700679 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700680 return {};
Yifan Hong402633d2019-04-09 10:11:34 -0700681}
682
Alistair Delvade28a862020-06-08 11:04:53 -0700683/* swapon_all [ <fstab> ] */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700684static Result<void> do_swapon_all(const BuiltinArguments& args) {
Alistair Delvade28a862020-06-08 11:04:53 -0700685 auto swapon_all = ParseSwaponAll(args.args);
686 if (!swapon_all.ok()) return swapon_all.error();
687
Tom Cherry30554572018-11-30 15:21:04 -0800688 Fstab fstab;
Alistair Delvade28a862020-06-08 11:04:53 -0700689 if (swapon_all->empty()) {
690 if (!ReadDefaultFstab(&fstab)) {
691 return Error() << "Could not read default fstab";
692 }
693 } else {
694 if (!ReadFstabFromFile(*swapon_all, &fstab)) {
695 return Error() << "Could not read fstab '" << *swapon_all << "'";
696 }
Tom Cherry30554572018-11-30 15:21:04 -0800697 }
Ken Sumralla76baaa2013-07-09 18:42:09 -0700698
Tom Cherry3707d322019-08-15 13:07:24 -0700699 if (!fs_mgr_swapon_all(fstab)) {
700 return Error() << "fs_mgr_swapon_all() failed";
Tom Cherry30554572018-11-30 15:21:04 -0800701 }
Ken Sumralla76baaa2013-07-09 18:42:09 -0700702
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700703 return {};
Ken Sumralla76baaa2013-07-09 18:42:09 -0700704}
705
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700706static Result<void> do_setprop(const BuiltinArguments& args) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700707 if (StartsWith(args[1], "ctl.")) {
708 return Error()
709 << "Cannot set ctl. properties from init; call the Service functions directly";
710 }
711 if (args[1] == kRestoreconProperty) {
712 return Error() << "Cannot set '" << kRestoreconProperty
713 << "' from init; use the restorecon builtin directly";
714 }
715
Tom Cherryc88d8f92019-08-19 15:21:25 -0700716 SetProperty(args[1], args[2]);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700717 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700718}
719
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700720static Result<void> do_setrlimit(const BuiltinArguments& args) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700721 auto rlimit = ParseRlimit(args.args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900722 if (!rlimit.ok()) return rlimit.error();
Tom Cherry7fa62c52017-08-01 13:50:23 -0700723
Tom Cherry7ac013d2017-08-25 10:39:25 -0700724 if (setrlimit(rlimit->first, &rlimit->second) == -1) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700725 return ErrnoError() << "setrlimit failed";
726 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700727 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700728}
729
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700730static Result<void> do_start(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700731 Service* svc = ServiceList::GetInstance().FindService(args[1]);
Tom Cherry7fa62c52017-08-01 13:50:23 -0700732 if (!svc) return Error() << "service " << args[1] << " not found";
Jooyung Hand6b65fb2023-08-22 09:59:26 +0900733 errno = 0;
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900734 if (auto result = svc->Start(); !result.ok()) {
Tom Cherryd17c3792019-07-30 10:51:59 -0700735 return ErrorIgnoreEnoent() << "Could not start service: " << result.error();
Tom Cherry76af7e62017-08-22 16:13:59 -0700736 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700737 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700738}
739
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700740static Result<void> do_stop(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700741 Service* svc = ServiceList::GetInstance().FindService(args[1]);
Tom Cherry7fa62c52017-08-01 13:50:23 -0700742 if (!svc) return Error() << "service " << args[1] << " not found";
Tom Cherrybac32992015-07-31 12:45:25 -0700743 svc->Stop();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700744 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700745}
746
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700747static Result<void> do_restart(const BuiltinArguments& args) {
David Anderson6d7c7a22021-12-03 15:48:16 -0800748 bool only_if_running = false;
749 if (args.size() == 3) {
750 if (args[1] == "--only-if-running") {
751 only_if_running = true;
752 } else {
753 return Error() << "Unknown argument to restart: " << args[1];
754 }
755 }
756
757 const auto& classname = args[args.size() - 1];
758 Service* svc = ServiceList::GetInstance().FindService(classname);
759 if (!svc) return Error() << "service " << classname << " not found";
760 if (only_if_running && !svc->IsRunning()) {
761 return {};
762 }
Tom Cherrybac32992015-07-31 12:45:25 -0700763 svc->Restart();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700764 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700765}
766
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700767static Result<void> do_trigger(const BuiltinArguments& args) {
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700768 ActionManager::GetInstance().QueueEventTrigger(args[1]);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700769 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700770}
771
Joel Galenson4b591f12017-11-27 14:45:26 -0800772static int MakeSymlink(const std::string& target, const std::string& linkpath) {
773 std::string secontext;
774 // Passing 0 for mode should work.
775 if (SelabelLookupFileContext(linkpath, 0, &secontext) && !secontext.empty()) {
776 setfscreatecon(secontext.c_str());
777 }
778
779 int rc = symlink(target.c_str(), linkpath.c_str());
780
781 if (!secontext.empty()) {
782 int save_errno = errno;
783 setfscreatecon(nullptr);
784 errno = save_errno;
785 }
786
787 return rc;
788}
789
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700790static Result<void> do_symlink(const BuiltinArguments& args) {
Joel Galenson4b591f12017-11-27 14:45:26 -0800791 if (MakeSymlink(args[1], args[2]) < 0) {
Tom Cherry68f2a462017-08-22 16:15:26 -0700792 // The symlink builtin is often used to create symlinks for older devices to be backwards
793 // compatible with new paths, therefore we skip reporting this error.
Tom Cherryd17c3792019-07-30 10:51:59 -0700794 return ErrnoErrorIgnoreEnoent() << "symlink() failed";
Elliott Hughesda46b392016-10-11 17:09:00 -0700795 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700796 return {};
The Android Open Source Project35237d12008-12-17 18:08:08 -0800797}
798
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700799static Result<void> do_rm(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700800 if (unlink(args[1].c_str()) < 0) {
801 return ErrnoError() << "unlink() failed";
802 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700803 return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -0700804}
805
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700806static Result<void> do_rmdir(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700807 if (rmdir(args[1].c_str()) < 0) {
808 return ErrnoError() << "rmdir() failed";
809 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700810 return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -0700811}
812
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700813static Result<void> do_sysclktz(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700814 struct timezone tz = {};
815 if (!android::base::ParseInt(args[1], &tz.tz_minuteswest)) {
816 return Error() << "Unable to parse mins_west_of_gmt";
817 }
818
819 if (settimeofday(nullptr, &tz) == -1) {
820 return ErrnoError() << "settimeofday() failed";
821 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700822 return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -0700823}
824
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700825static Result<void> do_verity_update_state(const BuiltinArguments& args) {
Tom Cherrycf80b6d2019-01-07 14:25:31 -0800826 int mode;
827 if (!fs_mgr_load_verity_state(&mode)) {
828 return Error() << "fs_mgr_load_verity_state() failed";
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700829 }
Tom Cherrycf80b6d2019-01-07 14:25:31 -0800830
831 Fstab fstab;
832 if (!ReadDefaultFstab(&fstab)) {
833 return Error() << "Failed to read default fstab";
834 }
835
836 for (const auto& entry : fstab) {
837 if (!fs_mgr_is_verity_enabled(entry)) {
838 continue;
839 }
840
841 // To be consistent in vboot 1.0 and vboot 2.0 (AVB), use "system" for the partition even
842 // for system as root, so it has property [partition.system.verified].
843 std::string partition = entry.mount_point == "/" ? "system" : Basename(entry.mount_point);
Tom Cherryc88d8f92019-08-19 15:21:25 -0700844 SetProperty("partition." + partition + ".verified", std::to_string(mode));
Tianjie327237d2021-01-20 19:02:34 -0800845
Tianjie10bec652021-08-30 16:10:09 -0700846 auto hashtree_info = fs_mgr_get_hashtree_info(entry);
847 if (hashtree_info) {
848 SetProperty("partition." + partition + ".verified.hash_alg", hashtree_info->algorithm);
849 SetProperty("partition." + partition + ".verified.root_digest",
850 hashtree_info->root_digest);
Nathan Huckleberry997d7382022-10-21 20:55:49 +0000851 SetProperty("partition." + partition + ".verified.check_at_most_once",
852 hashtree_info->check_at_most_once ? "1" : "0");
Tianjie327237d2021-01-20 19:02:34 -0800853 }
Tom Cherrycf80b6d2019-01-07 14:25:31 -0800854 }
855
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700856 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700857}
858
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700859static Result<void> do_write(const BuiltinArguments& args) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900860 if (auto result = WriteFile(args[1], args[2]); !result.ok()) {
Tom Cherryd17c3792019-07-30 10:51:59 -0700861 return ErrorIgnoreEnoent()
862 << "Unable to write to file '" << args[1] << "': " << result.error();
Tom Cherry7fa62c52017-08-01 13:50:23 -0700863 }
864
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700865 return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -0700866}
867
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700868static Result<void> readahead_file(const std::string& filename, bool fully) {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700869 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_CLOEXEC)));
Wei Wang02628f32017-08-16 11:34:50 -0700870 if (fd == -1) {
871 return ErrnoError() << "Error opening file";
872 }
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800873 if (posix_fadvise(fd.get(), 0, 0, POSIX_FADV_WILLNEED)) {
Wei Wang02628f32017-08-16 11:34:50 -0700874 return ErrnoError() << "Error posix_fadvise file";
875 }
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800876 if (readahead(fd.get(), 0, std::numeric_limits<size_t>::max())) {
Wei Wang02628f32017-08-16 11:34:50 -0700877 return ErrnoError() << "Error readahead file";
878 }
879 if (fully) {
880 char buf[BUFSIZ];
881 ssize_t n;
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800882 while ((n = TEMP_FAILURE_RETRY(read(fd.get(), &buf[0], sizeof(buf)))) > 0) {
Wei Wang02628f32017-08-16 11:34:50 -0700883 }
884 if (n != 0) {
885 return ErrnoError() << "Error reading file";
886 }
887 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700888 return {};
Wei Wang02628f32017-08-16 11:34:50 -0700889}
890
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700891static Result<void> do_readahead(const BuiltinArguments& args) {
Wei Wang542aae42017-08-04 13:22:36 -0700892 struct stat sb;
893
894 if (stat(args[1].c_str(), &sb)) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700895 return ErrnoError() << "Error opening " << args[1];
Wei Wang542aae42017-08-04 13:22:36 -0700896 }
897
Wei Wang02628f32017-08-16 11:34:50 -0700898 bool readfully = false;
899 if (args.size() == 3 && args[2] == "--fully") {
900 readfully = true;
901 }
Wei Wang542aae42017-08-04 13:22:36 -0700902 // We will do readahead in a forked process in order not to block init
903 // since it may block while it reads the
904 // filesystem metadata needed to locate the requested blocks. This
905 // occurs frequently with ext[234] on large files using indirect blocks
906 // instead of extents, giving the appearance that the call blocks until
907 // the requested data has been read.
908 pid_t pid = fork();
909 if (pid == 0) {
Wei Wang02628f32017-08-16 11:34:50 -0700910 if (setpriority(PRIO_PROCESS, 0, static_cast<int>(ANDROID_PRIORITY_LOWEST)) != 0) {
911 PLOG(WARNING) << "setpriority failed";
912 }
913 if (android_set_ioprio(0, IoSchedClass_IDLE, 7)) {
914 PLOG(WARNING) << "ioprio_get failed";
915 }
Wei Wang542aae42017-08-04 13:22:36 -0700916 android::base::Timer t;
917 if (S_ISREG(sb.st_mode)) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900918 if (auto result = readahead_file(args[1], readfully); !result.ok()) {
Wei Wang02628f32017-08-16 11:34:50 -0700919 LOG(WARNING) << "Unable to readahead '" << args[1] << "': " << result.error();
Wei Wang542aae42017-08-04 13:22:36 -0700920 _exit(EXIT_FAILURE);
921 }
922 } else if (S_ISDIR(sb.st_mode)) {
923 char* paths[] = {const_cast<char*>(args[1].data()), nullptr};
924 std::unique_ptr<FTS, decltype(&fts_close)> fts(
925 fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr), fts_close);
926 if (!fts) {
927 PLOG(ERROR) << "Error opening directory: " << args[1];
928 _exit(EXIT_FAILURE);
929 }
930 // Traverse the entire hierarchy and do readahead
931 for (FTSENT* ftsent = fts_read(fts.get()); ftsent != nullptr;
932 ftsent = fts_read(fts.get())) {
933 if (ftsent->fts_info & FTS_F) {
Wei Wang02628f32017-08-16 11:34:50 -0700934 const std::string filename = ftsent->fts_accpath;
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900935 if (auto result = readahead_file(filename, readfully); !result.ok()) {
Wei Wang02628f32017-08-16 11:34:50 -0700936 LOG(WARNING)
937 << "Unable to readahead '" << filename << "': " << result.error();
Wei Wang542aae42017-08-04 13:22:36 -0700938 }
939 }
940 }
941 }
Wei Wang02628f32017-08-16 11:34:50 -0700942 LOG(INFO) << "Readahead " << args[1] << " took " << t << " asynchronously";
Wei Wang542aae42017-08-04 13:22:36 -0700943 _exit(0);
944 } else if (pid < 0) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700945 return ErrnoError() << "Fork failed";
Wei Wang542aae42017-08-04 13:22:36 -0700946 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700947 return {};
Wei Wang542aae42017-08-04 13:22:36 -0700948}
949
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700950static Result<void> do_copy(const BuiltinArguments& args) {
Tom Cherry62ca6632017-08-03 12:54:07 -0700951 auto file_contents = ReadFile(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900952 if (!file_contents.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700953 return Error() << "Could not read input file '" << args[1] << "': " << file_contents.error();
San Mehat7c44fe52009-08-26 16:39:25 -0700954 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900955 if (auto result = WriteFile(args[2], *file_contents); !result.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700956 return Error() << "Could not write to output file '" << args[2] << "': " << result.error();
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700957 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700958
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700959 return {};
San Mehat7c44fe52009-08-26 16:39:25 -0700960}
961
Wei Wang49d25982020-11-18 15:56:14 -0800962static Result<void> do_copy_per_line(const BuiltinArguments& args) {
963 std::string file_contents;
964 if (!android::base::ReadFileToString(args[1], &file_contents, true)) {
965 return Error() << "Could not read input file '" << args[1] << "'";
966 }
967 auto lines = Split(file_contents, "\n");
968 for (const auto& line : lines) {
969 auto result = WriteFile(args[2], line);
970 if (!result.ok()) {
971 LOG(VERBOSE) << "Could not write to output file '" << args[2] << "' with '" << line
972 << "' : " << result.error();
973 }
974 }
975
976 return {};
977}
978
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700979static Result<void> do_chown(const BuiltinArguments& args) {
Tom Cherry62ca6632017-08-03 12:54:07 -0700980 auto uid = DecodeUid(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900981 if (!uid.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700982 return Error() << "Unable to decode UID for '" << args[1] << "': " << uid.error();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700983 }
Tom Cherry517e1f12017-05-04 17:40:33 -0700984
985 // GID is optional and pushes the index of path out by one if specified.
986 const std::string& path = (args.size() == 4) ? args[3] : args[2];
Tom Cherry62ca6632017-08-03 12:54:07 -0700987 Result<gid_t> gid = -1;
Tom Cherry517e1f12017-05-04 17:40:33 -0700988
989 if (args.size() == 4) {
Tom Cherry62ca6632017-08-03 12:54:07 -0700990 gid = DecodeUid(args[2]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900991 if (!gid.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700992 return Error() << "Unable to decode GID for '" << args[2] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700993 }
994 }
995
Tom Cherry7fa62c52017-08-01 13:50:23 -0700996 if (lchown(path.c_str(), *uid, *gid) == -1) {
Tom Cherryd17c3792019-07-30 10:51:59 -0700997 return ErrnoErrorIgnoreEnoent() << "lchown() failed";
Tom Cherry7fa62c52017-08-01 13:50:23 -0700998 }
Tom Cherry517e1f12017-05-04 17:40:33 -0700999
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001000 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001001}
1002
1003static mode_t get_mode(const char *s) {
1004 mode_t mode = 0;
1005 while (*s) {
1006 if (*s >= '0' && *s <= '7') {
1007 mode = (mode<<3) | (*s-'0');
1008 } else {
1009 return -1;
1010 }
1011 s++;
1012 }
1013 return mode;
1014}
1015
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001016static Result<void> do_chmod(const BuiltinArguments& args) {
Tom Cherry96f67312015-07-30 13:52:55 -07001017 mode_t mode = get_mode(args[1].c_str());
1018 if (fchmodat(AT_FDCWD, args[2].c_str(), mode, AT_SYMLINK_NOFOLLOW) < 0) {
Tom Cherryd17c3792019-07-30 10:51:59 -07001019 return ErrnoErrorIgnoreEnoent() << "fchmodat() failed";
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001020 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001021 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001022}
1023
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001024static Result<void> do_restorecon(const BuiltinArguments& args) {
Tom Cherry4772f1d2019-07-30 09:34:41 -07001025 auto restorecon_info = ParseRestorecon(args.args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001026 if (!restorecon_info.ok()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -07001027 return restorecon_info.error();
1028 }
1029
1030 const auto& [flag, paths] = *restorecon_info;
1031
Stephen Smalley726e8f72013-10-09 16:02:09 -04001032 int ret = 0;
Tom Cherry4772f1d2019-07-30 09:34:41 -07001033 for (const auto& path : paths) {
1034 if (selinux_android_restorecon(path.c_str(), flag) < 0) {
1035 ret = errno;
Paul Lawrencea8d84342016-11-14 15:40:18 -08001036 }
Stephen Smalleye46f9d52012-01-13 08:48:47 -05001037 }
Tom Cherry7fa62c52017-08-01 13:50:23 -07001038
Tom Cherryd17c3792019-07-30 10:51:59 -07001039 if (ret) return ErrnoErrorIgnoreEnoent() << "selinux_android_restorecon() failed";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001040 return {};
Stephen Smalley726e8f72013-10-09 16:02:09 -04001041}
1042
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001043static Result<void> do_restorecon_recursive(const BuiltinArguments& args) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001044 std::vector<std::string> non_const_args(args.args);
Paul Lawrencea8d84342016-11-14 15:40:18 -08001045 non_const_args.insert(std::next(non_const_args.begin()), "--recursive");
Bart Van Assche3dfb8bc2023-02-22 10:01:33 -08001046 return do_restorecon({.args = std::move(non_const_args), .context = args.context});
Stephen Smalleye46f9d52012-01-13 08:48:47 -05001047}
1048
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001049static Result<void> do_loglevel(const BuiltinArguments& args) {
Elliott Hughes7bc87a52016-08-04 16:09:39 -07001050 // TODO: support names instead/as well?
Elliott Hughesda46b392016-10-11 17:09:00 -07001051 int log_level = -1;
1052 android::base::ParseInt(args[1], &log_level);
Elliott Hughes7bc87a52016-08-04 16:09:39 -07001053 android::base::LogSeverity severity;
1054 switch (log_level) {
1055 case 7: severity = android::base::DEBUG; break;
1056 case 6: severity = android::base::INFO; break;
1057 case 5:
1058 case 4: severity = android::base::WARNING; break;
1059 case 3: severity = android::base::ERROR; break;
1060 case 2:
1061 case 1:
1062 case 0: severity = android::base::FATAL; break;
1063 default:
Tom Cherry7fa62c52017-08-01 13:50:23 -07001064 return Error() << "invalid log level " << log_level;
Riley Andrews1bbef882014-06-26 13:55:03 -07001065 }
Elliott Hughes7bc87a52016-08-04 16:09:39 -07001066 android::base::SetMinimumLogSeverity(severity);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001067 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001068}
1069
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001070static Result<void> do_load_persist_props(const BuiltinArguments& args) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001071 SendLoadPersistentPropertiesMessage();
1072
1073 start_waiting_for_property("ro.persistent_properties.ready", "true");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001074 return {};
Ken Sumrallc5c51032011-03-08 17:01:29 -08001075}
1076
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001077static Result<void> do_load_system_props(const BuiltinArguments& args) {
Jiyong Park3b316ee2019-01-13 02:42:31 +09001078 LOG(INFO) << "deprecated action `load_system_props` called.";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001079 return {};
Riley Andrewse4b7b292014-06-16 15:06:21 -07001080}
1081
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001082static Result<void> do_wait(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001083 auto timeout = kCommandRetryTimeout;
1084 if (args.size() == 3) {
Mark Salyzynffa52e92020-05-14 09:20:30 -07001085 double timeout_double;
1086 if (!android::base::ParseDouble(args[2], &timeout_double, 0)) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001087 return Error() << "failed to parse timeout";
Elliott Hughesda46b392016-10-11 17:09:00 -07001088 }
Mark Salyzynffa52e92020-05-14 09:20:30 -07001089 timeout = std::chrono::duration_cast<std::chrono::nanoseconds>(
1090 std::chrono::duration<double>(timeout_double));
Elliott Hughesda46b392016-10-11 17:09:00 -07001091 }
Tom Cherry7fa62c52017-08-01 13:50:23 -07001092
1093 if (wait_for_file(args[1].c_str(), timeout) != 0) {
1094 return Error() << "wait_for_file() failed";
1095 }
1096
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001097 return {};
Colin Crosscd0f1732010-04-19 17:10:24 -07001098}
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001099
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001100static Result<void> do_wait_for_prop(const BuiltinArguments& args) {
Wei Wang132ac312017-01-25 16:27:03 -08001101 const char* name = args[1].c_str();
1102 const char* value = args[2].c_str();
1103 size_t value_len = strlen(value);
1104
Tom Cherryde6bd502018-02-13 16:50:08 -08001105 if (!IsLegalPropertyName(name)) {
1106 return Error() << "IsLegalPropertyName(" << name << ") failed";
Wei Wang132ac312017-01-25 16:27:03 -08001107 }
1108 if (value_len >= PROP_VALUE_MAX) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001109 return Error() << "value too long";
Wei Wang132ac312017-01-25 16:27:03 -08001110 }
Wei Wang2d0fdaa2017-02-02 10:52:39 -08001111 if (!start_waiting_for_property(name, value)) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001112 return Error() << "already waiting for a property";
Wei Wang132ac312017-01-25 16:27:03 -08001113 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001114 return {};
Wei Wang132ac312017-01-25 16:27:03 -08001115}
1116
Paul Crowley749af8c2015-05-28 17:35:06 +01001117static bool is_file_crypto() {
Tom Cherryccf23532017-03-28 16:40:41 -07001118 return android::base::GetProperty("ro.crypto.type", "") == "file";
Paul Crowley749af8c2015-05-28 17:35:06 +01001119}
1120
Tom Cherry7896e7a2019-09-04 15:26:52 -07001121static Result<void> ExecWithFunctionOnFailure(const std::vector<std::string>& args,
1122 std::function<void(const std::string&)> function) {
1123 auto service = Service::MakeTemporaryOneshotService(args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001124 if (!service.ok()) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001125 function("MakeTemporaryOneshotService failed: " + service.error().message());
Paul Crowleyc73b2152018-04-13 17:38:57 +00001126 }
Tom Cherry7896e7a2019-09-04 15:26:52 -07001127 (*service)->AddReapCallback([function](const siginfo_t& siginfo) {
Paul Crowleyc73b2152018-04-13 17:38:57 +00001128 if (siginfo.si_code != CLD_EXITED || siginfo.si_status != 0) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001129 function(StringPrintf("Exec service failed, status %d", siginfo.si_status));
Paul Crowleyc73b2152018-04-13 17:38:57 +00001130 }
1131 });
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001132 if (auto result = (*service)->ExecStart(); !result.ok()) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001133 function("ExecStart failed: " + result.error().message());
Paul Crowleyc73b2152018-04-13 17:38:57 +00001134 }
Tom Cherry4772f1d2019-07-30 09:34:41 -07001135 ServiceList::GetInstance().AddService(std::move(*service));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001136 return {};
Paul Crowleyc73b2152018-04-13 17:38:57 +00001137}
1138
Tom Cherry7896e7a2019-09-04 15:26:52 -07001139static Result<void> ExecVdcRebootOnFailure(const std::string& vdc_arg) {
1140 auto reboot_reason = vdc_arg + "_failed";
1141
Jooyung Hanf91503b2024-08-09 16:17:20 +09001142 auto reboot = [reboot_reason](const std::string& message) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001143 // TODO (b/122850122): support this in gsi
Jooyung Hanf91503b2024-08-09 16:17:20 +09001144 if (IsFbeEnabled() && !android::gsi::IsGsiRunning()) {
1145 LOG(ERROR) << message << ": Rebooting into recovery, reason: " << reboot_reason;
1146 if (auto result = reboot_into_recovery(
1147 {"--prompt_and_wipe_data", "--reason="s + reboot_reason});
1148 !result.ok()) {
1149 LOG(FATAL) << "Could not reboot into recovery: " << result.error();
Tom Cherry7896e7a2019-09-04 15:26:52 -07001150 }
1151 } else {
Jooyung Hanf91503b2024-08-09 16:17:20 +09001152 LOG(ERROR) << "Failure (reboot suppressed): " << reboot_reason;
Tom Cherry7896e7a2019-09-04 15:26:52 -07001153 }
1154 };
1155
1156 std::vector<std::string> args = {"exec", "/system/bin/vdc", "--wait", "cryptfs", vdc_arg};
1157 return ExecWithFunctionOnFailure(args, reboot);
1158}
1159
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001160static Result<void> do_installkey(const BuiltinArguments& args) {
1161 if (!is_file_crypto()) return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -07001162
Eric Biggersf05da4a2018-10-23 13:10:33 -07001163 auto unencrypted_dir = args[1] + fscrypt_unencrypted_folder;
Tom Cherryc3692b32017-08-10 12:22:44 -07001164 if (!make_dir(unencrypted_dir, 0700) && errno != EEXIST) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001165 return ErrnoError() << "Failed to create " << unencrypted_dir;
Janis Danisevskis9cc51722017-03-29 14:50:01 -07001166 }
Tom Cherry7896e7a2019-09-04 15:26:52 -07001167 return ExecVdcRebootOnFailure("enablefilecrypto");
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001168}
Paul Crowley749af8c2015-05-28 17:35:06 +01001169
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001170static Result<void> do_init_user0(const BuiltinArguments& args) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001171 return ExecVdcRebootOnFailure("init_user0");
Paul Crowley59497452016-02-01 16:37:13 +00001172}
1173
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001174static Result<void> do_mark_post_data(const BuiltinArguments& args) {
Jooyung Han148f6022024-08-19 14:29:04 +09001175 LOG(INFO) << "deprecated action `mark_post_data` called.";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001176 return {};
Martijn Coenen70788f92019-04-23 16:26:01 +02001177}
1178
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001179static Result<void> GenerateLinkerConfiguration() {
Kiyoung Kim03b9bca2020-11-30 14:49:36 +09001180 const char* linkerconfig_binary = "/apex/com.android.runtime/bin/linkerconfig";
Kiyoung Kim3b2dbe92019-12-30 18:44:41 +09001181 const char* linkerconfig_target = "/linkerconfig";
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001182 const char* arguments[] = {linkerconfig_binary, "--target", linkerconfig_target};
1183
1184 if (logwrap_fork_execvp(arraysize(arguments), arguments, nullptr, false, LOG_KLOG, false,
1185 nullptr) != 0) {
1186 return ErrnoError() << "failed to execute linkerconfig";
1187 }
1188
Kiyoung Kim0cbee0d2021-03-02 16:45:27 +09001189 auto current_mount_ns = GetCurrentMountNamespace();
1190 if (!current_mount_ns.ok()) {
1191 return current_mount_ns.error();
1192 }
1193 if (*current_mount_ns == NS_DEFAULT) {
1194 SetDefaultMountNamespaceReady();
1195 }
1196
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001197 LOG(INFO) << "linkerconfig generated " << linkerconfig_target
1198 << " with mounted APEX modules info";
1199
1200 return {};
1201}
1202
Jooyung Han4f23d5a2020-06-09 13:44:17 +09001203static Result<void> MountLinkerConfigForDefaultNamespace() {
1204 // No need to mount linkerconfig for default mount namespace if the path does not exist (which
1205 // would mean it is already mounted)
1206 if (access("/linkerconfig/default", 0) != 0) {
1207 return {};
1208 }
1209
1210 if (mount("/linkerconfig/default", "/linkerconfig", nullptr, MS_BIND | MS_REC, nullptr) != 0) {
1211 return ErrnoError() << "Failed to mount linker configuration for default mount namespace.";
1212 }
1213
1214 return {};
1215}
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001216static Result<void> do_update_linker_config(const BuiltinArguments&) {
Shikha Malhotra720694d2021-07-30 12:35:27 +00001217 return GenerateLinkerConfiguration();
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001218}
1219
Oli Lan13e51e72019-11-19 18:08:45 +00001220/*
1221 * Creates a directory under /data/misc/apexdata/ for each APEX.
1222 */
Jooyung Han2982f092023-08-11 14:14:37 +09001223static void create_apex_data_dirs() {
1224 for (const auto& name : GetApexListFrom("/apex")) {
1225 auto path = "/data/misc/apexdata/" + name;
Oli Lan90c523b2020-01-17 11:41:04 +00001226 auto options = MkdirOptions{path, 0771, AID_ROOT, AID_SYSTEM, FscryptAction::kNone, "ref"};
Jooyung Han2982f092023-08-11 14:14:37 +09001227 auto result = make_dir_with_options(options);
1228 if (!result.ok()) {
1229 LOG(ERROR) << result.error();
1230 }
Oli Lan13e51e72019-11-19 18:08:45 +00001231 }
Oli Lan13e51e72019-11-19 18:08:45 +00001232}
1233
1234static Result<void> do_perform_apex_config(const BuiltinArguments& args) {
Jooyung Han5c4217c2023-08-10 13:12:53 +09001235 bool bootstrap = false;
1236 if (args.size() == 2) {
1237 if (args[1] != "--bootstrap") {
1238 return Error() << "Unexpected argument: " << args[1];
1239 }
1240 bootstrap = true;
Oli Lan13e51e72019-11-19 18:08:45 +00001241 }
Jooyung Han5c4217c2023-08-10 13:12:53 +09001242
1243 if (!bootstrap) {
Jooyung Han2982f092023-08-11 14:14:37 +09001244 create_apex_data_dirs();
Jooyung Han5c4217c2023-08-10 13:12:53 +09001245 }
1246
Jooyung Han55ef3d62023-08-10 18:27:22 +09001247 auto parse_result = ParseRcScriptsFromAllApexes(bootstrap);
1248 if (!parse_result.ok()) {
1249 return parse_result.error();
Oli Lan13e51e72019-11-19 18:08:45 +00001250 }
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001251
1252 auto update_linker_config = do_update_linker_config(args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001253 if (!update_linker_config.ok()) {
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001254 return update_linker_config.error();
1255 }
1256
Jooyung Han5c4217c2023-08-10 13:12:53 +09001257 if (!bootstrap) {
Jooyung Han646e0012023-08-21 17:34:37 +09001258 ServiceList::GetInstance().StartDelayedServices();
Jooyung Han5c4217c2023-08-10 13:12:53 +09001259 }
Oli Lan13e51e72019-11-19 18:08:45 +00001260 return {};
1261}
1262
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001263static Result<void> do_enter_default_mount_ns(const BuiltinArguments& args) {
Jooyung Han4f23d5a2020-06-09 13:44:17 +09001264 if (auto result = SwitchToMountNamespaceIfNeeded(NS_DEFAULT); !result.ok()) {
1265 return result.error();
Jiyong Parkdcbaf9f2019-02-22 22:15:25 +09001266 }
Jooyung Han4f23d5a2020-06-09 13:44:17 +09001267 if (auto result = MountLinkerConfigForDefaultNamespace(); !result.ok()) {
1268 return result.error();
1269 }
1270 LOG(INFO) << "Switched to default mount namespace";
1271 return {};
Jiyong Parkdcbaf9f2019-02-22 22:15:25 +09001272}
1273
terryguan43997542024-09-05 17:35:41 -07001274static Result<void> do_swapoff(const BuiltinArguments& args) {
1275 if (!swapoff(args[1].c_str())) {
1276 return ErrnoError() << "swapoff() failed";
1277 }
1278 return {};
1279}
1280
Tom Cherryde6bd502018-02-13 16:50:08 -08001281// Builtin-function-map start
Tom Cherryd52a5b32019-07-22 16:05:36 -07001282const BuiltinFunctionMap& GetBuiltinFunctionMap() {
Tom Cherryb7349902015-08-26 11:43:36 -07001283 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Tom Cherryb27004a2017-03-27 16:27:30 -07001284 // clang-format off
Tom Cherryd52a5b32019-07-22 16:05:36 -07001285 static const BuiltinFunctionMap builtin_functions = {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001286 {"bootchart", {1, 1, {false, do_bootchart}}},
1287 {"chmod", {2, 2, {true, do_chmod}}},
1288 {"chown", {2, 3, {true, do_chown}}},
1289 {"class_reset", {1, 1, {false, do_class_reset}}},
David Anderson2285b522021-11-09 18:26:39 -08001290 {"class_restart", {1, 2, {false, do_class_restart}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001291 {"class_start", {1, 1, {false, do_class_start}}},
1292 {"class_stop", {1, 1, {false, do_class_stop}}},
1293 {"copy", {2, 2, {true, do_copy}}},
Wei Wang49d25982020-11-18 15:56:14 -08001294 {"copy_per_line", {2, 2, {true, do_copy_per_line}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001295 {"domainname", {1, 1, {true, do_domainname}}},
1296 {"enable", {1, 1, {false, do_enable}}},
1297 {"exec", {1, kMax, {false, do_exec}}},
1298 {"exec_background", {1, kMax, {false, do_exec_background}}},
1299 {"exec_start", {1, 1, {false, do_exec_start}}},
1300 {"export", {2, 2, {false, do_export}}},
1301 {"hostname", {1, 1, {true, do_hostname}}},
1302 {"ifup", {1, 1, {true, do_ifup}}},
1303 {"init_user0", {0, 0, {false, do_init_user0}}},
1304 {"insmod", {1, kMax, {true, do_insmod}}},
1305 {"installkey", {1, 1, {false, do_installkey}}},
Steven Moreland612d7a42018-05-08 11:21:37 -07001306 {"interface_restart", {1, 1, {false, do_interface_restart}}},
1307 {"interface_start", {1, 1, {false, do_interface_start}}},
1308 {"interface_stop", {1, 1, {false, do_interface_stop}}},
Artur Satayev500946b2021-02-15 20:48:49 +00001309 {"load_exports", {1, 1, {false, do_load_exports}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001310 {"load_persist_props", {0, 0, {false, do_load_persist_props}}},
1311 {"load_system_props", {0, 0, {false, do_load_system_props}}},
1312 {"loglevel", {1, 1, {false, do_loglevel}}},
Martijn Coenen70788f92019-04-23 16:26:01 +02001313 {"mark_post_data", {0, 0, {false, do_mark_post_data}}},
Paul Crowley68258e82019-10-28 07:55:03 -07001314 {"mkdir", {1, 6, {true, do_mkdir}}},
Tom Cherry880d5662018-02-05 08:01:54 -08001315 // TODO: Do mount operations in vendor_init.
1316 // mount_all is currently too complex to run in vendor_init as it queues action triggers,
1317 // imports rc scripts, etc. It should be simplified and run in vendor_init context.
1318 // mount and umount are run in the same context as mount_all for symmetry.
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -07001319 {"mount_all", {0, kMax, {false, do_mount_all}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001320 {"mount", {3, kMax, {false, do_mount}}},
Jooyung Han5c4217c2023-08-10 13:12:53 +09001321 {"perform_apex_config", {0, 1, {false, do_perform_apex_config}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001322 {"umount", {1, 1, {false, do_umount}}},
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -07001323 {"umount_all", {0, 1, {false, do_umount_all}}},
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001324 {"update_linker_config", {0, 0, {false, do_update_linker_config}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001325 {"readahead", {1, 2, {true, do_readahead}}},
David Anderson6d7c7a22021-12-03 15:48:16 -08001326 {"restart", {1, 2, {false, do_restart}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001327 {"restorecon", {1, kMax, {true, do_restorecon}}},
1328 {"restorecon_recursive", {1, kMax, {true, do_restorecon_recursive}}},
1329 {"rm", {1, 1, {true, do_rm}}},
1330 {"rmdir", {1, 1, {true, do_rmdir}}},
Tom Cherry32228482018-01-18 16:14:25 -08001331 {"setprop", {2, 2, {true, do_setprop}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001332 {"setrlimit", {3, 3, {false, do_setrlimit}}},
1333 {"start", {1, 1, {false, do_start}}},
1334 {"stop", {1, 1, {false, do_stop}}},
Alistair Delvade28a862020-06-08 11:04:53 -07001335 {"swapon_all", {0, 1, {false, do_swapon_all}}},
terryguan43997542024-09-05 17:35:41 -07001336 {"swapoff", {1, 1, {false, do_swapoff}}},
Jiyong Parkdcbaf9f2019-02-22 22:15:25 +09001337 {"enter_default_mount_ns", {0, 0, {false, do_enter_default_mount_ns}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001338 {"symlink", {2, 2, {true, do_symlink}}},
1339 {"sysclktz", {1, 1, {false, do_sysclktz}}},
1340 {"trigger", {1, 1, {false, do_trigger}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001341 {"verity_update_state", {0, 0, {false, do_verity_update_state}}},
1342 {"wait", {1, 2, {true, do_wait}}},
Tom Cherryfa3e52c2017-10-17 10:43:52 -07001343 {"wait_for_prop", {2, 2, {false, do_wait_for_prop}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001344 {"write", {2, 2, {true, do_write}}},
Tom Cherryb7349902015-08-26 11:43:36 -07001345 };
Tom Cherryb27004a2017-03-27 16:27:30 -07001346 // clang-format on
Tom Cherryb7349902015-08-26 11:43:36 -07001347 return builtin_functions;
1348}
Tom Cherryde6bd502018-02-13 16:50:08 -08001349// Builtin-function-map end
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001350
1351} // namespace init
1352} // namespace android