blob: 3f3bec6df904ad028a5a61e48239775848130497 [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>
Nick Kralevich124a9c92016-03-27 16:55:59 -070039#include <sys/syscall.h>
Tom Cherryf57c0bf2017-04-07 13:46:21 -070040#include <sys/system_properties.h>
Elliott Hughes3d74d7a2015-01-29 21:31:23 -080041#include <sys/time.h>
Elliott Hughesdb3f2672015-03-20 09:45:18 -070042#include <sys/types.h>
Ken Sumrall0e9dd902012-04-17 17:20:16 -070043#include <sys/wait.h>
Elliott Hughesdb3f2672015-03-20 09:45:18 -070044#include <unistd.h>
Stephen Smalleye46f9d52012-01-13 08:48:47 -050045
Ray Essick35ffd692021-10-07 15:48:11 -070046#include <map>
Nikita Ioffe12a36072019-10-23 20:11:32 +010047#include <memory>
48
Tom Cherryede0d532017-07-06 14:20:11 -070049#include <android-base/chrono_utils.h>
Mark Salyzyna98cc9c2016-04-05 13:43:40 -070050#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070051#include <android-base/logging.h>
Mark Salyzynffa52e92020-05-14 09:20:30 -070052#include <android-base/parsedouble.h>
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -080053#include <android-base/parseint.h>
Tom Cherryccf23532017-03-28 16:40:41 -070054#include <android-base/properties.h>
Tom Cherry70379912017-08-01 14:10:11 -070055#include <android-base/stringprintf.h>
Tom Cherryccf23532017-03-28 16:40:41 -070056#include <android-base/strings.h>
Tom Cherry70379912017-08-01 14:10:11 -070057#include <android-base/unique_fd.h>
Yabin Cui0b1252c2016-06-24 18:28:03 -070058#include <bootloader_message/bootloader_message.h>
Elliott Hughesdb3f2672015-03-20 09:45:18 -070059#include <cutils/android_reboot.h>
Tom Cherryccf23532017-03-28 16:40:41 -070060#include <fs_mgr.h>
Eric Biggersf05da4a2018-10-23 13:10:33 -070061#include <fscrypt/fscrypt.h>
tangjie12b26bdf2023-04-13 17:15:23 +080062#include <libdm/dm.h>
63#include <libdm/loop_control.h>
David Anderson0e330f12019-01-03 18:16:56 -080064#include <libgsi/libgsi.h>
Kiyoung Kime4d3f212019-12-16 14:31:04 +090065#include <logwrap/logwrap.h>
Oli Landc516722020-01-03 10:04:31 +000066#include <private/android_filesystem_config.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070067#include <selinux/android.h>
68#include <selinux/label.h>
69#include <selinux/selinux.h>
Wei Wang02628f32017-08-16 11:34:50 -070070#include <system/thread_defs.h>
Elliott Hughesdb3f2672015-03-20 09:45:18 -070071
Tom Cherry7fd3bc22018-02-13 15:36:14 -080072#include "action_manager.h"
Deyao Ren238e9092022-07-21 23:05:13 +000073#include "apex_init_util.h"
Tom Cherryb7349902015-08-26 11:43:36 -070074#include "bootchart.h"
Nikita Ioffec0df1872019-11-13 21:47:06 +000075#include "builtin_arguments.h"
Paul Crowley052f31c2019-08-26 10:33:17 -070076#include "fscrypt_init_extensions.h"
Tom Cherrybac32992015-07-31 12:45:25 -070077#include "init.h"
Jiyong Park68660412019-01-16 23:00:59 +090078#include "mount_namespace.h"
Tom Cherry67dee622017-07-27 12:54:48 -070079#include "parser.h"
Tom Cherrybac32992015-07-31 12:45:25 -070080#include "property_service.h"
Keun-young Park8d01f632017-03-13 11:54:47 -070081#include "reboot.h"
Tom Cherry7ac013d2017-08-25 10:39:25 -070082#include "rlimit_parser.h"
Vic Yang92c236e2019-05-28 15:58:35 -070083#include "selabel.h"
Joel Galenson4b591f12017-11-27 14:45:26 -080084#include "selinux.h"
Tom Cherrybac32992015-07-31 12:45:25 -070085#include "service.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070086#include "service_list.h"
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070087#include "subcontext.h"
Tom Cherrybac32992015-07-31 12:45:25 -070088#include "util.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070089
Paul Crowley0b8b2302016-12-19 13:03:47 -080090using namespace std::literals::string_literals;
91
Tom Cherrycf80b6d2019-01-07 14:25:31 -080092using android::base::Basename;
Jiyong Parkd185d4a2021-12-11 10:45:20 +090093using android::base::ResultError;
Tom Cherryc88d8f92019-08-19 15:21:25 -070094using android::base::SetProperty;
Wei Wang49d25982020-11-18 15:56:14 -080095using android::base::Split;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070096using android::base::StartsWith;
Tom Cherry7896e7a2019-09-04 15:26:52 -070097using android::base::StringPrintf;
Tom Cherry70379912017-08-01 14:10:11 -070098using android::base::unique_fd;
Tom Cherrya3530e62019-01-30 13:25:35 -080099using android::fs_mgr::Fstab;
100using android::fs_mgr::ReadFstabFromFile;
Tom Cherry70379912017-08-01 14:10:11 -0700101
Nick Kralevichbc609542015-01-31 21:39:46 -0800102#define chmod DO_NOT_USE_CHMOD_USE_FCHMODAT_SYMLINK_NOFOLLOW
103
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700104namespace android {
105namespace init {
106
Tom Cherryd17c3792019-07-30 10:51:59 -0700107// There are many legacy paths in rootdir/init.rc that will virtually never exist on a new
108// device, such as '/sys/class/leds/jogball-backlight/brightness'. As of this writing, there
109// are 81 such failures on cuttlefish. Instead of spamming the log reporting them, we do not
110// report such failures unless we're running at the DEBUG log level.
111class ErrorIgnoreEnoent {
112 public:
113 ErrorIgnoreEnoent()
114 : ignore_error_(errno == ENOENT &&
115 android::base::GetMinimumLogSeverity() > android::base::DEBUG) {}
116 explicit ErrorIgnoreEnoent(int errno_to_append)
117 : error_(errno_to_append),
118 ignore_error_(errno_to_append == ENOENT &&
119 android::base::GetMinimumLogSeverity() > android::base::DEBUG) {}
120
121 template <typename T>
Jiyong Park705abe22021-12-14 22:55:34 +0900122 operator android::base::expected<T, ResultError<android::base::Errno>>() {
Tom Cherryd17c3792019-07-30 10:51:59 -0700123 if (ignore_error_) {
124 return {};
125 }
126 return error_;
127 }
128
129 template <typename T>
130 ErrorIgnoreEnoent& operator<<(T&& t) {
131 error_ << t;
132 return *this;
133 }
134
135 private:
Jiyong Parkd185d4a2021-12-11 10:45:20 +0900136 Error<> error_;
Tom Cherryd17c3792019-07-30 10:51:59 -0700137 bool ignore_error_;
138};
139
140inline ErrorIgnoreEnoent ErrnoErrorIgnoreEnoent() {
141 return ErrorIgnoreEnoent(errno);
142}
143
Tom Cherry172c83f2019-06-26 14:44:37 -0700144std::vector<std::string> late_import_paths;
145
Elliott Hughes9605a942016-11-10 17:43:47 -0800146static constexpr std::chrono::nanoseconds kCommandRetryTimeout = 5s;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800147
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700148static Result<void> reboot_into_recovery(const std::vector<std::string>& options) {
Paul Crowleyc73b2152018-04-13 17:38:57 +0000149 LOG(ERROR) << "Rebooting into recovery";
Paul Crowleyaf8be582016-05-10 08:52:06 -0700150 std::string err;
151 if (!write_bootloader_message(options, &err)) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700152 return Error() << "Failed to set bootloader message: " << err;
Paul Crowleyaf8be582016-05-10 08:52:06 -0700153 }
Tom Cherry18278d22019-11-12 16:21:20 -0800154 trigger_shutdown("reboot,recovery");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700155 return {};
Yusuke Sato0df08272015-07-08 14:57:07 -0700156}
157
Tom Cherry911b9b12017-07-27 16:20:58 -0700158template <typename F>
159static void ForEachServiceInClass(const std::string& classname, F function) {
160 for (const auto& service : ServiceList::GetInstance()) {
161 if (service->classnames().count(classname)) std::invoke(function, service);
162 }
163}
164
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700165static Result<void> do_class_start(const BuiltinArguments& args) {
Daniel Rosenbergca00b0e2018-11-27 22:08:02 -0800166 // 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 +0200167 if (android::base::GetBoolProperty("persist.init.dont_start_class." + args[1], false))
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700168 return {};
Tom Cherry911b9b12017-07-27 16:20:58 -0700169 // Starting a class does not start services which are explicitly disabled.
170 // They must be started individually.
Tom Cherry20acdef2017-10-03 13:15:03 -0700171 for (const auto& service : ServiceList::GetInstance()) {
Martijn Coenenacc45aa2019-05-15 22:04:13 +0200172 if (service->classnames().count(args[1])) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900173 if (auto result = service->StartIfNotDisabled(); !result.ok()) {
Tom Cherry20acdef2017-10-03 13:15:03 -0700174 LOG(ERROR) << "Could not start service '" << service->name()
Martijn Coenenacc45aa2019-05-15 22:04:13 +0200175 << "' as part of class '" << args[1] << "': " << result.error();
Tom Cherry20acdef2017-10-03 13:15:03 -0700176 }
177 }
178 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700179 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700180}
181
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700182static Result<void> do_class_stop(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700183 ForEachServiceInClass(args[1], &Service::Stop);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700184 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700185}
186
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700187static Result<void> do_class_reset(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700188 ForEachServiceInClass(args[1], &Service::Reset);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700189 return {};
Ken Sumrall752923c2010-12-03 16:33:31 -0800190}
191
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700192static Result<void> do_class_restart(const BuiltinArguments& args) {
Daniel Rosenbergca00b0e2018-11-27 22:08:02 -0800193 // Do not restart a class if it has a property persist.dont_start_class.CLASS set to 1.
194 if (android::base::GetBoolProperty("persist.init.dont_start_class." + args[1], false))
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700195 return {};
David Anderson2285b522021-11-09 18:26:39 -0800196
197 std::string classname;
198
199 CHECK(args.size() == 2 || args.size() == 3);
200
201 bool only_enabled = false;
202 if (args.size() == 3) {
203 if (args[1] != "--only-enabled") {
204 return Error() << "Unexpected argument: " << args[1];
205 }
206 only_enabled = true;
207 classname = args[2];
208 } else if (args.size() == 2) {
209 classname = args[1];
210 }
211
212 for (const auto& service : ServiceList::GetInstance()) {
213 if (!service->classnames().count(classname)) {
214 continue;
215 }
216 if (only_enabled && !service->IsEnabled()) {
217 continue;
218 }
219 service->Restart();
220 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700221 return {};
Steven Moreland2b63d542017-03-10 14:04:37 -0800222}
223
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700224static Result<void> do_domainname(const BuiltinArguments& args) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900225 if (auto result = WriteFile("/proc/sys/kernel/domainname", args[1]); !result.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700226 return Error() << "Unable to write to /proc/sys/kernel/domainname: " << result.error();
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700227 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700228 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700229}
230
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700231static Result<void> do_enable(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700232 Service* svc = ServiceList::GetInstance().FindService(args[1]);
Tom Cherry7fa62c52017-08-01 13:50:23 -0700233 if (!svc) return Error() << "Could not find service";
234
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900235 if (auto result = svc->Enable(); !result.ok()) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700236 return Error() << "Could not enable service: " << result.error();
237 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700238
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700239 return {};
JP Abgrall3beec7e2014-05-02 21:14:29 -0700240}
241
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700242static Result<void> do_exec(const BuiltinArguments& args) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700243 auto service = Service::MakeTemporaryOneshotService(args.args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900244 if (!service.ok()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -0700245 return Error() << "Could not create exec service: " << service.error();
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700246 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900247 if (auto result = (*service)->ExecStart(); !result.ok()) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700248 return Error() << "Could not start exec service: " << result.error();
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700249 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700250
Tom Cherry4772f1d2019-07-30 09:34:41 -0700251 ServiceList::GetInstance().AddService(std::move(*service));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700252 return {};
Tom Cherryb27004a2017-03-27 16:27:30 -0700253}
254
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700255static Result<void> do_exec_background(const BuiltinArguments& args) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700256 auto service = Service::MakeTemporaryOneshotService(args.args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900257 if (!service.ok()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -0700258 return Error() << "Could not create exec background service: " << service.error();
Tom Cherry3631c542017-09-18 12:16:27 -0700259 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900260 if (auto result = (*service)->Start(); !result.ok()) {
Tom Cherry3631c542017-09-18 12:16:27 -0700261 return Error() << "Could not start exec background service: " << result.error();
262 }
263
Tom Cherry4772f1d2019-07-30 09:34:41 -0700264 ServiceList::GetInstance().AddService(std::move(*service));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700265 return {};
Tom Cherry3631c542017-09-18 12:16:27 -0700266}
267
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700268static Result<void> do_exec_start(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700269 Service* service = ServiceList::GetInstance().FindService(args[1]);
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700270 if (!service) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700271 return Error() << "Service not found";
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700272 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700273
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900274 if (auto result = service->ExecStart(); !result.ok()) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700275 return Error() << "Could not start exec service: " << result.error();
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700276 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700277
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700278 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700279}
280
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700281static Result<void> do_export(const BuiltinArguments& args) {
Tom Cherry6de21f12017-08-22 15:41:03 -0700282 if (setenv(args[1].c_str(), args[2].c_str(), 1) == -1) {
283 return ErrnoError() << "setenv() failed";
Tom Cherry7fa62c52017-08-01 13:50:23 -0700284 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700285 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700286}
287
Artur Satayev500946b2021-02-15 20:48:49 +0000288static Result<void> do_load_exports(const BuiltinArguments& args) {
289 auto file_contents = ReadFile(args[1]);
290 if (!file_contents.ok()) {
291 return Error() << "Could not read input file '" << args[1]
292 << "': " << file_contents.error();
293 }
294
295 auto lines = Split(*file_contents, "\n");
296 for (const auto& line : lines) {
297 if (line.empty()) {
298 continue;
299 }
300
301 auto env = Split(line, " ");
302
303 if (env.size() != 3) {
304 return ErrnoError() << "Expected a line as `export <name> <value>`, found: `" << line
305 << "`";
306 }
307
308 if (env[0] != "export") {
309 return ErrnoError() << "Unknown action: '" << env[0] << "', expected 'export'";
310 }
311
312 if (setenv(env[1].c_str(), env[2].c_str(), 1) == -1) {
313 return ErrnoError() << "Failed to export '" << line << "' from " << args[1];
314 }
315 }
316
317 return {};
318}
319
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700320static Result<void> do_hostname(const BuiltinArguments& args) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900321 if (auto result = WriteFile("/proc/sys/kernel/hostname", args[1]); !result.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700322 return Error() << "Unable to write to /proc/sys/kernel/hostname: " << result.error();
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700323 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700324 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700325}
326
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700327static Result<void> do_ifup(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700328 struct ifreq ifr;
329
330 strlcpy(ifr.ifr_name, args[1].c_str(), IFNAMSIZ);
331
Tom Cherry247ffbf2019-07-08 15:09:36 -0700332 unique_fd s(TEMP_FAILURE_RETRY(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0)));
Tom Cherry7fa62c52017-08-01 13:50:23 -0700333 if (s < 0) return ErrnoError() << "opening socket failed";
334
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800335 if (ioctl(s.get(), SIOCGIFFLAGS, &ifr) < 0) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700336 return ErrnoError() << "ioctl(..., SIOCGIFFLAGS, ...) failed";
337 }
338
339 ifr.ifr_flags |= IFF_UP;
340
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800341 if (ioctl(s.get(), SIOCSIFFLAGS, &ifr) < 0) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700342 return ErrnoError() << "ioctl(..., SIOCSIFFLAGS, ...) failed";
343 }
344
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700345 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700346}
347
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700348static Result<void> do_insmod(const BuiltinArguments& args) {
Hung-ying Tyanbfa6d752016-05-17 18:49:10 +0800349 int flags = 0;
350 auto it = args.begin() + 1;
The Android Open Source Project35237d12008-12-17 18:08:08 -0800351
Hung-ying Tyanbfa6d752016-05-17 18:49:10 +0800352 if (!(*it).compare("-f")) {
353 flags = MODULE_INIT_IGNORE_VERMAGIC | MODULE_INIT_IGNORE_MODVERSIONS;
354 it++;
The Android Open Source Project35237d12008-12-17 18:08:08 -0800355 }
356
Hung-ying Tyanbfa6d752016-05-17 18:49:10 +0800357 std::string filename = *it++;
358 std::string options = android::base::Join(std::vector<std::string>(it, args.end()), ' ');
Tom Cherry7fa62c52017-08-01 13:50:23 -0700359
360 unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
361 if (fd == -1) return ErrnoError() << "open(\"" << filename << "\") failed";
362
363 int rc = syscall(__NR_finit_module, fd.get(), options.c_str(), flags);
364 if (rc == -1) return ErrnoError() << "finit_module for \"" << filename << "\" failed";
365
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700366 return {};
The Android Open Source Project35237d12008-12-17 18:08:08 -0800367}
368
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700369static Result<void> do_interface_restart(const BuiltinArguments& args) {
Steven Moreland612d7a42018-05-08 11:21:37 -0700370 Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
371 if (!svc) return Error() << "interface " << args[1] << " not found";
372 svc->Restart();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700373 return {};
Steven Moreland612d7a42018-05-08 11:21:37 -0700374}
375
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700376static Result<void> do_interface_start(const BuiltinArguments& args) {
Steven Moreland612d7a42018-05-08 11:21:37 -0700377 Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
378 if (!svc) return Error() << "interface " << args[1] << " not found";
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900379 if (auto result = svc->Start(); !result.ok()) {
Steven Moreland612d7a42018-05-08 11:21:37 -0700380 return Error() << "Could not start interface: " << result.error();
381 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700382 return {};
Steven Moreland612d7a42018-05-08 11:21:37 -0700383}
384
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700385static Result<void> do_interface_stop(const BuiltinArguments& args) {
Steven Moreland612d7a42018-05-08 11:21:37 -0700386 Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
387 if (!svc) return Error() << "interface " << args[1] << " not found";
388 svc->Stop();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700389 return {};
Steven Moreland612d7a42018-05-08 11:21:37 -0700390}
391
Oli Lan13e51e72019-11-19 18:08:45 +0000392static Result<void> make_dir_with_options(const MkdirOptions& options) {
Paul Crowley68258e82019-10-28 07:55:03 -0700393 std::string ref_basename;
Oli Lan13e51e72019-11-19 18:08:45 +0000394 if (options.ref_option == "ref") {
Paul Crowley68258e82019-10-28 07:55:03 -0700395 ref_basename = fscrypt_key_ref;
Oli Lan13e51e72019-11-19 18:08:45 +0000396 } else if (options.ref_option == "per_boot_ref") {
Paul Crowley68258e82019-10-28 07:55:03 -0700397 ref_basename = fscrypt_key_per_boot_ref;
398 } else {
Oli Lan13e51e72019-11-19 18:08:45 +0000399 return Error() << "Unknown key option: '" << options.ref_option << "'";
Paul Crowley1b4e7322019-08-25 12:18:43 -0700400 }
Paul Crowley68258e82019-10-28 07:55:03 -0700401
Paul Crowley1b4e7322019-08-25 12:18:43 -0700402 struct stat mstat;
Oli Lan13e51e72019-11-19 18:08:45 +0000403 if (lstat(options.target.c_str(), &mstat) != 0) {
Paul Crowley1b4e7322019-08-25 12:18:43 -0700404 if (errno != ENOENT) {
Oli Lan13e51e72019-11-19 18:08:45 +0000405 return ErrnoError() << "lstat() failed on " << options.target;
Paul Crowley1b4e7322019-08-25 12:18:43 -0700406 }
Oli Lan13e51e72019-11-19 18:08:45 +0000407 if (!make_dir(options.target, options.mode)) {
408 return ErrnoErrorIgnoreEnoent() << "mkdir() failed on " << options.target;
Paul Crowley1b4e7322019-08-25 12:18:43 -0700409 }
Oli Lan13e51e72019-11-19 18:08:45 +0000410 if (lstat(options.target.c_str(), &mstat) != 0) {
411 return ErrnoError() << "lstat() failed on new " << options.target;
Benoit Goby5c8574b2012-08-14 15:43:46 -0700412 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700413 }
Paul Crowley1b4e7322019-08-25 12:18:43 -0700414 if (!S_ISDIR(mstat.st_mode)) {
Oli Lan13e51e72019-11-19 18:08:45 +0000415 return Error() << "Not a directory on " << options.target;
Paul Crowley1b4e7322019-08-25 12:18:43 -0700416 }
Oli Lan13e51e72019-11-19 18:08:45 +0000417 bool needs_chmod = (mstat.st_mode & ~S_IFMT) != options.mode;
418 if ((options.uid != static_cast<uid_t>(-1) && options.uid != mstat.st_uid) ||
419 (options.gid != static_cast<gid_t>(-1) && options.gid != mstat.st_gid)) {
420 if (lchown(options.target.c_str(), options.uid, options.gid) == -1) {
421 return ErrnoError() << "lchown failed on " << options.target;
Paul Crowley1b4e7322019-08-25 12:18:43 -0700422 }
423 // chown may have cleared S_ISUID and S_ISGID, chmod again
424 needs_chmod = true;
425 }
426 if (needs_chmod) {
Oli Lan13e51e72019-11-19 18:08:45 +0000427 if (fchmodat(AT_FDCWD, options.target.c_str(), options.mode, AT_SYMLINK_NOFOLLOW) == -1) {
428 return ErrnoError() << "fchmodat() failed on " << options.target;
Paul Crowley1b4e7322019-08-25 12:18:43 -0700429 }
430 }
Eric Biggers893b1ae2022-06-15 18:52:39 +0000431 if (IsFbeEnabled()) {
Oli Lan13e51e72019-11-19 18:08:45 +0000432 if (!FscryptSetDirectoryPolicy(ref_basename, options.fscrypt_action, options.target)) {
Paul Crowleyc73b2152018-04-13 17:38:57 +0000433 return reboot_into_recovery(
Oli Lan13e51e72019-11-19 18:08:45 +0000434 {"--prompt_and_wipe_data", "--reason=set_policy_failed:"s + options.target});
Paul Crowleyaf8be582016-05-10 08:52:06 -0700435 }
436 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700437 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700438}
439
Oli Lan13e51e72019-11-19 18:08:45 +0000440// mkdir <path> [mode] [owner] [group] [<option> ...]
441static Result<void> do_mkdir(const BuiltinArguments& args) {
442 auto options = ParseMkdir(args.args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900443 if (!options.ok()) return options.error();
Oli Lan13e51e72019-11-19 18:08:45 +0000444 return make_dir_with_options(*options);
445}
446
Alex Light68ab20f2016-06-23 11:11:39 -0700447/* umount <path> */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700448static Result<void> do_umount(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700449 if (umount(args[1].c_str()) < 0) {
450 return ErrnoError() << "umount() failed";
451 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700452 return {};
Alex Light68ab20f2016-06-23 11:11:39 -0700453}
454
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700455static struct {
456 const char *name;
457 unsigned flag;
458} mount_flags[] = {
459 { "noatime", MS_NOATIME },
Lars Svenssonb6ee25e2011-07-14 13:39:09 +0200460 { "noexec", MS_NOEXEC },
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700461 { "nosuid", MS_NOSUID },
462 { "nodev", MS_NODEV },
463 { "nodiratime", MS_NODIRATIME },
464 { "ro", MS_RDONLY },
465 { "rw", 0 },
466 { "remount", MS_REMOUNT },
Jeff Sharkeye50ac5f2012-08-14 11:34:34 -0700467 { "bind", MS_BIND },
468 { "rec", MS_REC },
469 { "unbindable", MS_UNBINDABLE },
470 { "private", MS_PRIVATE },
471 { "slave", MS_SLAVE },
472 { "shared", MS_SHARED },
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700473 { "defaults", 0 },
474 { 0, 0 },
475};
476
477/* mount <type> <device> <path> <flags ...> <options> */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700478static Result<void> do_mount(const BuiltinArguments& args) {
Tom Cherry70379912017-08-01 14:10:11 -0700479 const char* options = nullptr;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700480 unsigned flags = 0;
Tom Cherry70379912017-08-01 14:10:11 -0700481 bool wait = false;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700482
Tom Cherry70379912017-08-01 14:10:11 -0700483 for (size_t na = 4; na < args.size(); na++) {
484 size_t i;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700485 for (i = 0; mount_flags[i].name; i++) {
Tom Cherry96f67312015-07-30 13:52:55 -0700486 if (!args[na].compare(mount_flags[i].name)) {
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700487 flags |= mount_flags[i].flag;
488 break;
489 }
490 }
491
Colin Crosscd0f1732010-04-19 17:10:24 -0700492 if (!mount_flags[i].name) {
Tom Cherry70379912017-08-01 14:10:11 -0700493 if (!args[na].compare("wait")) {
494 wait = true;
495 // If our last argument isn't a flag, wolf it up as an option string.
496 } else if (na + 1 == args.size()) {
Tom Cherry96f67312015-07-30 13:52:55 -0700497 options = args[na].c_str();
Tom Cherry70379912017-08-01 14:10:11 -0700498 }
Colin Crosscd0f1732010-04-19 17:10:24 -0700499 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700500 }
501
Tom Cherry70379912017-08-01 14:10:11 -0700502 const char* system = args[1].c_str();
503 const char* source = args[2].c_str();
504 const char* target = args[3].c_str();
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000505
Tom Cherry70379912017-08-01 14:10:11 -0700506 if (android::base::StartsWith(source, "loop@")) {
507 int mode = (flags & MS_RDONLY) ? O_RDONLY : O_RDWR;
tangjie12b26bdf2023-04-13 17:15:23 +0800508 const char* file_path = source + strlen("loop@");
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000509
tangjie12b26bdf2023-04-13 17:15:23 +0800510 // Open source file
511 if (wait) {
512 wait_for_file(file_path, kCommandRetryTimeout);
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000513 }
514
tangjie12b26bdf2023-04-13 17:15:23 +0800515 unique_fd fd(TEMP_FAILURE_RETRY(open(file_path, mode | O_CLOEXEC)));
516 if (fd < 0) {
517 return ErrnoError() << "open(" << file_path << ", " << mode << ") failed";
518 }
519
520 // Allocate loop device and attach it to file_path.
521 android::dm::LoopControl loop_control;
522 std::string loop_device;
523 if (!loop_control.Attach(fd.get(), 5s, &loop_device)) {
524 return ErrnoError() << "loop_control.Attach " << file_path << " failed";
525 }
526
527 if (mount(loop_device.c_str(), target, system, flags, options) < 0) {
528 loop_control.Detach(loop_device);
529 return ErrnoError() << "mount() failed";
530 }
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000531 } else {
Colin Crosscd0f1732010-04-19 17:10:24 -0700532 if (wait)
Elliott Hughes9605a942016-11-10 17:43:47 -0800533 wait_for_file(source, kCommandRetryTimeout);
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000534 if (mount(source, target, system, flags, options) < 0) {
Tom Cherryd17c3792019-07-30 10:51:59 -0700535 return ErrnoErrorIgnoreEnoent() << "mount() failed";
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000536 }
537
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700538 }
Ken Sumralldd4d7862011-02-17 18:09:47 -0800539
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700540 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700541}
542
Hung-ying Tyandc738ea2016-01-14 11:18:21 +0800543/* Imports .rc files from the specified paths. Default ones are applied if none is given.
544 *
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700545 * rc_paths: list of paths to rc files to import
Hung-ying Tyandc738ea2016-01-14 11:18:21 +0800546 */
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700547static void import_late(const std::vector<std::string>& rc_paths) {
Tom Cherry67dee622017-07-27 12:54:48 -0700548 auto& action_manager = ActionManager::GetInstance();
Tom Cherry911b9b12017-07-27 16:20:58 -0700549 auto& service_list = ServiceList::GetInstance();
550 Parser parser = CreateParser(action_manager, service_list);
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700551 if (rc_paths.empty()) {
Jaekyun Seok4ec72cc2017-02-22 20:37:57 +0900552 // Fallbacks for partitions on which early mount isn't enabled.
Tom Cherry67dee622017-07-27 12:54:48 -0700553 for (const auto& path : late_import_paths) {
554 parser.ParseConfig(path);
Jaekyun Seok4ec72cc2017-02-22 20:37:57 +0900555 }
Tom Cherry67dee622017-07-27 12:54:48 -0700556 late_import_paths.clear();
Hung-ying Tyandc738ea2016-01-14 11:18:21 +0800557 } else {
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700558 for (const auto& rc_path : rc_paths) {
559 parser.ParseConfig(rc_path);
Hung-ying Tyandc738ea2016-01-14 11:18:21 +0800560 }
Tom Cherryb8dd0272015-07-22 14:23:33 -0700561 }
Tom Cherryd8a72572017-03-13 12:24:49 -0700562
563 // Turning this on and letting the INFO logging be discarded adds 0.2s to
564 // Nexus 9 boot time, so it's disabled by default.
Tom Cherry30a6f272017-04-19 15:31:58 -0700565 if (false) DumpState();
Tom Cherryb8dd0272015-07-22 14:23:33 -0700566}
567
Wei Wangd61a7e22016-08-23 11:58:09 -0700568/* Queue event based on fs_mgr return code.
569 *
570 * code: return code of fs_mgr_mount_all
571 *
572 * This function might request a reboot, in which case it will
573 * not return.
574 *
575 * return code is processed based on input code
576 */
Eric Biggersab74dbb2023-07-10 17:58:33 +0000577static Result<void> queue_fs_event(int code) {
Eric Biggerse5b5e372021-11-08 16:38:54 -0800578 if (code == FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700579 SetProperty("ro.crypto.state", "unsupported");
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700580 ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700581 return {};
Wei Wangd61a7e22016-08-23 11:58:09 -0700582 } else if (code == FS_MGR_MNTALL_DEV_NEEDS_RECOVERY) {
JP Abgrallcee20682014-07-02 14:26:54 -0700583 /* Setup a wipe via recovery, and reboot into recovery */
David Anderson0e330f12019-01-03 18:16:56 -0800584 if (android::gsi::IsGsiRunning()) {
585 return Error() << "cannot wipe within GSI";
586 }
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700587 PLOG(ERROR) << "fs_mgr_mount_all suggested recovery, so wiping data via recovery.";
Paul Crowley0b8b2302016-12-19 13:03:47 -0800588 const std::vector<std::string> options = {"--wipe_data", "--reason=fs_mgr_mount_all" };
Paul Crowleyc73b2152018-04-13 17:38:57 +0000589 return reboot_into_recovery(options);
JP Abgrallcee20682014-07-02 14:26:54 -0700590 /* If reboot worked, there is no return. */
Eric Biggersab74dbb2023-07-10 17:58:33 +0000591 } else if (code == FS_MGR_MNTALL_DEV_FILE_ENCRYPTED ||
592 code == FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED ||
593 code == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700594 SetProperty("ro.crypto.state", "encrypted");
Paul Lawrence9dbe97b2017-04-21 12:41:48 -0700595
Paul Crowleyc6846962018-01-30 09:56:03 -0800596 // Although encrypted, vold has already set the device up, so we do not need to
597 // do anything different from the nonencrypted case.
598 ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700599 return {};
Wei Wangd61a7e22016-08-23 11:58:09 -0700600 } else if (code > 0) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700601 Error() << "fs_mgr_mount_all() returned unexpected error " << code;
Ken Sumrall0e9dd902012-04-17 17:20:16 -0700602 }
JP Abgrallf22b7452014-07-02 13:16:04 -0700603 /* else ... < 0: error */
Ken Sumrall0e9dd902012-04-17 17:20:16 -0700604
Tom Cherry7fa62c52017-08-01 13:50:23 -0700605 return Error() << "Invalid code: " << code;
Ken Sumrall0e9dd902012-04-17 17:20:16 -0700606}
607
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700608/* <= Q: mount_all <fstab> [ <path> ]* [--<options>]*
609 * >= R: mount_all [ <fstab> ] [--<options>]*
Wei Wangd61a7e22016-08-23 11:58:09 -0700610 *
611 * This function might request a reboot, in which case it will
612 * not return.
613 */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700614static Result<void> do_mount_all(const BuiltinArguments& args) {
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700615 auto mount_all = ParseMountAll(args.args);
616 if (!mount_all.ok()) return mount_all.error();
Wei Wangd61a7e22016-08-23 11:58:09 -0700617
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700618 const char* prop_post_fix = "default";
619 bool queue_event = true;
620 if (mount_all->mode == MOUNT_MODE_EARLY) {
621 prop_post_fix = "early";
622 queue_event = false;
623 } else if (mount_all->mode == MOUNT_MODE_LATE) {
624 prop_post_fix = "late";
Wei Wangd61a7e22016-08-23 11:58:09 -0700625 }
626
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700627 std::string prop_name = "ro.boottime.init.mount_all."s + prop_post_fix;
Tom Cherryede0d532017-07-06 14:20:11 -0700628 android::base::Timer t;
Tom Cherry990483d2019-04-17 12:55:50 -0700629
630 Fstab fstab;
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700631 if (mount_all->fstab_path.empty()) {
632 if (!ReadDefaultFstab(&fstab)) {
633 return Error() << "Could not read default fstab";
634 }
635 } else {
636 if (!ReadFstabFromFile(mount_all->fstab_path, &fstab)) {
637 return Error() << "Could not read fstab";
638 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700639 }
Nikita Ioffe12a36072019-10-23 20:11:32 +0100640
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +0100641 auto mount_fstab_result = fs_mgr_mount_all(&fstab, mount_all->mode);
Tom Cherryc88d8f92019-08-19 15:21:25 -0700642 SetProperty(prop_name, std::to_string(t.duration().count()));
Wei Wangd61a7e22016-08-23 11:58:09 -0700643
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700644 if (mount_all->import_rc) {
645 import_late(mount_all->rc_paths);
Wei Wangd61a7e22016-08-23 11:58:09 -0700646 }
647
648 if (queue_event) {
649 /* queue_fs_event will queue event based on mount_fstab return code
650 * and return processed return code*/
Jooyung Hane34549a2024-08-09 15:58:53 +0900651 auto queue_fs_result = queue_fs_event(mount_fstab_result);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900652 if (!queue_fs_result.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700653 return Error() << "queue_fs_event() failed: " << queue_fs_result.error();
654 }
Wei Wangd61a7e22016-08-23 11:58:09 -0700655 }
656
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700657 return {};
Wei Wangd61a7e22016-08-23 11:58:09 -0700658}
659
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700660/* umount_all [ <fstab> ] */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700661static Result<void> do_umount_all(const BuiltinArguments& args) {
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700662 auto umount_all = ParseUmountAll(args.args);
663 if (!umount_all.ok()) return umount_all.error();
664
Tom Cherry990483d2019-04-17 12:55:50 -0700665 Fstab fstab;
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700666 if (umount_all->empty()) {
667 if (!ReadDefaultFstab(&fstab)) {
668 return Error() << "Could not read default fstab";
669 }
670 } else {
671 if (!ReadFstabFromFile(*umount_all, &fstab)) {
672 return Error() << "Could not read fstab";
673 }
Tom Cherry990483d2019-04-17 12:55:50 -0700674 }
675
Tom Cherry3707d322019-08-15 13:07:24 -0700676 if (auto result = fs_mgr_umount_all(&fstab); result != 0) {
677 return Error() << "umount_fstab() failed " << result;
Yifan Hong402633d2019-04-09 10:11:34 -0700678 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700679 return {};
Yifan Hong402633d2019-04-09 10:11:34 -0700680}
681
Alistair Delvade28a862020-06-08 11:04:53 -0700682/* swapon_all [ <fstab> ] */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700683static Result<void> do_swapon_all(const BuiltinArguments& args) {
Alistair Delvade28a862020-06-08 11:04:53 -0700684 auto swapon_all = ParseSwaponAll(args.args);
685 if (!swapon_all.ok()) return swapon_all.error();
686
Tom Cherry30554572018-11-30 15:21:04 -0800687 Fstab fstab;
Alistair Delvade28a862020-06-08 11:04:53 -0700688 if (swapon_all->empty()) {
689 if (!ReadDefaultFstab(&fstab)) {
690 return Error() << "Could not read default fstab";
691 }
692 } else {
693 if (!ReadFstabFromFile(*swapon_all, &fstab)) {
694 return Error() << "Could not read fstab '" << *swapon_all << "'";
695 }
Tom Cherry30554572018-11-30 15:21:04 -0800696 }
Ken Sumralla76baaa2013-07-09 18:42:09 -0700697
Tom Cherry3707d322019-08-15 13:07:24 -0700698 if (!fs_mgr_swapon_all(fstab)) {
699 return Error() << "fs_mgr_swapon_all() failed";
Tom Cherry30554572018-11-30 15:21:04 -0800700 }
Ken Sumralla76baaa2013-07-09 18:42:09 -0700701
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700702 return {};
Ken Sumralla76baaa2013-07-09 18:42:09 -0700703}
704
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700705static Result<void> do_setprop(const BuiltinArguments& args) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700706 if (StartsWith(args[1], "ctl.")) {
707 return Error()
708 << "Cannot set ctl. properties from init; call the Service functions directly";
709 }
710 if (args[1] == kRestoreconProperty) {
711 return Error() << "Cannot set '" << kRestoreconProperty
712 << "' from init; use the restorecon builtin directly";
713 }
714
Tom Cherryc88d8f92019-08-19 15:21:25 -0700715 SetProperty(args[1], args[2]);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700716 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700717}
718
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700719static Result<void> do_setrlimit(const BuiltinArguments& args) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700720 auto rlimit = ParseRlimit(args.args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900721 if (!rlimit.ok()) return rlimit.error();
Tom Cherry7fa62c52017-08-01 13:50:23 -0700722
Tom Cherry7ac013d2017-08-25 10:39:25 -0700723 if (setrlimit(rlimit->first, &rlimit->second) == -1) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700724 return ErrnoError() << "setrlimit failed";
725 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700726 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700727}
728
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700729static Result<void> do_start(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700730 Service* svc = ServiceList::GetInstance().FindService(args[1]);
Tom Cherry7fa62c52017-08-01 13:50:23 -0700731 if (!svc) return Error() << "service " << args[1] << " not found";
Jooyung Hand6b65fb2023-08-22 09:59:26 +0900732 errno = 0;
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900733 if (auto result = svc->Start(); !result.ok()) {
Tom Cherryd17c3792019-07-30 10:51:59 -0700734 return ErrorIgnoreEnoent() << "Could not start service: " << result.error();
Tom Cherry76af7e62017-08-22 16:13:59 -0700735 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700736 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700737}
738
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700739static Result<void> do_stop(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700740 Service* svc = ServiceList::GetInstance().FindService(args[1]);
Tom Cherry7fa62c52017-08-01 13:50:23 -0700741 if (!svc) return Error() << "service " << args[1] << " not found";
Tom Cherrybac32992015-07-31 12:45:25 -0700742 svc->Stop();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700743 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700744}
745
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700746static Result<void> do_restart(const BuiltinArguments& args) {
David Anderson6d7c7a22021-12-03 15:48:16 -0800747 bool only_if_running = false;
748 if (args.size() == 3) {
749 if (args[1] == "--only-if-running") {
750 only_if_running = true;
751 } else {
752 return Error() << "Unknown argument to restart: " << args[1];
753 }
754 }
755
756 const auto& classname = args[args.size() - 1];
757 Service* svc = ServiceList::GetInstance().FindService(classname);
758 if (!svc) return Error() << "service " << classname << " not found";
759 if (only_if_running && !svc->IsRunning()) {
760 return {};
761 }
Tom Cherrybac32992015-07-31 12:45:25 -0700762 svc->Restart();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700763 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700764}
765
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700766static Result<void> do_trigger(const BuiltinArguments& args) {
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700767 ActionManager::GetInstance().QueueEventTrigger(args[1]);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700768 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700769}
770
Joel Galenson4b591f12017-11-27 14:45:26 -0800771static int MakeSymlink(const std::string& target, const std::string& linkpath) {
772 std::string secontext;
773 // Passing 0 for mode should work.
774 if (SelabelLookupFileContext(linkpath, 0, &secontext) && !secontext.empty()) {
775 setfscreatecon(secontext.c_str());
776 }
777
778 int rc = symlink(target.c_str(), linkpath.c_str());
779
780 if (!secontext.empty()) {
781 int save_errno = errno;
782 setfscreatecon(nullptr);
783 errno = save_errno;
784 }
785
786 return rc;
787}
788
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700789static Result<void> do_symlink(const BuiltinArguments& args) {
Joel Galenson4b591f12017-11-27 14:45:26 -0800790 if (MakeSymlink(args[1], args[2]) < 0) {
Tom Cherry68f2a462017-08-22 16:15:26 -0700791 // The symlink builtin is often used to create symlinks for older devices to be backwards
792 // compatible with new paths, therefore we skip reporting this error.
Tom Cherryd17c3792019-07-30 10:51:59 -0700793 return ErrnoErrorIgnoreEnoent() << "symlink() failed";
Elliott Hughesda46b392016-10-11 17:09:00 -0700794 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700795 return {};
The Android Open Source Project35237d12008-12-17 18:08:08 -0800796}
797
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700798static Result<void> do_rm(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700799 if (unlink(args[1].c_str()) < 0) {
800 return ErrnoError() << "unlink() failed";
801 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700802 return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -0700803}
804
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700805static Result<void> do_rmdir(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700806 if (rmdir(args[1].c_str()) < 0) {
807 return ErrnoError() << "rmdir() failed";
808 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700809 return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -0700810}
811
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700812static Result<void> do_sysclktz(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700813 struct timezone tz = {};
814 if (!android::base::ParseInt(args[1], &tz.tz_minuteswest)) {
815 return Error() << "Unable to parse mins_west_of_gmt";
816 }
817
818 if (settimeofday(nullptr, &tz) == -1) {
819 return ErrnoError() << "settimeofday() failed";
820 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700821 return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -0700822}
823
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700824static Result<void> do_verity_update_state(const BuiltinArguments& args) {
Tom Cherrycf80b6d2019-01-07 14:25:31 -0800825 int mode;
826 if (!fs_mgr_load_verity_state(&mode)) {
827 return Error() << "fs_mgr_load_verity_state() failed";
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700828 }
Tom Cherrycf80b6d2019-01-07 14:25:31 -0800829
830 Fstab fstab;
831 if (!ReadDefaultFstab(&fstab)) {
832 return Error() << "Failed to read default fstab";
833 }
834
835 for (const auto& entry : fstab) {
836 if (!fs_mgr_is_verity_enabled(entry)) {
837 continue;
838 }
839
840 // To be consistent in vboot 1.0 and vboot 2.0 (AVB), use "system" for the partition even
841 // for system as root, so it has property [partition.system.verified].
842 std::string partition = entry.mount_point == "/" ? "system" : Basename(entry.mount_point);
Tom Cherryc88d8f92019-08-19 15:21:25 -0700843 SetProperty("partition." + partition + ".verified", std::to_string(mode));
Tianjie327237d2021-01-20 19:02:34 -0800844
Tianjie10bec652021-08-30 16:10:09 -0700845 auto hashtree_info = fs_mgr_get_hashtree_info(entry);
846 if (hashtree_info) {
847 SetProperty("partition." + partition + ".verified.hash_alg", hashtree_info->algorithm);
848 SetProperty("partition." + partition + ".verified.root_digest",
849 hashtree_info->root_digest);
Nathan Huckleberry997d7382022-10-21 20:55:49 +0000850 SetProperty("partition." + partition + ".verified.check_at_most_once",
851 hashtree_info->check_at_most_once ? "1" : "0");
Tianjie327237d2021-01-20 19:02:34 -0800852 }
Tom Cherrycf80b6d2019-01-07 14:25:31 -0800853 }
854
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700855 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700856}
857
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700858static Result<void> do_write(const BuiltinArguments& args) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900859 if (auto result = WriteFile(args[1], args[2]); !result.ok()) {
Tom Cherryd17c3792019-07-30 10:51:59 -0700860 return ErrorIgnoreEnoent()
861 << "Unable to write to file '" << args[1] << "': " << result.error();
Tom Cherry7fa62c52017-08-01 13:50:23 -0700862 }
863
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700864 return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -0700865}
866
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700867static Result<void> readahead_file(const std::string& filename, bool fully) {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700868 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_CLOEXEC)));
Wei Wang02628f32017-08-16 11:34:50 -0700869 if (fd == -1) {
870 return ErrnoError() << "Error opening file";
871 }
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800872 if (posix_fadvise(fd.get(), 0, 0, POSIX_FADV_WILLNEED)) {
Wei Wang02628f32017-08-16 11:34:50 -0700873 return ErrnoError() << "Error posix_fadvise file";
874 }
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800875 if (readahead(fd.get(), 0, std::numeric_limits<size_t>::max())) {
Wei Wang02628f32017-08-16 11:34:50 -0700876 return ErrnoError() << "Error readahead file";
877 }
878 if (fully) {
879 char buf[BUFSIZ];
880 ssize_t n;
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800881 while ((n = TEMP_FAILURE_RETRY(read(fd.get(), &buf[0], sizeof(buf)))) > 0) {
Wei Wang02628f32017-08-16 11:34:50 -0700882 }
883 if (n != 0) {
884 return ErrnoError() << "Error reading file";
885 }
886 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700887 return {};
Wei Wang02628f32017-08-16 11:34:50 -0700888}
889
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700890static Result<void> do_readahead(const BuiltinArguments& args) {
Wei Wang542aae42017-08-04 13:22:36 -0700891 struct stat sb;
892
893 if (stat(args[1].c_str(), &sb)) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700894 return ErrnoError() << "Error opening " << args[1];
Wei Wang542aae42017-08-04 13:22:36 -0700895 }
896
Wei Wang02628f32017-08-16 11:34:50 -0700897 bool readfully = false;
898 if (args.size() == 3 && args[2] == "--fully") {
899 readfully = true;
900 }
Wei Wang542aae42017-08-04 13:22:36 -0700901 // We will do readahead in a forked process in order not to block init
902 // since it may block while it reads the
903 // filesystem metadata needed to locate the requested blocks. This
904 // occurs frequently with ext[234] on large files using indirect blocks
905 // instead of extents, giving the appearance that the call blocks until
906 // the requested data has been read.
907 pid_t pid = fork();
908 if (pid == 0) {
Wei Wang02628f32017-08-16 11:34:50 -0700909 if (setpriority(PRIO_PROCESS, 0, static_cast<int>(ANDROID_PRIORITY_LOWEST)) != 0) {
910 PLOG(WARNING) << "setpriority failed";
911 }
912 if (android_set_ioprio(0, IoSchedClass_IDLE, 7)) {
913 PLOG(WARNING) << "ioprio_get failed";
914 }
Wei Wang542aae42017-08-04 13:22:36 -0700915 android::base::Timer t;
916 if (S_ISREG(sb.st_mode)) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900917 if (auto result = readahead_file(args[1], readfully); !result.ok()) {
Wei Wang02628f32017-08-16 11:34:50 -0700918 LOG(WARNING) << "Unable to readahead '" << args[1] << "': " << result.error();
Wei Wang542aae42017-08-04 13:22:36 -0700919 _exit(EXIT_FAILURE);
920 }
921 } else if (S_ISDIR(sb.st_mode)) {
922 char* paths[] = {const_cast<char*>(args[1].data()), nullptr};
923 std::unique_ptr<FTS, decltype(&fts_close)> fts(
924 fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr), fts_close);
925 if (!fts) {
926 PLOG(ERROR) << "Error opening directory: " << args[1];
927 _exit(EXIT_FAILURE);
928 }
929 // Traverse the entire hierarchy and do readahead
930 for (FTSENT* ftsent = fts_read(fts.get()); ftsent != nullptr;
931 ftsent = fts_read(fts.get())) {
932 if (ftsent->fts_info & FTS_F) {
Wei Wang02628f32017-08-16 11:34:50 -0700933 const std::string filename = ftsent->fts_accpath;
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900934 if (auto result = readahead_file(filename, readfully); !result.ok()) {
Wei Wang02628f32017-08-16 11:34:50 -0700935 LOG(WARNING)
936 << "Unable to readahead '" << filename << "': " << result.error();
Wei Wang542aae42017-08-04 13:22:36 -0700937 }
938 }
939 }
940 }
Wei Wang02628f32017-08-16 11:34:50 -0700941 LOG(INFO) << "Readahead " << args[1] << " took " << t << " asynchronously";
Wei Wang542aae42017-08-04 13:22:36 -0700942 _exit(0);
943 } else if (pid < 0) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700944 return ErrnoError() << "Fork failed";
Wei Wang542aae42017-08-04 13:22:36 -0700945 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700946 return {};
Wei Wang542aae42017-08-04 13:22:36 -0700947}
948
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700949static Result<void> do_copy(const BuiltinArguments& args) {
Tom Cherry62ca6632017-08-03 12:54:07 -0700950 auto file_contents = ReadFile(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900951 if (!file_contents.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700952 return Error() << "Could not read input file '" << args[1] << "': " << file_contents.error();
San Mehat7c44fe52009-08-26 16:39:25 -0700953 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900954 if (auto result = WriteFile(args[2], *file_contents); !result.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700955 return Error() << "Could not write to output file '" << args[2] << "': " << result.error();
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700956 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700957
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700958 return {};
San Mehat7c44fe52009-08-26 16:39:25 -0700959}
960
Wei Wang49d25982020-11-18 15:56:14 -0800961static Result<void> do_copy_per_line(const BuiltinArguments& args) {
962 std::string file_contents;
963 if (!android::base::ReadFileToString(args[1], &file_contents, true)) {
964 return Error() << "Could not read input file '" << args[1] << "'";
965 }
966 auto lines = Split(file_contents, "\n");
967 for (const auto& line : lines) {
968 auto result = WriteFile(args[2], line);
969 if (!result.ok()) {
970 LOG(VERBOSE) << "Could not write to output file '" << args[2] << "' with '" << line
971 << "' : " << result.error();
972 }
973 }
974
975 return {};
976}
977
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700978static Result<void> do_chown(const BuiltinArguments& args) {
Tom Cherry62ca6632017-08-03 12:54:07 -0700979 auto uid = DecodeUid(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900980 if (!uid.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700981 return Error() << "Unable to decode UID for '" << args[1] << "': " << uid.error();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700982 }
Tom Cherry517e1f12017-05-04 17:40:33 -0700983
984 // GID is optional and pushes the index of path out by one if specified.
985 const std::string& path = (args.size() == 4) ? args[3] : args[2];
Tom Cherry62ca6632017-08-03 12:54:07 -0700986 Result<gid_t> gid = -1;
Tom Cherry517e1f12017-05-04 17:40:33 -0700987
988 if (args.size() == 4) {
Tom Cherry62ca6632017-08-03 12:54:07 -0700989 gid = DecodeUid(args[2]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900990 if (!gid.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700991 return Error() << "Unable to decode GID for '" << args[2] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700992 }
993 }
994
Tom Cherry7fa62c52017-08-01 13:50:23 -0700995 if (lchown(path.c_str(), *uid, *gid) == -1) {
Tom Cherryd17c3792019-07-30 10:51:59 -0700996 return ErrnoErrorIgnoreEnoent() << "lchown() failed";
Tom Cherry7fa62c52017-08-01 13:50:23 -0700997 }
Tom Cherry517e1f12017-05-04 17:40:33 -0700998
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700999 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001000}
1001
1002static mode_t get_mode(const char *s) {
1003 mode_t mode = 0;
1004 while (*s) {
1005 if (*s >= '0' && *s <= '7') {
1006 mode = (mode<<3) | (*s-'0');
1007 } else {
1008 return -1;
1009 }
1010 s++;
1011 }
1012 return mode;
1013}
1014
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001015static Result<void> do_chmod(const BuiltinArguments& args) {
Tom Cherry96f67312015-07-30 13:52:55 -07001016 mode_t mode = get_mode(args[1].c_str());
1017 if (fchmodat(AT_FDCWD, args[2].c_str(), mode, AT_SYMLINK_NOFOLLOW) < 0) {
Tom Cherryd17c3792019-07-30 10:51:59 -07001018 return ErrnoErrorIgnoreEnoent() << "fchmodat() failed";
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001019 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001020 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001021}
1022
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001023static Result<void> do_restorecon(const BuiltinArguments& args) {
Tom Cherry4772f1d2019-07-30 09:34:41 -07001024 auto restorecon_info = ParseRestorecon(args.args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001025 if (!restorecon_info.ok()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -07001026 return restorecon_info.error();
1027 }
1028
1029 const auto& [flag, paths] = *restorecon_info;
1030
Stephen Smalley726e8f72013-10-09 16:02:09 -04001031 int ret = 0;
Tom Cherry4772f1d2019-07-30 09:34:41 -07001032 for (const auto& path : paths) {
1033 if (selinux_android_restorecon(path.c_str(), flag) < 0) {
1034 ret = errno;
Paul Lawrencea8d84342016-11-14 15:40:18 -08001035 }
Stephen Smalleye46f9d52012-01-13 08:48:47 -05001036 }
Tom Cherry7fa62c52017-08-01 13:50:23 -07001037
Tom Cherryd17c3792019-07-30 10:51:59 -07001038 if (ret) return ErrnoErrorIgnoreEnoent() << "selinux_android_restorecon() failed";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001039 return {};
Stephen Smalley726e8f72013-10-09 16:02:09 -04001040}
1041
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001042static Result<void> do_restorecon_recursive(const BuiltinArguments& args) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001043 std::vector<std::string> non_const_args(args.args);
Paul Lawrencea8d84342016-11-14 15:40:18 -08001044 non_const_args.insert(std::next(non_const_args.begin()), "--recursive");
Bart Van Assche3dfb8bc2023-02-22 10:01:33 -08001045 return do_restorecon({.args = std::move(non_const_args), .context = args.context});
Stephen Smalleye46f9d52012-01-13 08:48:47 -05001046}
1047
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001048static Result<void> do_loglevel(const BuiltinArguments& args) {
Elliott Hughes7bc87a52016-08-04 16:09:39 -07001049 // TODO: support names instead/as well?
Elliott Hughesda46b392016-10-11 17:09:00 -07001050 int log_level = -1;
1051 android::base::ParseInt(args[1], &log_level);
Elliott Hughes7bc87a52016-08-04 16:09:39 -07001052 android::base::LogSeverity severity;
1053 switch (log_level) {
1054 case 7: severity = android::base::DEBUG; break;
1055 case 6: severity = android::base::INFO; break;
1056 case 5:
1057 case 4: severity = android::base::WARNING; break;
1058 case 3: severity = android::base::ERROR; break;
1059 case 2:
1060 case 1:
1061 case 0: severity = android::base::FATAL; break;
1062 default:
Tom Cherry7fa62c52017-08-01 13:50:23 -07001063 return Error() << "invalid log level " << log_level;
Riley Andrews1bbef882014-06-26 13:55:03 -07001064 }
Elliott Hughes7bc87a52016-08-04 16:09:39 -07001065 android::base::SetMinimumLogSeverity(severity);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001066 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001067}
1068
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001069static Result<void> do_load_persist_props(const BuiltinArguments& args) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001070 SendLoadPersistentPropertiesMessage();
1071
1072 start_waiting_for_property("ro.persistent_properties.ready", "true");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001073 return {};
Ken Sumrallc5c51032011-03-08 17:01:29 -08001074}
1075
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001076static Result<void> do_load_system_props(const BuiltinArguments& args) {
Jiyong Park3b316ee2019-01-13 02:42:31 +09001077 LOG(INFO) << "deprecated action `load_system_props` called.";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001078 return {};
Riley Andrewse4b7b292014-06-16 15:06:21 -07001079}
1080
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001081static Result<void> do_wait(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001082 auto timeout = kCommandRetryTimeout;
1083 if (args.size() == 3) {
Mark Salyzynffa52e92020-05-14 09:20:30 -07001084 double timeout_double;
1085 if (!android::base::ParseDouble(args[2], &timeout_double, 0)) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001086 return Error() << "failed to parse timeout";
Elliott Hughesda46b392016-10-11 17:09:00 -07001087 }
Mark Salyzynffa52e92020-05-14 09:20:30 -07001088 timeout = std::chrono::duration_cast<std::chrono::nanoseconds>(
1089 std::chrono::duration<double>(timeout_double));
Elliott Hughesda46b392016-10-11 17:09:00 -07001090 }
Tom Cherry7fa62c52017-08-01 13:50:23 -07001091
1092 if (wait_for_file(args[1].c_str(), timeout) != 0) {
1093 return Error() << "wait_for_file() failed";
1094 }
1095
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001096 return {};
Colin Crosscd0f1732010-04-19 17:10:24 -07001097}
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001098
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001099static Result<void> do_wait_for_prop(const BuiltinArguments& args) {
Wei Wang132ac312017-01-25 16:27:03 -08001100 const char* name = args[1].c_str();
1101 const char* value = args[2].c_str();
1102 size_t value_len = strlen(value);
1103
Tom Cherryde6bd502018-02-13 16:50:08 -08001104 if (!IsLegalPropertyName(name)) {
1105 return Error() << "IsLegalPropertyName(" << name << ") failed";
Wei Wang132ac312017-01-25 16:27:03 -08001106 }
1107 if (value_len >= PROP_VALUE_MAX) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001108 return Error() << "value too long";
Wei Wang132ac312017-01-25 16:27:03 -08001109 }
Wei Wang2d0fdaa2017-02-02 10:52:39 -08001110 if (!start_waiting_for_property(name, value)) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001111 return Error() << "already waiting for a property";
Wei Wang132ac312017-01-25 16:27:03 -08001112 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001113 return {};
Wei Wang132ac312017-01-25 16:27:03 -08001114}
1115
Paul Crowley749af8c2015-05-28 17:35:06 +01001116static bool is_file_crypto() {
Tom Cherryccf23532017-03-28 16:40:41 -07001117 return android::base::GetProperty("ro.crypto.type", "") == "file";
Paul Crowley749af8c2015-05-28 17:35:06 +01001118}
1119
Tom Cherry7896e7a2019-09-04 15:26:52 -07001120static Result<void> ExecWithFunctionOnFailure(const std::vector<std::string>& args,
1121 std::function<void(const std::string&)> function) {
1122 auto service = Service::MakeTemporaryOneshotService(args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001123 if (!service.ok()) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001124 function("MakeTemporaryOneshotService failed: " + service.error().message());
Paul Crowleyc73b2152018-04-13 17:38:57 +00001125 }
Tom Cherry7896e7a2019-09-04 15:26:52 -07001126 (*service)->AddReapCallback([function](const siginfo_t& siginfo) {
Paul Crowleyc73b2152018-04-13 17:38:57 +00001127 if (siginfo.si_code != CLD_EXITED || siginfo.si_status != 0) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001128 function(StringPrintf("Exec service failed, status %d", siginfo.si_status));
Paul Crowleyc73b2152018-04-13 17:38:57 +00001129 }
1130 });
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001131 if (auto result = (*service)->ExecStart(); !result.ok()) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001132 function("ExecStart failed: " + result.error().message());
Paul Crowleyc73b2152018-04-13 17:38:57 +00001133 }
Tom Cherry4772f1d2019-07-30 09:34:41 -07001134 ServiceList::GetInstance().AddService(std::move(*service));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001135 return {};
Paul Crowleyc73b2152018-04-13 17:38:57 +00001136}
1137
Tom Cherry7896e7a2019-09-04 15:26:52 -07001138static Result<void> ExecVdcRebootOnFailure(const std::string& vdc_arg) {
1139 auto reboot_reason = vdc_arg + "_failed";
1140
Jooyung Hanf91503b2024-08-09 16:17:20 +09001141 auto reboot = [reboot_reason](const std::string& message) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001142 // TODO (b/122850122): support this in gsi
Jooyung Hanf91503b2024-08-09 16:17:20 +09001143 if (IsFbeEnabled() && !android::gsi::IsGsiRunning()) {
1144 LOG(ERROR) << message << ": Rebooting into recovery, reason: " << reboot_reason;
1145 if (auto result = reboot_into_recovery(
1146 {"--prompt_and_wipe_data", "--reason="s + reboot_reason});
1147 !result.ok()) {
1148 LOG(FATAL) << "Could not reboot into recovery: " << result.error();
Tom Cherry7896e7a2019-09-04 15:26:52 -07001149 }
1150 } else {
Jooyung Hanf91503b2024-08-09 16:17:20 +09001151 LOG(ERROR) << "Failure (reboot suppressed): " << reboot_reason;
Tom Cherry7896e7a2019-09-04 15:26:52 -07001152 }
1153 };
1154
1155 std::vector<std::string> args = {"exec", "/system/bin/vdc", "--wait", "cryptfs", vdc_arg};
1156 return ExecWithFunctionOnFailure(args, reboot);
1157}
1158
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001159static Result<void> do_installkey(const BuiltinArguments& args) {
1160 if (!is_file_crypto()) return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -07001161
Eric Biggersf05da4a2018-10-23 13:10:33 -07001162 auto unencrypted_dir = args[1] + fscrypt_unencrypted_folder;
Tom Cherryc3692b32017-08-10 12:22:44 -07001163 if (!make_dir(unencrypted_dir, 0700) && errno != EEXIST) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001164 return ErrnoError() << "Failed to create " << unencrypted_dir;
Janis Danisevskis9cc51722017-03-29 14:50:01 -07001165 }
Tom Cherry7896e7a2019-09-04 15:26:52 -07001166 return ExecVdcRebootOnFailure("enablefilecrypto");
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001167}
Paul Crowley749af8c2015-05-28 17:35:06 +01001168
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001169static Result<void> do_init_user0(const BuiltinArguments& args) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001170 return ExecVdcRebootOnFailure("init_user0");
Paul Crowley59497452016-02-01 16:37:13 +00001171}
1172
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001173static Result<void> do_mark_post_data(const BuiltinArguments& args) {
Jooyung Han148f6022024-08-19 14:29:04 +09001174 LOG(INFO) << "deprecated action `mark_post_data` called.";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001175 return {};
Martijn Coenen70788f92019-04-23 16:26:01 +02001176}
1177
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001178static Result<void> GenerateLinkerConfiguration() {
Kiyoung Kim03b9bca2020-11-30 14:49:36 +09001179 const char* linkerconfig_binary = "/apex/com.android.runtime/bin/linkerconfig";
Kiyoung Kim3b2dbe92019-12-30 18:44:41 +09001180 const char* linkerconfig_target = "/linkerconfig";
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001181 const char* arguments[] = {linkerconfig_binary, "--target", linkerconfig_target};
1182
1183 if (logwrap_fork_execvp(arraysize(arguments), arguments, nullptr, false, LOG_KLOG, false,
1184 nullptr) != 0) {
1185 return ErrnoError() << "failed to execute linkerconfig";
1186 }
1187
Kiyoung Kim0cbee0d2021-03-02 16:45:27 +09001188 auto current_mount_ns = GetCurrentMountNamespace();
1189 if (!current_mount_ns.ok()) {
1190 return current_mount_ns.error();
1191 }
1192 if (*current_mount_ns == NS_DEFAULT) {
1193 SetDefaultMountNamespaceReady();
1194 }
1195
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001196 LOG(INFO) << "linkerconfig generated " << linkerconfig_target
1197 << " with mounted APEX modules info";
1198
1199 return {};
1200}
1201
Jooyung Han4f23d5a2020-06-09 13:44:17 +09001202static Result<void> MountLinkerConfigForDefaultNamespace() {
1203 // No need to mount linkerconfig for default mount namespace if the path does not exist (which
1204 // would mean it is already mounted)
1205 if (access("/linkerconfig/default", 0) != 0) {
1206 return {};
1207 }
1208
1209 if (mount("/linkerconfig/default", "/linkerconfig", nullptr, MS_BIND | MS_REC, nullptr) != 0) {
1210 return ErrnoError() << "Failed to mount linker configuration for default mount namespace.";
1211 }
1212
1213 return {};
1214}
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001215static Result<void> do_update_linker_config(const BuiltinArguments&) {
Shikha Malhotra720694d2021-07-30 12:35:27 +00001216 return GenerateLinkerConfiguration();
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001217}
1218
Oli Lan13e51e72019-11-19 18:08:45 +00001219/*
1220 * Creates a directory under /data/misc/apexdata/ for each APEX.
1221 */
Jooyung Han2982f092023-08-11 14:14:37 +09001222static void create_apex_data_dirs() {
1223 for (const auto& name : GetApexListFrom("/apex")) {
1224 auto path = "/data/misc/apexdata/" + name;
Oli Lan90c523b2020-01-17 11:41:04 +00001225 auto options = MkdirOptions{path, 0771, AID_ROOT, AID_SYSTEM, FscryptAction::kNone, "ref"};
Jooyung Han2982f092023-08-11 14:14:37 +09001226 auto result = make_dir_with_options(options);
1227 if (!result.ok()) {
1228 LOG(ERROR) << result.error();
1229 }
Oli Lan13e51e72019-11-19 18:08:45 +00001230 }
Oli Lan13e51e72019-11-19 18:08:45 +00001231}
1232
1233static Result<void> do_perform_apex_config(const BuiltinArguments& args) {
Jooyung Han5c4217c2023-08-10 13:12:53 +09001234 bool bootstrap = false;
1235 if (args.size() == 2) {
1236 if (args[1] != "--bootstrap") {
1237 return Error() << "Unexpected argument: " << args[1];
1238 }
1239 bootstrap = true;
Oli Lan13e51e72019-11-19 18:08:45 +00001240 }
Jooyung Han5c4217c2023-08-10 13:12:53 +09001241
1242 if (!bootstrap) {
Jooyung Han2982f092023-08-11 14:14:37 +09001243 create_apex_data_dirs();
Jooyung Han5c4217c2023-08-10 13:12:53 +09001244 }
1245
Jooyung Han55ef3d62023-08-10 18:27:22 +09001246 auto parse_result = ParseRcScriptsFromAllApexes(bootstrap);
1247 if (!parse_result.ok()) {
1248 return parse_result.error();
Oli Lan13e51e72019-11-19 18:08:45 +00001249 }
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001250
1251 auto update_linker_config = do_update_linker_config(args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001252 if (!update_linker_config.ok()) {
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001253 return update_linker_config.error();
1254 }
1255
Jooyung Han5c4217c2023-08-10 13:12:53 +09001256 if (!bootstrap) {
Jooyung Han646e0012023-08-21 17:34:37 +09001257 ServiceList::GetInstance().StartDelayedServices();
Jooyung Han5c4217c2023-08-10 13:12:53 +09001258 }
Oli Lan13e51e72019-11-19 18:08:45 +00001259 return {};
1260}
1261
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001262static Result<void> do_enter_default_mount_ns(const BuiltinArguments& args) {
Jooyung Han4f23d5a2020-06-09 13:44:17 +09001263 if (auto result = SwitchToMountNamespaceIfNeeded(NS_DEFAULT); !result.ok()) {
1264 return result.error();
Jiyong Parkdcbaf9f2019-02-22 22:15:25 +09001265 }
Jooyung Han4f23d5a2020-06-09 13:44:17 +09001266 if (auto result = MountLinkerConfigForDefaultNamespace(); !result.ok()) {
1267 return result.error();
1268 }
1269 LOG(INFO) << "Switched to default mount namespace";
1270 return {};
Jiyong Parkdcbaf9f2019-02-22 22:15:25 +09001271}
1272
Tom Cherryde6bd502018-02-13 16:50:08 -08001273// Builtin-function-map start
Tom Cherryd52a5b32019-07-22 16:05:36 -07001274const BuiltinFunctionMap& GetBuiltinFunctionMap() {
Tom Cherryb7349902015-08-26 11:43:36 -07001275 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Tom Cherryb27004a2017-03-27 16:27:30 -07001276 // clang-format off
Tom Cherryd52a5b32019-07-22 16:05:36 -07001277 static const BuiltinFunctionMap builtin_functions = {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001278 {"bootchart", {1, 1, {false, do_bootchart}}},
1279 {"chmod", {2, 2, {true, do_chmod}}},
1280 {"chown", {2, 3, {true, do_chown}}},
1281 {"class_reset", {1, 1, {false, do_class_reset}}},
David Anderson2285b522021-11-09 18:26:39 -08001282 {"class_restart", {1, 2, {false, do_class_restart}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001283 {"class_start", {1, 1, {false, do_class_start}}},
1284 {"class_stop", {1, 1, {false, do_class_stop}}},
1285 {"copy", {2, 2, {true, do_copy}}},
Wei Wang49d25982020-11-18 15:56:14 -08001286 {"copy_per_line", {2, 2, {true, do_copy_per_line}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001287 {"domainname", {1, 1, {true, do_domainname}}},
1288 {"enable", {1, 1, {false, do_enable}}},
1289 {"exec", {1, kMax, {false, do_exec}}},
1290 {"exec_background", {1, kMax, {false, do_exec_background}}},
1291 {"exec_start", {1, 1, {false, do_exec_start}}},
1292 {"export", {2, 2, {false, do_export}}},
1293 {"hostname", {1, 1, {true, do_hostname}}},
1294 {"ifup", {1, 1, {true, do_ifup}}},
1295 {"init_user0", {0, 0, {false, do_init_user0}}},
1296 {"insmod", {1, kMax, {true, do_insmod}}},
1297 {"installkey", {1, 1, {false, do_installkey}}},
Steven Moreland612d7a42018-05-08 11:21:37 -07001298 {"interface_restart", {1, 1, {false, do_interface_restart}}},
1299 {"interface_start", {1, 1, {false, do_interface_start}}},
1300 {"interface_stop", {1, 1, {false, do_interface_stop}}},
Artur Satayev500946b2021-02-15 20:48:49 +00001301 {"load_exports", {1, 1, {false, do_load_exports}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001302 {"load_persist_props", {0, 0, {false, do_load_persist_props}}},
1303 {"load_system_props", {0, 0, {false, do_load_system_props}}},
1304 {"loglevel", {1, 1, {false, do_loglevel}}},
Martijn Coenen70788f92019-04-23 16:26:01 +02001305 {"mark_post_data", {0, 0, {false, do_mark_post_data}}},
Paul Crowley68258e82019-10-28 07:55:03 -07001306 {"mkdir", {1, 6, {true, do_mkdir}}},
Tom Cherry880d5662018-02-05 08:01:54 -08001307 // TODO: Do mount operations in vendor_init.
1308 // mount_all is currently too complex to run in vendor_init as it queues action triggers,
1309 // imports rc scripts, etc. It should be simplified and run in vendor_init context.
1310 // mount and umount are run in the same context as mount_all for symmetry.
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -07001311 {"mount_all", {0, kMax, {false, do_mount_all}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001312 {"mount", {3, kMax, {false, do_mount}}},
Jooyung Han5c4217c2023-08-10 13:12:53 +09001313 {"perform_apex_config", {0, 1, {false, do_perform_apex_config}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001314 {"umount", {1, 1, {false, do_umount}}},
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -07001315 {"umount_all", {0, 1, {false, do_umount_all}}},
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001316 {"update_linker_config", {0, 0, {false, do_update_linker_config}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001317 {"readahead", {1, 2, {true, do_readahead}}},
David Anderson6d7c7a22021-12-03 15:48:16 -08001318 {"restart", {1, 2, {false, do_restart}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001319 {"restorecon", {1, kMax, {true, do_restorecon}}},
1320 {"restorecon_recursive", {1, kMax, {true, do_restorecon_recursive}}},
1321 {"rm", {1, 1, {true, do_rm}}},
1322 {"rmdir", {1, 1, {true, do_rmdir}}},
Tom Cherry32228482018-01-18 16:14:25 -08001323 {"setprop", {2, 2, {true, do_setprop}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001324 {"setrlimit", {3, 3, {false, do_setrlimit}}},
1325 {"start", {1, 1, {false, do_start}}},
1326 {"stop", {1, 1, {false, do_stop}}},
Alistair Delvade28a862020-06-08 11:04:53 -07001327 {"swapon_all", {0, 1, {false, do_swapon_all}}},
Jiyong Parkdcbaf9f2019-02-22 22:15:25 +09001328 {"enter_default_mount_ns", {0, 0, {false, do_enter_default_mount_ns}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001329 {"symlink", {2, 2, {true, do_symlink}}},
1330 {"sysclktz", {1, 1, {false, do_sysclktz}}},
1331 {"trigger", {1, 1, {false, do_trigger}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001332 {"verity_update_state", {0, 0, {false, do_verity_update_state}}},
1333 {"wait", {1, 2, {true, do_wait}}},
Tom Cherryfa3e52c2017-10-17 10:43:52 -07001334 {"wait_for_prop", {2, 2, {false, do_wait_for_prop}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001335 {"write", {2, 2, {true, do_write}}},
Tom Cherryb7349902015-08-26 11:43:36 -07001336 };
Tom Cherryb27004a2017-03-27 16:27:30 -07001337 // clang-format on
Tom Cherryb7349902015-08-26 11:43:36 -07001338 return builtin_functions;
1339}
Tom Cherryde6bd502018-02-13 16:50:08 -08001340// Builtin-function-map end
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001341
1342} // namespace init
1343} // namespace android