blob: 38aed9c64c52737c2375e62dca99e6b33029fc42 [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 },
Abdelrahman Daim589afaa2024-11-21 08:13:41 -0800474 { "nosymfollow", MS_NOSYMFOLLOW },
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700475 { "defaults", 0 },
476 { 0, 0 },
477};
478
479/* mount <type> <device> <path> <flags ...> <options> */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700480static Result<void> do_mount(const BuiltinArguments& args) {
Tom Cherry70379912017-08-01 14:10:11 -0700481 const char* options = nullptr;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700482 unsigned flags = 0;
Tom Cherry70379912017-08-01 14:10:11 -0700483 bool wait = false;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700484
Tom Cherry70379912017-08-01 14:10:11 -0700485 for (size_t na = 4; na < args.size(); na++) {
486 size_t i;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700487 for (i = 0; mount_flags[i].name; i++) {
Tom Cherry96f67312015-07-30 13:52:55 -0700488 if (!args[na].compare(mount_flags[i].name)) {
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700489 flags |= mount_flags[i].flag;
490 break;
491 }
492 }
493
Colin Crosscd0f1732010-04-19 17:10:24 -0700494 if (!mount_flags[i].name) {
Tom Cherry70379912017-08-01 14:10:11 -0700495 if (!args[na].compare("wait")) {
496 wait = true;
497 // If our last argument isn't a flag, wolf it up as an option string.
498 } else if (na + 1 == args.size()) {
Tom Cherry96f67312015-07-30 13:52:55 -0700499 options = args[na].c_str();
Tom Cherry70379912017-08-01 14:10:11 -0700500 }
Colin Crosscd0f1732010-04-19 17:10:24 -0700501 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700502 }
503
Tom Cherry70379912017-08-01 14:10:11 -0700504 const char* system = args[1].c_str();
505 const char* source = args[2].c_str();
506 const char* target = args[3].c_str();
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000507
Tom Cherry70379912017-08-01 14:10:11 -0700508 if (android::base::StartsWith(source, "loop@")) {
509 int mode = (flags & MS_RDONLY) ? O_RDONLY : O_RDWR;
tangjie12b26bdf2023-04-13 17:15:23 +0800510 const char* file_path = source + strlen("loop@");
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000511
tangjie12b26bdf2023-04-13 17:15:23 +0800512 // Open source file
513 if (wait) {
514 wait_for_file(file_path, kCommandRetryTimeout);
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000515 }
516
tangjie12b26bdf2023-04-13 17:15:23 +0800517 unique_fd fd(TEMP_FAILURE_RETRY(open(file_path, mode | O_CLOEXEC)));
518 if (fd < 0) {
519 return ErrnoError() << "open(" << file_path << ", " << mode << ") failed";
520 }
521
522 // Allocate loop device and attach it to file_path.
523 android::dm::LoopControl loop_control;
524 std::string loop_device;
525 if (!loop_control.Attach(fd.get(), 5s, &loop_device)) {
526 return ErrnoError() << "loop_control.Attach " << file_path << " failed";
527 }
528
529 if (mount(loop_device.c_str(), target, system, flags, options) < 0) {
530 loop_control.Detach(loop_device);
531 return ErrnoError() << "mount() failed";
532 }
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000533 } else {
Colin Crosscd0f1732010-04-19 17:10:24 -0700534 if (wait)
Elliott Hughes9605a942016-11-10 17:43:47 -0800535 wait_for_file(source, kCommandRetryTimeout);
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000536 if (mount(source, target, system, flags, options) < 0) {
Tom Cherryd17c3792019-07-30 10:51:59 -0700537 return ErrnoErrorIgnoreEnoent() << "mount() failed";
Jay Freeman (saurik)e520d032008-11-20 03:37:30 +0000538 }
539
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700540 }
Ken Sumralldd4d7862011-02-17 18:09:47 -0800541
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700542 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700543}
544
Hung-ying Tyandc738ea2016-01-14 11:18:21 +0800545/* Imports .rc files from the specified paths. Default ones are applied if none is given.
546 *
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700547 * rc_paths: list of paths to rc files to import
Hung-ying Tyandc738ea2016-01-14 11:18:21 +0800548 */
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700549static void import_late(const std::vector<std::string>& rc_paths) {
Tom Cherry67dee622017-07-27 12:54:48 -0700550 auto& action_manager = ActionManager::GetInstance();
Tom Cherry911b9b12017-07-27 16:20:58 -0700551 auto& service_list = ServiceList::GetInstance();
552 Parser parser = CreateParser(action_manager, service_list);
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700553 if (rc_paths.empty()) {
Jaekyun Seok4ec72cc2017-02-22 20:37:57 +0900554 // Fallbacks for partitions on which early mount isn't enabled.
Tom Cherry67dee622017-07-27 12:54:48 -0700555 for (const auto& path : late_import_paths) {
556 parser.ParseConfig(path);
Jaekyun Seok4ec72cc2017-02-22 20:37:57 +0900557 }
Tom Cherry67dee622017-07-27 12:54:48 -0700558 late_import_paths.clear();
Hung-ying Tyandc738ea2016-01-14 11:18:21 +0800559 } else {
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700560 for (const auto& rc_path : rc_paths) {
561 parser.ParseConfig(rc_path);
Hung-ying Tyandc738ea2016-01-14 11:18:21 +0800562 }
Tom Cherryb8dd0272015-07-22 14:23:33 -0700563 }
Tom Cherryd8a72572017-03-13 12:24:49 -0700564
565 // Turning this on and letting the INFO logging be discarded adds 0.2s to
566 // Nexus 9 boot time, so it's disabled by default.
Tom Cherry30a6f272017-04-19 15:31:58 -0700567 if (false) DumpState();
Tom Cherryb8dd0272015-07-22 14:23:33 -0700568}
569
Wei Wangd61a7e22016-08-23 11:58:09 -0700570/* Queue event based on fs_mgr return code.
571 *
572 * code: return code of fs_mgr_mount_all
573 *
574 * This function might request a reboot, in which case it will
575 * not return.
576 *
577 * return code is processed based on input code
578 */
Eric Biggersab74dbb2023-07-10 17:58:33 +0000579static Result<void> queue_fs_event(int code) {
Eric Biggerse5b5e372021-11-08 16:38:54 -0800580 if (code == FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700581 SetProperty("ro.crypto.state", "unsupported");
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700582 ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700583 return {};
Wei Wangd61a7e22016-08-23 11:58:09 -0700584 } else if (code == FS_MGR_MNTALL_DEV_NEEDS_RECOVERY) {
JP Abgrallcee20682014-07-02 14:26:54 -0700585 /* Setup a wipe via recovery, and reboot into recovery */
David Anderson0e330f12019-01-03 18:16:56 -0800586 if (android::gsi::IsGsiRunning()) {
587 return Error() << "cannot wipe within GSI";
588 }
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700589 PLOG(ERROR) << "fs_mgr_mount_all suggested recovery, so wiping data via recovery.";
Paul Crowley0b8b2302016-12-19 13:03:47 -0800590 const std::vector<std::string> options = {"--wipe_data", "--reason=fs_mgr_mount_all" };
Paul Crowleyc73b2152018-04-13 17:38:57 +0000591 return reboot_into_recovery(options);
JP Abgrallcee20682014-07-02 14:26:54 -0700592 /* If reboot worked, there is no return. */
Eric Biggersab74dbb2023-07-10 17:58:33 +0000593 } else if (code == FS_MGR_MNTALL_DEV_FILE_ENCRYPTED ||
594 code == FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED ||
595 code == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700596 SetProperty("ro.crypto.state", "encrypted");
Paul Lawrence9dbe97b2017-04-21 12:41:48 -0700597
Paul Crowleyc6846962018-01-30 09:56:03 -0800598 // Although encrypted, vold has already set the device up, so we do not need to
599 // do anything different from the nonencrypted case.
600 ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700601 return {};
Wei Wangd61a7e22016-08-23 11:58:09 -0700602 } else if (code > 0) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700603 Error() << "fs_mgr_mount_all() returned unexpected error " << code;
Ken Sumrall0e9dd902012-04-17 17:20:16 -0700604 }
JP Abgrallf22b7452014-07-02 13:16:04 -0700605 /* else ... < 0: error */
Ken Sumrall0e9dd902012-04-17 17:20:16 -0700606
Tom Cherry7fa62c52017-08-01 13:50:23 -0700607 return Error() << "Invalid code: " << code;
Ken Sumrall0e9dd902012-04-17 17:20:16 -0700608}
609
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700610/* <= Q: mount_all <fstab> [ <path> ]* [--<options>]*
611 * >= R: mount_all [ <fstab> ] [--<options>]*
Wei Wangd61a7e22016-08-23 11:58:09 -0700612 *
613 * This function might request a reboot, in which case it will
614 * not return.
615 */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700616static Result<void> do_mount_all(const BuiltinArguments& args) {
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700617 auto mount_all = ParseMountAll(args.args);
618 if (!mount_all.ok()) return mount_all.error();
Wei Wangd61a7e22016-08-23 11:58:09 -0700619
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700620 const char* prop_post_fix = "default";
621 bool queue_event = true;
622 if (mount_all->mode == MOUNT_MODE_EARLY) {
623 prop_post_fix = "early";
624 queue_event = false;
625 } else if (mount_all->mode == MOUNT_MODE_LATE) {
626 prop_post_fix = "late";
Wei Wangd61a7e22016-08-23 11:58:09 -0700627 }
628
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700629 std::string prop_name = "ro.boottime.init.mount_all."s + prop_post_fix;
Tom Cherryede0d532017-07-06 14:20:11 -0700630 android::base::Timer t;
Tom Cherry990483d2019-04-17 12:55:50 -0700631
632 Fstab fstab;
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700633 if (mount_all->fstab_path.empty()) {
634 if (!ReadDefaultFstab(&fstab)) {
635 return Error() << "Could not read default fstab";
636 }
637 } else {
638 if (!ReadFstabFromFile(mount_all->fstab_path, &fstab)) {
639 return Error() << "Could not read fstab";
640 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700641 }
Nikita Ioffe12a36072019-10-23 20:11:32 +0100642
Nikita Ioffe9ede7ec2020-09-07 10:27:25 +0100643 auto mount_fstab_result = fs_mgr_mount_all(&fstab, mount_all->mode);
Tom Cherryc88d8f92019-08-19 15:21:25 -0700644 SetProperty(prop_name, std::to_string(t.duration().count()));
Wei Wangd61a7e22016-08-23 11:58:09 -0700645
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700646 if (mount_all->import_rc) {
647 import_late(mount_all->rc_paths);
Wei Wangd61a7e22016-08-23 11:58:09 -0700648 }
649
650 if (queue_event) {
651 /* queue_fs_event will queue event based on mount_fstab return code
652 * and return processed return code*/
Jooyung Hane34549a2024-08-09 15:58:53 +0900653 auto queue_fs_result = queue_fs_event(mount_fstab_result);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900654 if (!queue_fs_result.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700655 return Error() << "queue_fs_event() failed: " << queue_fs_result.error();
656 }
Wei Wangd61a7e22016-08-23 11:58:09 -0700657 }
658
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700659 return {};
Wei Wangd61a7e22016-08-23 11:58:09 -0700660}
661
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700662/* umount_all [ <fstab> ] */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700663static Result<void> do_umount_all(const BuiltinArguments& args) {
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700664 auto umount_all = ParseUmountAll(args.args);
665 if (!umount_all.ok()) return umount_all.error();
666
Tom Cherry990483d2019-04-17 12:55:50 -0700667 Fstab fstab;
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700668 if (umount_all->empty()) {
669 if (!ReadDefaultFstab(&fstab)) {
670 return Error() << "Could not read default fstab";
671 }
672 } else {
673 if (!ReadFstabFromFile(*umount_all, &fstab)) {
674 return Error() << "Could not read fstab";
675 }
Tom Cherry990483d2019-04-17 12:55:50 -0700676 }
677
Tom Cherry3707d322019-08-15 13:07:24 -0700678 if (auto result = fs_mgr_umount_all(&fstab); result != 0) {
679 return Error() << "umount_fstab() failed " << result;
Yifan Hong402633d2019-04-09 10:11:34 -0700680 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700681 return {};
Yifan Hong402633d2019-04-09 10:11:34 -0700682}
683
Alistair Delvade28a862020-06-08 11:04:53 -0700684/* swapon_all [ <fstab> ] */
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700685static Result<void> do_swapon_all(const BuiltinArguments& args) {
Alistair Delvade28a862020-06-08 11:04:53 -0700686 auto swapon_all = ParseSwaponAll(args.args);
687 if (!swapon_all.ok()) return swapon_all.error();
688
Tom Cherry30554572018-11-30 15:21:04 -0800689 Fstab fstab;
Alistair Delvade28a862020-06-08 11:04:53 -0700690 if (swapon_all->empty()) {
691 if (!ReadDefaultFstab(&fstab)) {
692 return Error() << "Could not read default fstab";
693 }
694 } else {
695 if (!ReadFstabFromFile(*swapon_all, &fstab)) {
696 return Error() << "Could not read fstab '" << *swapon_all << "'";
697 }
Tom Cherry30554572018-11-30 15:21:04 -0800698 }
Ken Sumralla76baaa2013-07-09 18:42:09 -0700699
Tom Cherry3707d322019-08-15 13:07:24 -0700700 if (!fs_mgr_swapon_all(fstab)) {
701 return Error() << "fs_mgr_swapon_all() failed";
Tom Cherry30554572018-11-30 15:21:04 -0800702 }
Ken Sumralla76baaa2013-07-09 18:42:09 -0700703
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700704 return {};
Ken Sumralla76baaa2013-07-09 18:42:09 -0700705}
706
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700707static Result<void> do_setprop(const BuiltinArguments& args) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700708 if (StartsWith(args[1], "ctl.")) {
709 return Error()
710 << "Cannot set ctl. properties from init; call the Service functions directly";
711 }
712 if (args[1] == kRestoreconProperty) {
713 return Error() << "Cannot set '" << kRestoreconProperty
714 << "' from init; use the restorecon builtin directly";
715 }
716
Tom Cherryc88d8f92019-08-19 15:21:25 -0700717 SetProperty(args[1], args[2]);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700718 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700719}
720
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700721static Result<void> do_setrlimit(const BuiltinArguments& args) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700722 auto rlimit = ParseRlimit(args.args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900723 if (!rlimit.ok()) return rlimit.error();
Tom Cherry7fa62c52017-08-01 13:50:23 -0700724
Tom Cherry7ac013d2017-08-25 10:39:25 -0700725 if (setrlimit(rlimit->first, &rlimit->second) == -1) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700726 return ErrnoError() << "setrlimit failed";
727 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700728 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700729}
730
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700731static Result<void> do_start(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700732 Service* svc = ServiceList::GetInstance().FindService(args[1]);
Tom Cherry7fa62c52017-08-01 13:50:23 -0700733 if (!svc) return Error() << "service " << args[1] << " not found";
Jooyung Hand6b65fb2023-08-22 09:59:26 +0900734 errno = 0;
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900735 if (auto result = svc->Start(); !result.ok()) {
Tom Cherryd17c3792019-07-30 10:51:59 -0700736 return ErrorIgnoreEnoent() << "Could not start service: " << result.error();
Tom Cherry76af7e62017-08-22 16:13:59 -0700737 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700738 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700739}
740
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700741static Result<void> do_stop(const BuiltinArguments& args) {
Tom Cherry911b9b12017-07-27 16:20:58 -0700742 Service* svc = ServiceList::GetInstance().FindService(args[1]);
Tom Cherry7fa62c52017-08-01 13:50:23 -0700743 if (!svc) return Error() << "service " << args[1] << " not found";
Tom Cherrybac32992015-07-31 12:45:25 -0700744 svc->Stop();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700745 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700746}
747
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700748static Result<void> do_restart(const BuiltinArguments& args) {
David Anderson6d7c7a22021-12-03 15:48:16 -0800749 bool only_if_running = false;
750 if (args.size() == 3) {
751 if (args[1] == "--only-if-running") {
752 only_if_running = true;
753 } else {
754 return Error() << "Unknown argument to restart: " << args[1];
755 }
756 }
757
758 const auto& classname = args[args.size() - 1];
759 Service* svc = ServiceList::GetInstance().FindService(classname);
760 if (!svc) return Error() << "service " << classname << " not found";
761 if (only_if_running && !svc->IsRunning()) {
762 return {};
763 }
Tom Cherrybac32992015-07-31 12:45:25 -0700764 svc->Restart();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700765 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700766}
767
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700768static Result<void> do_trigger(const BuiltinArguments& args) {
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700769 ActionManager::GetInstance().QueueEventTrigger(args[1]);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700770 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700771}
772
Joel Galenson4b591f12017-11-27 14:45:26 -0800773static int MakeSymlink(const std::string& target, const std::string& linkpath) {
774 std::string secontext;
775 // Passing 0 for mode should work.
776 if (SelabelLookupFileContext(linkpath, 0, &secontext) && !secontext.empty()) {
777 setfscreatecon(secontext.c_str());
778 }
779
780 int rc = symlink(target.c_str(), linkpath.c_str());
781
782 if (!secontext.empty()) {
783 int save_errno = errno;
784 setfscreatecon(nullptr);
785 errno = save_errno;
786 }
787
788 return rc;
789}
790
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700791static Result<void> do_symlink(const BuiltinArguments& args) {
Joel Galenson4b591f12017-11-27 14:45:26 -0800792 if (MakeSymlink(args[1], args[2]) < 0) {
Tom Cherry68f2a462017-08-22 16:15:26 -0700793 // The symlink builtin is often used to create symlinks for older devices to be backwards
794 // compatible with new paths, therefore we skip reporting this error.
Tom Cherryd17c3792019-07-30 10:51:59 -0700795 return ErrnoErrorIgnoreEnoent() << "symlink() failed";
Elliott Hughesda46b392016-10-11 17:09:00 -0700796 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700797 return {};
The Android Open Source Project35237d12008-12-17 18:08:08 -0800798}
799
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700800static Result<void> do_rm(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700801 if (unlink(args[1].c_str()) < 0) {
802 return ErrnoError() << "unlink() failed";
803 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700804 return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -0700805}
806
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700807static Result<void> do_rmdir(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700808 if (rmdir(args[1].c_str()) < 0) {
809 return ErrnoError() << "rmdir() failed";
810 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700811 return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -0700812}
813
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700814static Result<void> do_sysclktz(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700815 struct timezone tz = {};
816 if (!android::base::ParseInt(args[1], &tz.tz_minuteswest)) {
817 return Error() << "Unable to parse mins_west_of_gmt";
818 }
819
820 if (settimeofday(nullptr, &tz) == -1) {
821 return ErrnoError() << "settimeofday() failed";
822 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700823 return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -0700824}
825
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700826static Result<void> do_verity_update_state(const BuiltinArguments& args) {
Tom Cherrycf80b6d2019-01-07 14:25:31 -0800827 int mode;
828 if (!fs_mgr_load_verity_state(&mode)) {
829 return Error() << "fs_mgr_load_verity_state() failed";
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700830 }
Tom Cherrycf80b6d2019-01-07 14:25:31 -0800831
832 Fstab fstab;
833 if (!ReadDefaultFstab(&fstab)) {
834 return Error() << "Failed to read default fstab";
835 }
836
837 for (const auto& entry : fstab) {
838 if (!fs_mgr_is_verity_enabled(entry)) {
839 continue;
840 }
841
842 // To be consistent in vboot 1.0 and vboot 2.0 (AVB), use "system" for the partition even
843 // for system as root, so it has property [partition.system.verified].
844 std::string partition = entry.mount_point == "/" ? "system" : Basename(entry.mount_point);
Tom Cherryc88d8f92019-08-19 15:21:25 -0700845 SetProperty("partition." + partition + ".verified", std::to_string(mode));
Tianjie327237d2021-01-20 19:02:34 -0800846
Tianjie10bec652021-08-30 16:10:09 -0700847 auto hashtree_info = fs_mgr_get_hashtree_info(entry);
848 if (hashtree_info) {
849 SetProperty("partition." + partition + ".verified.hash_alg", hashtree_info->algorithm);
850 SetProperty("partition." + partition + ".verified.root_digest",
851 hashtree_info->root_digest);
Nathan Huckleberry997d7382022-10-21 20:55:49 +0000852 SetProperty("partition." + partition + ".verified.check_at_most_once",
853 hashtree_info->check_at_most_once ? "1" : "0");
Tianjie327237d2021-01-20 19:02:34 -0800854 }
Tom Cherrycf80b6d2019-01-07 14:25:31 -0800855 }
856
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700857 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700858}
859
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700860static Result<void> do_write(const BuiltinArguments& args) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900861 if (auto result = WriteFile(args[1], args[2]); !result.ok()) {
Tom Cherryd17c3792019-07-30 10:51:59 -0700862 return ErrorIgnoreEnoent()
863 << "Unable to write to file '" << args[1] << "': " << result.error();
Tom Cherry7fa62c52017-08-01 13:50:23 -0700864 }
865
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700866 return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -0700867}
868
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700869static Result<void> readahead_file(const std::string& filename, bool fully) {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700870 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_CLOEXEC)));
Wei Wang02628f32017-08-16 11:34:50 -0700871 if (fd == -1) {
872 return ErrnoError() << "Error opening file";
873 }
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800874 if (posix_fadvise(fd.get(), 0, 0, POSIX_FADV_WILLNEED)) {
Wei Wang02628f32017-08-16 11:34:50 -0700875 return ErrnoError() << "Error posix_fadvise file";
876 }
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800877 if (readahead(fd.get(), 0, std::numeric_limits<size_t>::max())) {
Wei Wang02628f32017-08-16 11:34:50 -0700878 return ErrnoError() << "Error readahead file";
879 }
880 if (fully) {
881 char buf[BUFSIZ];
882 ssize_t n;
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800883 while ((n = TEMP_FAILURE_RETRY(read(fd.get(), &buf[0], sizeof(buf)))) > 0) {
Wei Wang02628f32017-08-16 11:34:50 -0700884 }
885 if (n != 0) {
886 return ErrnoError() << "Error reading file";
887 }
888 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700889 return {};
Wei Wang02628f32017-08-16 11:34:50 -0700890}
891
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700892static Result<void> do_readahead(const BuiltinArguments& args) {
Wei Wang542aae42017-08-04 13:22:36 -0700893 struct stat sb;
894
895 if (stat(args[1].c_str(), &sb)) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700896 return ErrnoError() << "Error opening " << args[1];
Wei Wang542aae42017-08-04 13:22:36 -0700897 }
898
Wei Wang02628f32017-08-16 11:34:50 -0700899 bool readfully = false;
900 if (args.size() == 3 && args[2] == "--fully") {
901 readfully = true;
902 }
Wei Wang542aae42017-08-04 13:22:36 -0700903 // We will do readahead in a forked process in order not to block init
904 // since it may block while it reads the
905 // filesystem metadata needed to locate the requested blocks. This
906 // occurs frequently with ext[234] on large files using indirect blocks
907 // instead of extents, giving the appearance that the call blocks until
908 // the requested data has been read.
909 pid_t pid = fork();
910 if (pid == 0) {
Wei Wang02628f32017-08-16 11:34:50 -0700911 if (setpriority(PRIO_PROCESS, 0, static_cast<int>(ANDROID_PRIORITY_LOWEST)) != 0) {
912 PLOG(WARNING) << "setpriority failed";
913 }
914 if (android_set_ioprio(0, IoSchedClass_IDLE, 7)) {
915 PLOG(WARNING) << "ioprio_get failed";
916 }
Wei Wang542aae42017-08-04 13:22:36 -0700917 android::base::Timer t;
918 if (S_ISREG(sb.st_mode)) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900919 if (auto result = readahead_file(args[1], readfully); !result.ok()) {
Wei Wang02628f32017-08-16 11:34:50 -0700920 LOG(WARNING) << "Unable to readahead '" << args[1] << "': " << result.error();
Wei Wang542aae42017-08-04 13:22:36 -0700921 _exit(EXIT_FAILURE);
922 }
923 } else if (S_ISDIR(sb.st_mode)) {
924 char* paths[] = {const_cast<char*>(args[1].data()), nullptr};
925 std::unique_ptr<FTS, decltype(&fts_close)> fts(
926 fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr), fts_close);
927 if (!fts) {
928 PLOG(ERROR) << "Error opening directory: " << args[1];
929 _exit(EXIT_FAILURE);
930 }
931 // Traverse the entire hierarchy and do readahead
932 for (FTSENT* ftsent = fts_read(fts.get()); ftsent != nullptr;
933 ftsent = fts_read(fts.get())) {
934 if (ftsent->fts_info & FTS_F) {
Wei Wang02628f32017-08-16 11:34:50 -0700935 const std::string filename = ftsent->fts_accpath;
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900936 if (auto result = readahead_file(filename, readfully); !result.ok()) {
Wei Wang02628f32017-08-16 11:34:50 -0700937 LOG(WARNING)
938 << "Unable to readahead '" << filename << "': " << result.error();
Wei Wang542aae42017-08-04 13:22:36 -0700939 }
940 }
941 }
942 }
Wei Wang02628f32017-08-16 11:34:50 -0700943 LOG(INFO) << "Readahead " << args[1] << " took " << t << " asynchronously";
Wei Wang542aae42017-08-04 13:22:36 -0700944 _exit(0);
945 } else if (pid < 0) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700946 return ErrnoError() << "Fork failed";
Wei Wang542aae42017-08-04 13:22:36 -0700947 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700948 return {};
Wei Wang542aae42017-08-04 13:22:36 -0700949}
950
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700951static Result<void> do_copy(const BuiltinArguments& args) {
Tom Cherry62ca6632017-08-03 12:54:07 -0700952 auto file_contents = ReadFile(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900953 if (!file_contents.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700954 return Error() << "Could not read input file '" << args[1] << "': " << file_contents.error();
San Mehat7c44fe52009-08-26 16:39:25 -0700955 }
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900956 if (auto result = WriteFile(args[2], *file_contents); !result.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700957 return Error() << "Could not write to output file '" << args[2] << "': " << result.error();
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700958 }
Tom Cherry7fa62c52017-08-01 13:50:23 -0700959
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700960 return {};
San Mehat7c44fe52009-08-26 16:39:25 -0700961}
962
Wei Wang49d25982020-11-18 15:56:14 -0800963static Result<void> do_copy_per_line(const BuiltinArguments& args) {
964 std::string file_contents;
965 if (!android::base::ReadFileToString(args[1], &file_contents, true)) {
966 return Error() << "Could not read input file '" << args[1] << "'";
967 }
968 auto lines = Split(file_contents, "\n");
969 for (const auto& line : lines) {
970 auto result = WriteFile(args[2], line);
971 if (!result.ok()) {
972 LOG(VERBOSE) << "Could not write to output file '" << args[2] << "' with '" << line
973 << "' : " << result.error();
974 }
975 }
976
977 return {};
978}
979
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700980static Result<void> do_chown(const BuiltinArguments& args) {
Tom Cherry62ca6632017-08-03 12:54:07 -0700981 auto uid = DecodeUid(args[1]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900982 if (!uid.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700983 return Error() << "Unable to decode UID for '" << args[1] << "': " << uid.error();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700984 }
Tom Cherry517e1f12017-05-04 17:40:33 -0700985
986 // GID is optional and pushes the index of path out by one if specified.
987 const std::string& path = (args.size() == 4) ? args[3] : args[2];
Tom Cherry62ca6632017-08-03 12:54:07 -0700988 Result<gid_t> gid = -1;
Tom Cherry517e1f12017-05-04 17:40:33 -0700989
990 if (args.size() == 4) {
Tom Cherry62ca6632017-08-03 12:54:07 -0700991 gid = DecodeUid(args[2]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900992 if (!gid.ok()) {
Tom Cherry7fa62c52017-08-01 13:50:23 -0700993 return Error() << "Unable to decode GID for '" << args[2] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700994 }
995 }
996
Tom Cherry7fa62c52017-08-01 13:50:23 -0700997 if (lchown(path.c_str(), *uid, *gid) == -1) {
Tom Cherryd17c3792019-07-30 10:51:59 -0700998 return ErrnoErrorIgnoreEnoent() << "lchown() failed";
Tom Cherry7fa62c52017-08-01 13:50:23 -0700999 }
Tom Cherry517e1f12017-05-04 17:40:33 -07001000
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001001 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001002}
1003
1004static mode_t get_mode(const char *s) {
1005 mode_t mode = 0;
1006 while (*s) {
1007 if (*s >= '0' && *s <= '7') {
1008 mode = (mode<<3) | (*s-'0');
1009 } else {
1010 return -1;
1011 }
1012 s++;
1013 }
1014 return mode;
1015}
1016
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001017static Result<void> do_chmod(const BuiltinArguments& args) {
Tom Cherry96f67312015-07-30 13:52:55 -07001018 mode_t mode = get_mode(args[1].c_str());
1019 if (fchmodat(AT_FDCWD, args[2].c_str(), mode, AT_SYMLINK_NOFOLLOW) < 0) {
Tom Cherryd17c3792019-07-30 10:51:59 -07001020 return ErrnoErrorIgnoreEnoent() << "fchmodat() failed";
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001021 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001022 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001023}
1024
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001025static Result<void> do_restorecon(const BuiltinArguments& args) {
Tom Cherry4772f1d2019-07-30 09:34:41 -07001026 auto restorecon_info = ParseRestorecon(args.args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001027 if (!restorecon_info.ok()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -07001028 return restorecon_info.error();
1029 }
1030
1031 const auto& [flag, paths] = *restorecon_info;
1032
Stephen Smalley726e8f72013-10-09 16:02:09 -04001033 int ret = 0;
Tom Cherry4772f1d2019-07-30 09:34:41 -07001034 for (const auto& path : paths) {
1035 if (selinux_android_restorecon(path.c_str(), flag) < 0) {
1036 ret = errno;
Paul Lawrencea8d84342016-11-14 15:40:18 -08001037 }
Stephen Smalleye46f9d52012-01-13 08:48:47 -05001038 }
Tom Cherry7fa62c52017-08-01 13:50:23 -07001039
Tom Cherryd17c3792019-07-30 10:51:59 -07001040 if (ret) return ErrnoErrorIgnoreEnoent() << "selinux_android_restorecon() failed";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001041 return {};
Stephen Smalley726e8f72013-10-09 16:02:09 -04001042}
1043
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001044static Result<void> do_restorecon_recursive(const BuiltinArguments& args) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001045 std::vector<std::string> non_const_args(args.args);
Paul Lawrencea8d84342016-11-14 15:40:18 -08001046 non_const_args.insert(std::next(non_const_args.begin()), "--recursive");
Bart Van Assche3dfb8bc2023-02-22 10:01:33 -08001047 return do_restorecon({.args = std::move(non_const_args), .context = args.context});
Stephen Smalleye46f9d52012-01-13 08:48:47 -05001048}
1049
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001050static Result<void> do_loglevel(const BuiltinArguments& args) {
Elliott Hughes7bc87a52016-08-04 16:09:39 -07001051 // TODO: support names instead/as well?
Elliott Hughesda46b392016-10-11 17:09:00 -07001052 int log_level = -1;
1053 android::base::ParseInt(args[1], &log_level);
Elliott Hughes7bc87a52016-08-04 16:09:39 -07001054 android::base::LogSeverity severity;
1055 switch (log_level) {
1056 case 7: severity = android::base::DEBUG; break;
1057 case 6: severity = android::base::INFO; break;
1058 case 5:
1059 case 4: severity = android::base::WARNING; break;
1060 case 3: severity = android::base::ERROR; break;
1061 case 2:
1062 case 1:
1063 case 0: severity = android::base::FATAL; break;
1064 default:
Tom Cherry7fa62c52017-08-01 13:50:23 -07001065 return Error() << "invalid log level " << log_level;
Riley Andrews1bbef882014-06-26 13:55:03 -07001066 }
Elliott Hughes7bc87a52016-08-04 16:09:39 -07001067 android::base::SetMinimumLogSeverity(severity);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001068 return {};
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001069}
1070
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001071static Result<void> do_load_persist_props(const BuiltinArguments& args) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001072 SendLoadPersistentPropertiesMessage();
1073
1074 start_waiting_for_property("ro.persistent_properties.ready", "true");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001075 return {};
Ken Sumrallc5c51032011-03-08 17:01:29 -08001076}
1077
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001078static Result<void> do_load_system_props(const BuiltinArguments& args) {
Jiyong Park3b316ee2019-01-13 02:42:31 +09001079 LOG(INFO) << "deprecated action `load_system_props` called.";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001080 return {};
Riley Andrewse4b7b292014-06-16 15:06:21 -07001081}
1082
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001083static Result<void> do_wait(const BuiltinArguments& args) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001084 auto timeout = kCommandRetryTimeout;
1085 if (args.size() == 3) {
Mark Salyzynffa52e92020-05-14 09:20:30 -07001086 double timeout_double;
1087 if (!android::base::ParseDouble(args[2], &timeout_double, 0)) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001088 return Error() << "failed to parse timeout";
Elliott Hughesda46b392016-10-11 17:09:00 -07001089 }
Mark Salyzynffa52e92020-05-14 09:20:30 -07001090 timeout = std::chrono::duration_cast<std::chrono::nanoseconds>(
1091 std::chrono::duration<double>(timeout_double));
Elliott Hughesda46b392016-10-11 17:09:00 -07001092 }
Tom Cherry7fa62c52017-08-01 13:50:23 -07001093
1094 if (wait_for_file(args[1].c_str(), timeout) != 0) {
1095 return Error() << "wait_for_file() failed";
1096 }
1097
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001098 return {};
Colin Crosscd0f1732010-04-19 17:10:24 -07001099}
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001100
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001101static Result<void> do_wait_for_prop(const BuiltinArguments& args) {
Wei Wang132ac312017-01-25 16:27:03 -08001102 const char* name = args[1].c_str();
1103 const char* value = args[2].c_str();
1104 size_t value_len = strlen(value);
1105
Tom Cherryde6bd502018-02-13 16:50:08 -08001106 if (!IsLegalPropertyName(name)) {
1107 return Error() << "IsLegalPropertyName(" << name << ") failed";
Wei Wang132ac312017-01-25 16:27:03 -08001108 }
1109 if (value_len >= PROP_VALUE_MAX) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001110 return Error() << "value too long";
Wei Wang132ac312017-01-25 16:27:03 -08001111 }
Wei Wang2d0fdaa2017-02-02 10:52:39 -08001112 if (!start_waiting_for_property(name, value)) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001113 return Error() << "already waiting for a property";
Wei Wang132ac312017-01-25 16:27:03 -08001114 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001115 return {};
Wei Wang132ac312017-01-25 16:27:03 -08001116}
1117
Paul Crowley749af8c2015-05-28 17:35:06 +01001118static bool is_file_crypto() {
Tom Cherryccf23532017-03-28 16:40:41 -07001119 return android::base::GetProperty("ro.crypto.type", "") == "file";
Paul Crowley749af8c2015-05-28 17:35:06 +01001120}
1121
Tom Cherry7896e7a2019-09-04 15:26:52 -07001122static Result<void> ExecWithFunctionOnFailure(const std::vector<std::string>& args,
1123 std::function<void(const std::string&)> function) {
1124 auto service = Service::MakeTemporaryOneshotService(args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001125 if (!service.ok()) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001126 function("MakeTemporaryOneshotService failed: " + service.error().message());
Paul Crowleyc73b2152018-04-13 17:38:57 +00001127 }
Tom Cherry7896e7a2019-09-04 15:26:52 -07001128 (*service)->AddReapCallback([function](const siginfo_t& siginfo) {
Paul Crowleyc73b2152018-04-13 17:38:57 +00001129 if (siginfo.si_code != CLD_EXITED || siginfo.si_status != 0) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001130 function(StringPrintf("Exec service failed, status %d", siginfo.si_status));
Paul Crowleyc73b2152018-04-13 17:38:57 +00001131 }
1132 });
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001133 if (auto result = (*service)->ExecStart(); !result.ok()) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001134 function("ExecStart failed: " + result.error().message());
Paul Crowleyc73b2152018-04-13 17:38:57 +00001135 }
Tom Cherry4772f1d2019-07-30 09:34:41 -07001136 ServiceList::GetInstance().AddService(std::move(*service));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001137 return {};
Paul Crowleyc73b2152018-04-13 17:38:57 +00001138}
1139
Tom Cherry7896e7a2019-09-04 15:26:52 -07001140static Result<void> ExecVdcRebootOnFailure(const std::string& vdc_arg) {
1141 auto reboot_reason = vdc_arg + "_failed";
1142
Jooyung Hanf91503b2024-08-09 16:17:20 +09001143 auto reboot = [reboot_reason](const std::string& message) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001144 // TODO (b/122850122): support this in gsi
Jooyung Hanf91503b2024-08-09 16:17:20 +09001145 if (IsFbeEnabled() && !android::gsi::IsGsiRunning()) {
1146 LOG(ERROR) << message << ": Rebooting into recovery, reason: " << reboot_reason;
1147 if (auto result = reboot_into_recovery(
1148 {"--prompt_and_wipe_data", "--reason="s + reboot_reason});
1149 !result.ok()) {
1150 LOG(FATAL) << "Could not reboot into recovery: " << result.error();
Tom Cherry7896e7a2019-09-04 15:26:52 -07001151 }
1152 } else {
Jooyung Hanf91503b2024-08-09 16:17:20 +09001153 LOG(ERROR) << "Failure (reboot suppressed): " << reboot_reason;
Tom Cherry7896e7a2019-09-04 15:26:52 -07001154 }
1155 };
1156
1157 std::vector<std::string> args = {"exec", "/system/bin/vdc", "--wait", "cryptfs", vdc_arg};
1158 return ExecWithFunctionOnFailure(args, reboot);
1159}
1160
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001161static Result<void> do_installkey(const BuiltinArguments& args) {
1162 if (!is_file_crypto()) return {};
Tom Cherry7fa62c52017-08-01 13:50:23 -07001163
Eric Biggersf05da4a2018-10-23 13:10:33 -07001164 auto unencrypted_dir = args[1] + fscrypt_unencrypted_folder;
Tom Cherryc3692b32017-08-10 12:22:44 -07001165 if (!make_dir(unencrypted_dir, 0700) && errno != EEXIST) {
Tom Cherry7fa62c52017-08-01 13:50:23 -07001166 return ErrnoError() << "Failed to create " << unencrypted_dir;
Janis Danisevskis9cc51722017-03-29 14:50:01 -07001167 }
Tom Cherry7896e7a2019-09-04 15:26:52 -07001168 return ExecVdcRebootOnFailure("enablefilecrypto");
Paul Lawrenceb8c9d272015-03-26 15:49:42 +00001169}
Paul Crowley749af8c2015-05-28 17:35:06 +01001170
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001171static Result<void> do_init_user0(const BuiltinArguments& args) {
Tom Cherry7896e7a2019-09-04 15:26:52 -07001172 return ExecVdcRebootOnFailure("init_user0");
Paul Crowley59497452016-02-01 16:37:13 +00001173}
1174
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001175static Result<void> do_mark_post_data(const BuiltinArguments& args) {
Jooyung Han148f6022024-08-19 14:29:04 +09001176 LOG(INFO) << "deprecated action `mark_post_data` called.";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001177 return {};
Martijn Coenen70788f92019-04-23 16:26:01 +02001178}
1179
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001180static Result<void> GenerateLinkerConfiguration() {
Kiyoung Kim03b9bca2020-11-30 14:49:36 +09001181 const char* linkerconfig_binary = "/apex/com.android.runtime/bin/linkerconfig";
Kiyoung Kim3b2dbe92019-12-30 18:44:41 +09001182 const char* linkerconfig_target = "/linkerconfig";
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001183 const char* arguments[] = {linkerconfig_binary, "--target", linkerconfig_target};
1184
1185 if (logwrap_fork_execvp(arraysize(arguments), arguments, nullptr, false, LOG_KLOG, false,
1186 nullptr) != 0) {
1187 return ErrnoError() << "failed to execute linkerconfig";
1188 }
1189
Kiyoung Kim0cbee0d2021-03-02 16:45:27 +09001190 auto current_mount_ns = GetCurrentMountNamespace();
1191 if (!current_mount_ns.ok()) {
1192 return current_mount_ns.error();
1193 }
1194 if (*current_mount_ns == NS_DEFAULT) {
1195 SetDefaultMountNamespaceReady();
1196 }
1197
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001198 LOG(INFO) << "linkerconfig generated " << linkerconfig_target
1199 << " with mounted APEX modules info";
1200
1201 return {};
1202}
1203
Jooyung Han4f23d5a2020-06-09 13:44:17 +09001204static Result<void> MountLinkerConfigForDefaultNamespace() {
1205 // No need to mount linkerconfig for default mount namespace if the path does not exist (which
1206 // would mean it is already mounted)
1207 if (access("/linkerconfig/default", 0) != 0) {
1208 return {};
1209 }
1210
1211 if (mount("/linkerconfig/default", "/linkerconfig", nullptr, MS_BIND | MS_REC, nullptr) != 0) {
1212 return ErrnoError() << "Failed to mount linker configuration for default mount namespace.";
1213 }
1214
1215 return {};
1216}
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001217static Result<void> do_update_linker_config(const BuiltinArguments&) {
Shikha Malhotra720694d2021-07-30 12:35:27 +00001218 return GenerateLinkerConfiguration();
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001219}
1220
Oli Lan13e51e72019-11-19 18:08:45 +00001221/*
1222 * Creates a directory under /data/misc/apexdata/ for each APEX.
1223 */
Jooyung Han2982f092023-08-11 14:14:37 +09001224static void create_apex_data_dirs() {
1225 for (const auto& name : GetApexListFrom("/apex")) {
1226 auto path = "/data/misc/apexdata/" + name;
Oli Lan90c523b2020-01-17 11:41:04 +00001227 auto options = MkdirOptions{path, 0771, AID_ROOT, AID_SYSTEM, FscryptAction::kNone, "ref"};
Jooyung Han2982f092023-08-11 14:14:37 +09001228 auto result = make_dir_with_options(options);
1229 if (!result.ok()) {
1230 LOG(ERROR) << result.error();
1231 }
Oli Lan13e51e72019-11-19 18:08:45 +00001232 }
Oli Lan13e51e72019-11-19 18:08:45 +00001233}
1234
1235static Result<void> do_perform_apex_config(const BuiltinArguments& args) {
Jooyung Han5c4217c2023-08-10 13:12:53 +09001236 bool bootstrap = false;
1237 if (args.size() == 2) {
1238 if (args[1] != "--bootstrap") {
1239 return Error() << "Unexpected argument: " << args[1];
1240 }
1241 bootstrap = true;
Oli Lan13e51e72019-11-19 18:08:45 +00001242 }
Jooyung Han5c4217c2023-08-10 13:12:53 +09001243
1244 if (!bootstrap) {
Jooyung Han2982f092023-08-11 14:14:37 +09001245 create_apex_data_dirs();
Jooyung Han5c4217c2023-08-10 13:12:53 +09001246 }
1247
Jooyung Han55ef3d62023-08-10 18:27:22 +09001248 auto parse_result = ParseRcScriptsFromAllApexes(bootstrap);
1249 if (!parse_result.ok()) {
1250 return parse_result.error();
Oli Lan13e51e72019-11-19 18:08:45 +00001251 }
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001252
1253 auto update_linker_config = do_update_linker_config(args);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001254 if (!update_linker_config.ok()) {
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001255 return update_linker_config.error();
1256 }
1257
Jooyung Han5c4217c2023-08-10 13:12:53 +09001258 if (!bootstrap) {
Jooyung Han646e0012023-08-21 17:34:37 +09001259 ServiceList::GetInstance().StartDelayedServices();
Jooyung Han5c4217c2023-08-10 13:12:53 +09001260 }
Oli Lan13e51e72019-11-19 18:08:45 +00001261 return {};
1262}
1263
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001264static Result<void> do_enter_default_mount_ns(const BuiltinArguments& args) {
Jooyung Han4f23d5a2020-06-09 13:44:17 +09001265 if (auto result = SwitchToMountNamespaceIfNeeded(NS_DEFAULT); !result.ok()) {
1266 return result.error();
Jiyong Parkdcbaf9f2019-02-22 22:15:25 +09001267 }
Jooyung Han4f23d5a2020-06-09 13:44:17 +09001268 if (auto result = MountLinkerConfigForDefaultNamespace(); !result.ok()) {
1269 return result.error();
1270 }
1271 LOG(INFO) << "Switched to default mount namespace";
1272 return {};
Jiyong Parkdcbaf9f2019-02-22 22:15:25 +09001273}
1274
terryguan43997542024-09-05 17:35:41 -07001275static Result<void> do_swapoff(const BuiltinArguments& args) {
1276 if (!swapoff(args[1].c_str())) {
1277 return ErrnoError() << "swapoff() failed";
1278 }
1279 return {};
1280}
1281
Tom Cherryde6bd502018-02-13 16:50:08 -08001282// Builtin-function-map start
Tom Cherryd52a5b32019-07-22 16:05:36 -07001283const BuiltinFunctionMap& GetBuiltinFunctionMap() {
Tom Cherryb7349902015-08-26 11:43:36 -07001284 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Tom Cherryb27004a2017-03-27 16:27:30 -07001285 // clang-format off
Tom Cherryd52a5b32019-07-22 16:05:36 -07001286 static const BuiltinFunctionMap builtin_functions = {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001287 {"bootchart", {1, 1, {false, do_bootchart}}},
1288 {"chmod", {2, 2, {true, do_chmod}}},
1289 {"chown", {2, 3, {true, do_chown}}},
1290 {"class_reset", {1, 1, {false, do_class_reset}}},
David Anderson2285b522021-11-09 18:26:39 -08001291 {"class_restart", {1, 2, {false, do_class_restart}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001292 {"class_start", {1, 1, {false, do_class_start}}},
1293 {"class_stop", {1, 1, {false, do_class_stop}}},
1294 {"copy", {2, 2, {true, do_copy}}},
Wei Wang49d25982020-11-18 15:56:14 -08001295 {"copy_per_line", {2, 2, {true, do_copy_per_line}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001296 {"domainname", {1, 1, {true, do_domainname}}},
1297 {"enable", {1, 1, {false, do_enable}}},
1298 {"exec", {1, kMax, {false, do_exec}}},
1299 {"exec_background", {1, kMax, {false, do_exec_background}}},
1300 {"exec_start", {1, 1, {false, do_exec_start}}},
1301 {"export", {2, 2, {false, do_export}}},
1302 {"hostname", {1, 1, {true, do_hostname}}},
1303 {"ifup", {1, 1, {true, do_ifup}}},
1304 {"init_user0", {0, 0, {false, do_init_user0}}},
1305 {"insmod", {1, kMax, {true, do_insmod}}},
1306 {"installkey", {1, 1, {false, do_installkey}}},
Steven Moreland612d7a42018-05-08 11:21:37 -07001307 {"interface_restart", {1, 1, {false, do_interface_restart}}},
1308 {"interface_start", {1, 1, {false, do_interface_start}}},
1309 {"interface_stop", {1, 1, {false, do_interface_stop}}},
Artur Satayev500946b2021-02-15 20:48:49 +00001310 {"load_exports", {1, 1, {false, do_load_exports}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001311 {"load_persist_props", {0, 0, {false, do_load_persist_props}}},
1312 {"load_system_props", {0, 0, {false, do_load_system_props}}},
1313 {"loglevel", {1, 1, {false, do_loglevel}}},
Martijn Coenen70788f92019-04-23 16:26:01 +02001314 {"mark_post_data", {0, 0, {false, do_mark_post_data}}},
Paul Crowley68258e82019-10-28 07:55:03 -07001315 {"mkdir", {1, 6, {true, do_mkdir}}},
Tom Cherry880d5662018-02-05 08:01:54 -08001316 // TODO: Do mount operations in vendor_init.
1317 // mount_all is currently too complex to run in vendor_init as it queues action triggers,
1318 // imports rc scripts, etc. It should be simplified and run in vendor_init context.
1319 // mount and umount are run in the same context as mount_all for symmetry.
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -07001320 {"mount_all", {0, kMax, {false, do_mount_all}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001321 {"mount", {3, kMax, {false, do_mount}}},
Jooyung Han5c4217c2023-08-10 13:12:53 +09001322 {"perform_apex_config", {0, 1, {false, do_perform_apex_config}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001323 {"umount", {1, 1, {false, do_umount}}},
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -07001324 {"umount_all", {0, 1, {false, do_umount_all}}},
Kiyoung Kime4d3f212019-12-16 14:31:04 +09001325 {"update_linker_config", {0, 0, {false, do_update_linker_config}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001326 {"readahead", {1, 2, {true, do_readahead}}},
David Anderson6d7c7a22021-12-03 15:48:16 -08001327 {"restart", {1, 2, {false, do_restart}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001328 {"restorecon", {1, kMax, {true, do_restorecon}}},
1329 {"restorecon_recursive", {1, kMax, {true, do_restorecon_recursive}}},
1330 {"rm", {1, 1, {true, do_rm}}},
1331 {"rmdir", {1, 1, {true, do_rmdir}}},
Tom Cherry32228482018-01-18 16:14:25 -08001332 {"setprop", {2, 2, {true, do_setprop}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001333 {"setrlimit", {3, 3, {false, do_setrlimit}}},
1334 {"start", {1, 1, {false, do_start}}},
1335 {"stop", {1, 1, {false, do_stop}}},
Alistair Delvade28a862020-06-08 11:04:53 -07001336 {"swapon_all", {0, 1, {false, do_swapon_all}}},
terryguan43997542024-09-05 17:35:41 -07001337 {"swapoff", {1, 1, {false, do_swapoff}}},
Jiyong Parkdcbaf9f2019-02-22 22:15:25 +09001338 {"enter_default_mount_ns", {0, 0, {false, do_enter_default_mount_ns}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001339 {"symlink", {2, 2, {true, do_symlink}}},
1340 {"sysclktz", {1, 1, {false, do_sysclktz}}},
1341 {"trigger", {1, 1, {false, do_trigger}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001342 {"verity_update_state", {0, 0, {false, do_verity_update_state}}},
1343 {"wait", {1, 2, {true, do_wait}}},
Tom Cherryfa3e52c2017-10-17 10:43:52 -07001344 {"wait_for_prop", {2, 2, {false, do_wait_for_prop}}},
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001345 {"write", {2, 2, {true, do_write}}},
Tom Cherryb7349902015-08-26 11:43:36 -07001346 };
Tom Cherryb27004a2017-03-27 16:27:30 -07001347 // clang-format on
Tom Cherryb7349902015-08-26 11:43:36 -07001348 return builtin_functions;
1349}
Tom Cherryde6bd502018-02-13 16:50:08 -08001350// Builtin-function-map end
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001351
1352} // namespace init
1353} // namespace android