blob: 73f294a2f466b4d715b29d3cd49060cf385da479 [file] [log] [blame]
Tao Bao6d99d4b2018-04-25 16:47:04 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
Steve Kondik54987762013-10-19 19:49:20 -07003 * Copyright (C) 2019 The LineageOS Project
Tao Bao6d99d4b2018-04-25 16:47:04 -07004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
Tao Bao42c45e22018-07-31 09:37:12 -070018#include <dlfcn.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
22#include <inttypes.h>
23#include <limits.h>
24#include <linux/fs.h>
25#include <stdarg.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070026#include <stdio.h>
27#include <stdlib.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070028#include <string.h>
29#include <sys/stat.h>
30#include <sys/types.h>
31#include <time.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070032#include <unistd.h>
33
Hridya Valsaraju20c81b32018-07-27 22:09:12 -070034#include <atomic>
Steve Kondik54987762013-10-19 19:49:20 -070035#include <filesystem>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070036#include <string>
Hridya Valsaraju20c81b32018-07-27 22:09:12 -070037#include <thread>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070038#include <vector>
Tao Bao6d99d4b2018-04-25 16:47:04 -070039
Jerry Zhangf5e319a2018-05-04 11:24:10 -070040#include <android-base/file.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070041#include <android-base/logging.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070042#include <android-base/properties.h>
43#include <android-base/strings.h>
Hridya Valsaraju20c81b32018-07-27 22:09:12 -070044#include <android-base/unique_fd.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070045#include <bootloader_message/bootloader_message.h>
Hridya Valsaraju20c81b32018-07-27 22:09:12 -070046#include <cutils/sockets.h>
Tao Baof90d9a12019-05-10 10:40:59 -070047#include <fs_mgr/roots.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070048#include <private/android_logger.h> /* private pmsg functions */
Jerry Zhangf5e319a2018-05-04 11:24:10 -070049#include <selinux/android.h>
50#include <selinux/label.h>
51#include <selinux/selinux.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070052
Hridya Valsaraju20c81b32018-07-27 22:09:12 -070053#include "fastboot/fastboot.h"
xunchang316e9712019-04-12 16:22:15 -070054#include "install/wipe_data.h"
Tianjie Xub63a2212019-07-29 14:21:49 -070055#include "otautil/boot_state.h"
Tao Bao6d99d4b2018-04-25 16:47:04 -070056#include "otautil/paths.h"
Jerry Zhangf5e319a2018-05-04 11:24:10 -070057#include "otautil/sysutil.h"
58#include "recovery.h"
Tianjie Xu8f397302018-08-20 13:40:47 -070059#include "recovery_ui/device.h"
60#include "recovery_ui/stub_ui.h"
61#include "recovery_ui/ui.h"
Tao Baoe3f09a72019-10-01 11:55:36 -070062#include "recovery_utils/logging.h"
63#include "recovery_utils/roots.h"
Tao Bao6d99d4b2018-04-25 16:47:04 -070064
Steve Kondik54987762013-10-19 19:49:20 -070065namespace fs = std::filesystem;
66
Jerry Zhangf5e319a2018-05-04 11:24:10 -070067static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
68static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
69
Tianjie Xu164c60a2019-05-15 13:59:39 -070070static RecoveryUI* ui = nullptr;
Jerry Zhangf5e319a2018-05-04 11:24:10 -070071
Tianjie Xu164c60a2019-05-15 13:59:39 -070072static bool IsRoDebuggable() {
73 return android::base::GetBoolProperty("ro.debuggable", false);
74}
Jerry Zhangf5e319a2018-05-04 11:24:10 -070075
Tianjie Xu7d5c3412019-10-29 21:44:39 -070076static bool IsDeviceUnlocked() {
77 return "orange" == android::base::GetProperty("ro.boot.verifiedbootstate", "");
78}
79
Tom Marshall914603d2018-06-21 00:57:24 +020080std::string get_build_type() {
Michael Bestas93cd1272019-09-27 20:29:42 +030081 return android::base::GetProperty("ro.build.type", "");
82}
83
Steve Kondik54987762013-10-19 19:49:20 -070084static constexpr const char* adb_keys_data = "/data/misc/adb/adb_keys";
85static constexpr const char* adb_keys_root = "/adb_keys";
86
Tao Bao6d99d4b2018-04-25 16:47:04 -070087static void UiLogger(android::base::LogId /* id */, android::base::LogSeverity severity,
88 const char* /* tag */, const char* /* file */, unsigned int /* line */,
89 const char* message) {
90 static constexpr char log_characters[] = "VDIWEF";
91 if (severity >= android::base::ERROR && ui != nullptr) {
92 ui->Print("E:%s\n", message);
93 } else {
94 fprintf(stdout, "%c:%s\n", log_characters[severity], message);
95 }
96}
97
Tianjie Xub63a2212019-07-29 14:21:49 -070098// Parses the command line argument from various sources; and reads the stage field from BCB.
Jerry Zhangf5e319a2018-05-04 11:24:10 -070099// command line args come from, in decreasing precedence:
100// - the actual command line
101// - the bootloader control block (one per line, after "recovery")
102// - the contents of COMMAND_FILE (one per line)
Tianjie Xub63a2212019-07-29 14:21:49 -0700103static std::vector<std::string> get_args(const int argc, char** const argv, std::string* stage) {
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700104 CHECK_GT(argc, 0);
105
106 bootloader_message boot = {};
107 std::string err;
108 if (!read_bootloader_message(&boot, &err)) {
109 LOG(ERROR) << err;
110 // If fails, leave a zeroed bootloader_message.
111 boot = {};
112 }
Tianjie Xub63a2212019-07-29 14:21:49 -0700113 if (stage) {
114 *stage = std::string(boot.stage);
115 }
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700116
David Andersoneee4e262018-08-21 13:10:45 -0700117 std::string boot_command;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700118 if (boot.command[0] != 0) {
David Andersoneee4e262018-08-21 13:10:45 -0700119 if (memchr(boot.command, '\0', sizeof(boot.command))) {
120 boot_command = std::string(boot.command);
121 } else {
122 boot_command = std::string(boot.command, sizeof(boot.command));
123 }
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700124 LOG(INFO) << "Boot command: " << boot_command;
125 }
126
127 if (boot.status[0] != 0) {
128 std::string boot_status = std::string(boot.status, sizeof(boot.status));
129 LOG(INFO) << "Boot status: " << boot_status;
130 }
131
132 std::vector<std::string> args(argv, argv + argc);
133
134 // --- if arguments weren't supplied, look in the bootloader control block
135 if (args.size() == 1) {
136 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
137 std::string boot_recovery(boot.recovery);
138 std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
139 if (!tokens.empty() && tokens[0] == "recovery") {
140 for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
141 // Skip empty and '\0'-filled tokens.
142 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
143 }
144 LOG(INFO) << "Got " << args.size() << " arguments from boot message";
145 } else if (boot.recovery[0] != 0) {
146 LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
147 }
148 }
149
150 // --- if that doesn't work, try the command file (if we have /cache).
Tianjie Xu164c60a2019-05-15 13:59:39 -0700151 if (args.size() == 1 && HasCache()) {
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700152 std::string content;
153 if (ensure_path_mounted(COMMAND_FILE) == 0 &&
154 android::base::ReadFileToString(COMMAND_FILE, &content)) {
155 std::vector<std::string> tokens = android::base::Split(content, "\n");
156 // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
157 // COMMAND_FILE doesn't use filename as the first argument).
158 for (auto it = tokens.begin(); it != tokens.end(); it++) {
159 // Skip empty and '\0'-filled tokens.
160 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
161 }
162 LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
163 }
164 }
165
166 // Write the arguments (excluding the filename in args[0]) back into the
167 // bootloader control block. So the device will always boot into recovery to
Tianjie Xu164c60a2019-05-15 13:59:39 -0700168 // finish the pending work, until FinishRecovery() is called.
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700169 std::vector<std::string> options(args.cbegin() + 1, args.cend());
170 if (!update_bootloader_message(options, &err)) {
171 LOG(ERROR) << "Failed to set BCB message: " << err;
172 }
173
David Andersoneee4e262018-08-21 13:10:45 -0700174 // Finally, if no arguments were specified, check whether we should boot
Tao Baod9cb0142019-04-23 11:46:25 -0700175 // into fastboot or rescue mode.
David Andersoneee4e262018-08-21 13:10:45 -0700176 if (args.size() == 1 && boot_command == "boot-fastboot") {
177 args.emplace_back("--fastboot");
Tao Baod9cb0142019-04-23 11:46:25 -0700178 } else if (args.size() == 1 && boot_command == "boot-rescue") {
179 args.emplace_back("--rescue");
David Andersoneee4e262018-08-21 13:10:45 -0700180 }
181
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700182 return args;
183}
184
185static std::string load_locale_from_cache() {
186 if (ensure_path_mounted(LOCALE_FILE) != 0) {
187 LOG(ERROR) << "Can't mount " << LOCALE_FILE;
188 return "";
189 }
190
191 std::string content;
192 if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
193 PLOG(ERROR) << "Can't read " << LOCALE_FILE;
194 return "";
195 }
196
197 return android::base::Trim(content);
198}
199
Steve Kondik54987762013-10-19 19:49:20 -0700200static void copy_userdata_files() {
201 if (ensure_path_mounted("/data") == 0) {
202 if (access(adb_keys_root, F_OK) != 0) {
203 if (access(adb_keys_data, R_OK) == 0) {
204 std::error_code ec; // to invoke the overloaded copy_file() that won't throw.
205 if (!fs::copy_file(adb_keys_data, adb_keys_root, ec)) {
206 PLOG(ERROR) << "Failed to copy adb keys";
207 }
208 }
209 }
210 ensure_path_unmounted("/data");
211 }
212}
213
Tao Baoe0cfab32019-03-29 15:53:23 -0700214// Sets the usb config to 'state'.
215static bool SetUsbConfig(const std::string& state) {
216 android::base::SetProperty("sys.usb.config", state);
217 return android::base::WaitForProperty("sys.usb.state", state);
218}
219
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700220static void ListenRecoverySocket(RecoveryUI* ui, std::atomic<Device::BuiltinAction>& action) {
221 android::base::unique_fd sock_fd(android_get_control_socket("recovery"));
222 if (sock_fd < 0) {
223 PLOG(ERROR) << "Failed to open recovery socket";
224 return;
225 }
226 listen(sock_fd, 4);
227
228 while (true) {
229 android::base::unique_fd connection_fd;
230 connection_fd.reset(accept(sock_fd, nullptr, nullptr));
231 if (connection_fd < 0) {
232 PLOG(ERROR) << "Failed to accept socket connection";
233 continue;
234 }
235 char msg;
236 constexpr char kSwitchToFastboot = 'f';
237 constexpr char kSwitchToRecovery = 'r';
238 ssize_t ret = TEMP_FAILURE_RETRY(read(connection_fd, &msg, sizeof(msg)));
239 if (ret != sizeof(msg)) {
240 PLOG(ERROR) << "Couldn't read from socket";
241 continue;
242 }
243 switch (msg) {
244 case kSwitchToRecovery:
245 action = Device::BuiltinAction::ENTER_RECOVERY;
246 break;
247 case kSwitchToFastboot:
248 action = Device::BuiltinAction::ENTER_FASTBOOT;
249 break;
250 default:
251 LOG(ERROR) << "Unrecognized char from socket " << msg;
252 continue;
253 }
254 ui->InterruptKey();
255 }
256}
257
Tao Bao6d99d4b2018-04-25 16:47:04 -0700258static void redirect_stdio(const char* filename) {
Tao Bao6fcd2082019-01-16 09:29:17 -0800259 android::base::unique_fd pipe_read, pipe_write;
260 // Create a pipe that allows parent process sending logs over.
261 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
262 PLOG(ERROR) << "Failed to create pipe for redirecting stdio";
Tao Bao6d99d4b2018-04-25 16:47:04 -0700263
264 // Fall back to traditional logging mode without timestamps. If these fail, there's not really
265 // anywhere to complain...
266 freopen(filename, "a", stdout);
267 setbuf(stdout, nullptr);
268 freopen(filename, "a", stderr);
269 setbuf(stderr, nullptr);
270
271 return;
272 }
273
274 pid_t pid = fork();
275 if (pid == -1) {
Tao Bao6fcd2082019-01-16 09:29:17 -0800276 PLOG(ERROR) << "Failed to fork for redirecting stdio";
Tao Bao6d99d4b2018-04-25 16:47:04 -0700277
278 // Fall back to traditional logging mode without timestamps. If these fail, there's not really
279 // anywhere to complain...
280 freopen(filename, "a", stdout);
281 setbuf(stdout, nullptr);
282 freopen(filename, "a", stderr);
283 setbuf(stderr, nullptr);
284
285 return;
286 }
287
288 if (pid == 0) {
Tao Bao6fcd2082019-01-16 09:29:17 -0800289 // Child process reads the incoming logs and doesn't write to the pipe.
290 pipe_write.reset();
Tao Bao6d99d4b2018-04-25 16:47:04 -0700291
292 auto start = std::chrono::steady_clock::now();
293
294 // Child logger to actually write to the log file.
295 FILE* log_fp = fopen(filename, "ae");
296 if (log_fp == nullptr) {
297 PLOG(ERROR) << "fopen \"" << filename << "\" failed";
Tao Bao6d99d4b2018-04-25 16:47:04 -0700298 _exit(EXIT_FAILURE);
299 }
300
Tao Bao6fcd2082019-01-16 09:29:17 -0800301 FILE* pipe_fp = android::base::Fdopen(std::move(pipe_read), "r");
Tao Bao6d99d4b2018-04-25 16:47:04 -0700302 if (pipe_fp == nullptr) {
303 PLOG(ERROR) << "fdopen failed";
304 check_and_fclose(log_fp, filename);
Tao Bao6d99d4b2018-04-25 16:47:04 -0700305 _exit(EXIT_FAILURE);
306 }
307
308 char* line = nullptr;
309 size_t len = 0;
310 while (getline(&line, &len, pipe_fp) != -1) {
311 auto now = std::chrono::steady_clock::now();
312 double duration =
313 std::chrono::duration_cast<std::chrono::duration<double>>(now - start).count();
314 if (line[0] == '\n') {
315 fprintf(log_fp, "[%12.6lf]\n", duration);
316 } else {
317 fprintf(log_fp, "[%12.6lf] %s", duration, line);
318 }
319 fflush(log_fp);
320 }
321
322 PLOG(ERROR) << "getline failed";
323
Tao Bao6fcd2082019-01-16 09:29:17 -0800324 fclose(pipe_fp);
Tao Bao6d99d4b2018-04-25 16:47:04 -0700325 free(line);
326 check_and_fclose(log_fp, filename);
Tao Bao6d99d4b2018-04-25 16:47:04 -0700327 _exit(EXIT_FAILURE);
328 } else {
329 // Redirect stdout/stderr to the logger process. Close the unused read end.
Tao Bao6fcd2082019-01-16 09:29:17 -0800330 pipe_read.reset();
Tao Bao6d99d4b2018-04-25 16:47:04 -0700331
332 setbuf(stdout, nullptr);
333 setbuf(stderr, nullptr);
334
Tao Bao6fcd2082019-01-16 09:29:17 -0800335 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
Tao Bao6d99d4b2018-04-25 16:47:04 -0700336 PLOG(ERROR) << "dup2 stdout failed";
337 }
Tao Bao6fcd2082019-01-16 09:29:17 -0800338 if (dup2(pipe_write.get(), STDERR_FILENO) == -1) {
Tao Bao6d99d4b2018-04-25 16:47:04 -0700339 PLOG(ERROR) << "dup2 stderr failed";
340 }
Tao Bao6d99d4b2018-04-25 16:47:04 -0700341 }
342}
343
344int main(int argc, char** argv) {
345 // We don't have logcat yet under recovery; so we'll print error on screen and log to stdout
346 // (which is redirected to recovery.log) as we used to do.
347 android::base::InitLogging(argv, &UiLogger);
348
349 // Take last pmsg contents and rewrite it to the current pmsg session.
350 static constexpr const char filter[] = "recovery/";
351 // Do we need to rotate?
352 bool do_rotate = false;
353
354 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logbasename, &do_rotate);
355 // Take action to refresh pmsg contents
356 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logrotate, &do_rotate);
357
Steve Kondik54987762013-10-19 19:49:20 -0700358 // Clear umask for packages that copy files out to /tmp and then over
359 // to /system without properly setting all permissions (eg. gapps).
360 umask(0);
361
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700362 time_t start = time(nullptr);
363
Tao Bao6d99d4b2018-04-25 16:47:04 -0700364 // redirect_stdio should be called only in non-sideload mode. Otherwise we may have two logger
365 // instances with different timestamps.
366 redirect_stdio(Paths::Get().temporary_log_file().c_str());
367
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700368 load_volume_table();
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700369
Tianjie Xub63a2212019-07-29 14:21:49 -0700370 std::string stage;
371 std::vector<std::string> args = get_args(argc, argv, &stage);
Tao Bao1700cc42018-07-16 22:09:59 -0700372 auto args_to_parse = StringVectorToNullTerminatedArray(args);
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700373
374 static constexpr struct option OPTIONS[] = {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700375 { "fastboot", no_argument, nullptr, 0 },
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700376 { "locale", required_argument, nullptr, 0 },
Tianjie Xub63a2212019-07-29 14:21:49 -0700377 { "reason", required_argument, nullptr, 0 },
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700378 { "show_text", no_argument, nullptr, 't' },
379 { nullptr, 0, nullptr, 0 },
380 };
381
382 bool show_text = false;
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700383 bool fastboot = false;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700384 std::string locale;
Tianjie Xub63a2212019-07-29 14:21:49 -0700385 std::string reason;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700386
Tao Baoff185862019-09-18 13:28:32 -0700387 // The code here is only interested in the options that signal the intent to start fastbootd or
388 // recovery. Unrecognized options are likely meant for recovery, which will be processed later in
389 // start_recovery(). Suppress the warnings for such -- even if some flags were indeed invalid, the
390 // code in start_recovery() will capture and report them.
391 opterr = 0;
392
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700393 int arg;
394 int option_index;
Tao Bao1700cc42018-07-16 22:09:59 -0700395 while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700396 &option_index)) != -1) {
397 switch (arg) {
398 case 't':
399 show_text = true;
400 break;
401 case 0: {
402 std::string option = OPTIONS[option_index].name;
403 if (option == "locale") {
404 locale = optarg;
Tianjie Xub63a2212019-07-29 14:21:49 -0700405 } else if (option == "reason") {
406 reason = optarg;
Hridya Valsaraju7f41a2c2018-09-19 16:29:01 -0700407 } else if (option == "fastboot" &&
Alessandro Astoneb9f974d2020-02-26 17:25:54 +0100408 (android::base::GetBoolProperty("ro.boot.dynamic_partitions", false) ||
409 android::base::GetBoolProperty("ro.fastbootd.available", false))) {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700410 fastboot = true;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700411 }
412 break;
413 }
414 }
415 }
Jerry Zhang49fd5d22018-05-17 12:54:41 -0700416 optind = 1;
Tao Baoff185862019-09-18 13:28:32 -0700417 opterr = 1;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700418
419 if (locale.empty()) {
Tianjie Xu164c60a2019-05-15 13:59:39 -0700420 if (HasCache()) {
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700421 locale = load_locale_from_cache();
422 }
423
424 if (locale.empty()) {
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700425 locale = DEFAULT_LOCALE;
426 }
427 }
428
Tao Bao42c45e22018-07-31 09:37:12 -0700429 static constexpr const char* kDefaultLibRecoveryUIExt = "librecovery_ui_ext.so";
430 // Intentionally not calling dlclose(3) to avoid potential gotchas (e.g. `make_device` may have
431 // handed out pointers to code or static [or thread-local] data and doesn't collect them all back
432 // in on dlclose).
433 void* librecovery_ui_ext = dlopen(kDefaultLibRecoveryUIExt, RTLD_NOW);
434
435 using MakeDeviceType = decltype(&make_device);
436 MakeDeviceType make_device_func = nullptr;
437 if (librecovery_ui_ext == nullptr) {
438 printf("Failed to dlopen %s: %s\n", kDefaultLibRecoveryUIExt, dlerror());
439 } else {
440 reinterpret_cast<void*&>(make_device_func) = dlsym(librecovery_ui_ext, "make_device");
441 if (make_device_func == nullptr) {
442 printf("Failed to dlsym make_device: %s\n", dlerror());
443 }
444 }
445
446 Device* device;
447 if (make_device_func == nullptr) {
448 printf("Falling back to the default make_device() instead\n");
449 device = make_device();
450 } else {
451 printf("Loading make_device from %s\n", kDefaultLibRecoveryUIExt);
452 device = (*make_device_func)();
453 }
454
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700455 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
456 printf("Quiescent recovery mode.\n");
457 device->ResetUI(new StubRecoveryUI());
458 } else {
459 if (!device->GetUI()->Init(locale)) {
460 printf("Failed to initialize UI; using stub UI instead.\n");
461 device->ResetUI(new StubRecoveryUI());
462 }
463 }
Tianjie Xub63a2212019-07-29 14:21:49 -0700464
465 BootState boot_state(reason, stage); // recovery_main owns the state of boot.
466 device->SetBootState(&boot_state);
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700467 ui = device->GetUI();
468
Tianjie Xu164c60a2019-05-15 13:59:39 -0700469 if (!HasCache()) {
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700470 device->RemoveMenuItemForAction(Device::WIPE_CACHE);
471 }
472
Richard Hansenf09adaa2020-05-04 20:46:09 -0400473 if (android::base::GetBoolProperty("ro.build.ab_update", false)) {
474 // There's not much point in formatting the active slot's system partition
475 // because ROMs are flashed to the inactive slot. Removing the menu option
476 // prevents users from accidentally trashing a functioning ROM.
477 device->RemoveMenuItemForAction(Device::WIPE_SYSTEM);
478 }
479
Alessandro Astoneb9f974d2020-02-26 17:25:54 +0100480 if (!android::base::GetBoolProperty("ro.boot.dynamic_partitions", false) &&
481 !android::base::GetBoolProperty("ro.fastbootd.available", false)) {
Hridya Valsarajudaa301e2018-09-18 14:48:01 -0700482 device->RemoveMenuItemForAction(Device::ENTER_FASTBOOT);
483 }
484
Michael Bestas93cd1272019-09-27 20:29:42 +0300485 if (get_build_type() != "eng") {
486 device->RemoveMenuItemForAction(Device::RUN_GRAPHICS_TEST);
487 device->RemoveMenuItemForAction(Device::RUN_LOCALE_TEST);
Tao Baoc6dc3252019-04-16 14:22:25 -0700488 device->RemoveMenuItemForAction(Device::ENTER_RESCUE);
489 }
490
LuK13376422b8f2020-04-12 19:04:59 +0200491 if (get_build_type() != "userdebug") {
492 device->RemoveMenuItemForAction(Device::ENABLE_ADB);
493 }
494
Luca Stefani45628f02020-03-14 00:12:18 +0100495 if (get_build_type() == "user") {
496 device->RemoveMenuItemForAction(Device::WIPE_SYSTEM);
497 device->RemoveMenuItemForAction(Device::MOUNT_SYSTEM);
498 }
499
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700500 ui->SetBackground(RecoveryUI::NONE);
501 if (show_text) ui->ShowText(true);
502
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700503 LOG(INFO) << "Starting recovery (pid " << getpid() << ") on " << ctime(&start);
504 LOG(INFO) << "locale is [" << locale << "]";
505
Tianjie Xu164c60a2019-05-15 13:59:39 -0700506 auto sehandle = selinux_android_file_context_handle();
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700507 selinux_android_set_sehandle(sehandle);
508 if (!sehandle) {
509 ui->Print("Warning: No file_contexts\n");
510 }
511
xunchang2239b9e2019-04-15 15:24:24 -0700512 SetLoggingSehandle(sehandle);
xunchang316e9712019-04-12 16:22:15 -0700513
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700514 std::atomic<Device::BuiltinAction> action;
515 std::thread listener_thread(ListenRecoverySocket, ui, std::ref(action));
516 listener_thread.detach();
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700517
Steve Kondik54987762013-10-19 19:49:20 -0700518 // Set up adb_keys and enable root before starting ADB.
519 if (IsRoDebuggable() && !fastboot) {
520 copy_userdata_files();
521 android::base::SetProperty("service.adb.root", "1");
522 }
523
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700524 while (true) {
Tianjie Xu7d5c3412019-10-29 21:44:39 -0700525 // We start adbd in recovery for the device with userdebug build or a unlocked bootloader.
526 std::string usb_config =
527 fastboot ? "fastboot" : IsRoDebuggable() || IsDeviceUnlocked() ? "adb" : "none";
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700528 std::string usb_state = android::base::GetProperty("sys.usb.state", "none");
Hongguang Chen04267272020-04-21 20:58:04 -0700529 if (fastboot) {
530 device->PreFastboot();
531 } else {
532 device->PreRecovery();
533 }
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700534 if (usb_config != usb_state) {
535 if (!SetUsbConfig("none")) {
536 LOG(ERROR) << "Failed to clear USB config";
537 }
538 if (!SetUsbConfig(usb_config)) {
539 LOG(ERROR) << "Failed to set USB config to " << usb_config;
540 }
541 }
542
David Anderson983e2d52019-01-02 11:35:38 -0800543 ui->SetEnableFastbootdLogo(fastboot);
544
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700545 auto ret = fastboot ? StartFastboot(device, args) : start_recovery(device, args);
546
547 if (ret == Device::KEY_INTERRUPTED) {
548 ret = action.exchange(ret);
549 if (ret == Device::NO_ACTION) {
550 continue;
551 }
552 }
553 switch (ret) {
554 case Device::SHUTDOWN:
555 ui->Print("Shutting down...\n");
Mark Salyzyn488cc052019-05-20 10:36:16 -0700556 Shutdown("userrequested,recovery");
557 break;
558
559 case Device::SHUTDOWN_FROM_FASTBOOT:
560 ui->Print("Shutting down...\n");
561 Shutdown("userrequested,fastboot");
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700562 break;
563
564 case Device::REBOOT_BOOTLOADER:
565 ui->Print("Rebooting to bootloader...\n");
Tao Bao782dcc12019-04-29 11:23:16 -0700566 Reboot("bootloader");
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700567 break;
568
Tao Baod9cb0142019-04-23 11:46:25 -0700569 case Device::REBOOT_FASTBOOT:
570 ui->Print("Rebooting to recovery/fastboot...\n");
Tao Bao782dcc12019-04-29 11:23:16 -0700571 Reboot("fastboot");
Tao Bao10f441a2019-04-19 15:22:15 -0700572 break;
573
Tao Baod9cb0142019-04-23 11:46:25 -0700574 case Device::REBOOT_RECOVERY:
575 ui->Print("Rebooting to recovery...\n");
Tao Bao782dcc12019-04-29 11:23:16 -0700576 Reboot("recovery");
Tao Baod9cb0142019-04-23 11:46:25 -0700577 break;
578
579 case Device::REBOOT_RESCUE: {
Tao Bao782dcc12019-04-29 11:23:16 -0700580 // Not using `Reboot("rescue")`, as it requires matching support in kernel and/or
Tao Baod9cb0142019-04-23 11:46:25 -0700581 // bootloader.
582 bootloader_message boot = {};
583 strlcpy(boot.command, "boot-rescue", sizeof(boot.command));
584 std::string err;
585 if (!write_bootloader_message(boot, &err)) {
586 LOG(ERROR) << "Failed to write bootloader message: " << err;
587 // Stay under recovery on failure.
588 continue;
589 }
590 ui->Print("Rebooting to recovery/rescue...\n");
Tao Bao782dcc12019-04-29 11:23:16 -0700591 Reboot("recovery");
Tao Baod9cb0142019-04-23 11:46:25 -0700592 break;
593 }
594
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700595 case Device::ENTER_FASTBOOT:
Erfan Abdia24643e2020-04-14 23:07:33 +0430596 if (logical_partitions_mapped()) {
David Anderson2b2f4232018-10-29 18:48:56 -0700597 ui->Print("Partitions may be mounted - rebooting to enter fastboot.");
Tao Bao782dcc12019-04-29 11:23:16 -0700598 Reboot("fastboot");
David Anderson2b2f4232018-10-29 18:48:56 -0700599 } else {
600 LOG(INFO) << "Entering fastboot";
601 fastboot = true;
602 }
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700603 break;
604
605 case Device::ENTER_RECOVERY:
606 LOG(INFO) << "Entering recovery";
607 fastboot = false;
Tom Marshall88fe6f52020-03-29 14:36:57 +0200608 device->GoHome();
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700609 break;
610
Mark Salyzyn488cc052019-05-20 10:36:16 -0700611 case Device::REBOOT:
612 ui->Print("Rebooting...\n");
613 Reboot("userrequested,recovery");
614 break;
615
616 case Device::REBOOT_FROM_FASTBOOT:
617 ui->Print("Rebooting...\n");
618 Reboot("userrequested,fastboot");
619 break;
620
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700621 default:
622 ui->Print("Rebooting...\n");
Mark Salyzyn488cc052019-05-20 10:36:16 -0700623 Reboot("unknown" + std::to_string(ret));
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700624 break;
625 }
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700626 }
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700627
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700628 // Should be unreachable.
629 return EXIT_SUCCESS;
Tao Bao6d99d4b2018-04-25 16:47:04 -0700630}