blob: 4c8eb40314e20f4f9a8d862cb4ba560ac0939fb9 [file] [log] [blame]
Tao Bao6d99d4b2018-04-25 16:47:04 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
Steve Kondika90d0162013-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 Kondika90d0162013-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 Kondika90d0162013-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 Marshall3c709de2018-06-21 00:57:24 +020080std::string get_build_type() {
Michael Bestas447e3d92019-09-27 20:29:42 +030081 return android::base::GetProperty("ro.build.type", "");
82}
83
Steve Kondika90d0162013-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
Kelvin Zhang3d0d9c32022-04-20 14:51:30 -070087static void UiLogger(android::base::LogId log_buffer_id, android::base::LogSeverity severity,
88 const char* tag, const char* file, unsigned int line, const char* message) {
89 android::base::KernelLogger(log_buffer_id, severity, tag, file, line, message);
90 static constexpr auto&& log_characters = "VDIWEF";
Tao Bao6d99d4b2018-04-25 16:47:04 -070091 if (severity >= android::base::ERROR && ui != nullptr) {
Kelvin Zhang3d0d9c32022-04-20 14:51:30 -070092 ui->Print("ERROR: %10s: %s\n", tag, message);
Tao Bao6d99d4b2018-04-25 16:47:04 -070093 } 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 Kondika90d0162013-10-19 19:49:20 -0700200static void copy_userdata_files() {
Alessandro82fb0fa2020-04-06 23:55:07 +0200201 android::base::SetLogger(android::base::StdioLogger);
Steve Kondika90d0162013-10-19 19:49:20 -0700202 if (ensure_path_mounted("/data") == 0) {
203 if (access(adb_keys_root, F_OK) != 0) {
204 if (access(adb_keys_data, R_OK) == 0) {
205 std::error_code ec; // to invoke the overloaded copy_file() that won't throw.
206 if (!fs::copy_file(adb_keys_data, adb_keys_root, ec)) {
207 PLOG(ERROR) << "Failed to copy adb keys";
208 }
209 }
210 }
211 ensure_path_unmounted("/data");
212 }
Alessandro82fb0fa2020-04-06 23:55:07 +0200213 android::base::SetLogger(UiLogger);
Steve Kondika90d0162013-10-19 19:49:20 -0700214}
215
Tao Baoe0cfab32019-03-29 15:53:23 -0700216// Sets the usb config to 'state'.
217static bool SetUsbConfig(const std::string& state) {
218 android::base::SetProperty("sys.usb.config", state);
219 return android::base::WaitForProperty("sys.usb.state", state);
220}
221
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700222static void ListenRecoverySocket(RecoveryUI* ui, std::atomic<Device::BuiltinAction>& action) {
223 android::base::unique_fd sock_fd(android_get_control_socket("recovery"));
224 if (sock_fd < 0) {
225 PLOG(ERROR) << "Failed to open recovery socket";
226 return;
227 }
228 listen(sock_fd, 4);
229
230 while (true) {
231 android::base::unique_fd connection_fd;
232 connection_fd.reset(accept(sock_fd, nullptr, nullptr));
233 if (connection_fd < 0) {
234 PLOG(ERROR) << "Failed to accept socket connection";
235 continue;
236 }
237 char msg;
238 constexpr char kSwitchToFastboot = 'f';
239 constexpr char kSwitchToRecovery = 'r';
240 ssize_t ret = TEMP_FAILURE_RETRY(read(connection_fd, &msg, sizeof(msg)));
241 if (ret != sizeof(msg)) {
242 PLOG(ERROR) << "Couldn't read from socket";
243 continue;
244 }
245 switch (msg) {
246 case kSwitchToRecovery:
247 action = Device::BuiltinAction::ENTER_RECOVERY;
248 break;
249 case kSwitchToFastboot:
250 action = Device::BuiltinAction::ENTER_FASTBOOT;
251 break;
252 default:
253 LOG(ERROR) << "Unrecognized char from socket " << msg;
254 continue;
255 }
256 ui->InterruptKey();
257 }
258}
259
Tao Bao6d99d4b2018-04-25 16:47:04 -0700260static void redirect_stdio(const char* filename) {
Tao Bao6fcd2082019-01-16 09:29:17 -0800261 android::base::unique_fd pipe_read, pipe_write;
262 // Create a pipe that allows parent process sending logs over.
263 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
264 PLOG(ERROR) << "Failed to create pipe for redirecting stdio";
Tao Bao6d99d4b2018-04-25 16:47:04 -0700265
266 // Fall back to traditional logging mode without timestamps. If these fail, there's not really
267 // anywhere to complain...
268 freopen(filename, "a", stdout);
269 setbuf(stdout, nullptr);
270 freopen(filename, "a", stderr);
271 setbuf(stderr, nullptr);
272
273 return;
274 }
275
276 pid_t pid = fork();
277 if (pid == -1) {
Tao Bao6fcd2082019-01-16 09:29:17 -0800278 PLOG(ERROR) << "Failed to fork for redirecting stdio";
Tao Bao6d99d4b2018-04-25 16:47:04 -0700279
280 // Fall back to traditional logging mode without timestamps. If these fail, there's not really
281 // anywhere to complain...
282 freopen(filename, "a", stdout);
283 setbuf(stdout, nullptr);
284 freopen(filename, "a", stderr);
285 setbuf(stderr, nullptr);
286
287 return;
288 }
289
290 if (pid == 0) {
Tao Bao6fcd2082019-01-16 09:29:17 -0800291 // Child process reads the incoming logs and doesn't write to the pipe.
292 pipe_write.reset();
Tao Bao6d99d4b2018-04-25 16:47:04 -0700293
294 auto start = std::chrono::steady_clock::now();
295
296 // Child logger to actually write to the log file.
297 FILE* log_fp = fopen(filename, "ae");
298 if (log_fp == nullptr) {
299 PLOG(ERROR) << "fopen \"" << filename << "\" failed";
Tao Bao6d99d4b2018-04-25 16:47:04 -0700300 _exit(EXIT_FAILURE);
301 }
302
Tao Bao6fcd2082019-01-16 09:29:17 -0800303 FILE* pipe_fp = android::base::Fdopen(std::move(pipe_read), "r");
Tao Bao6d99d4b2018-04-25 16:47:04 -0700304 if (pipe_fp == nullptr) {
305 PLOG(ERROR) << "fdopen failed";
306 check_and_fclose(log_fp, filename);
Tao Bao6d99d4b2018-04-25 16:47:04 -0700307 _exit(EXIT_FAILURE);
308 }
309
310 char* line = nullptr;
311 size_t len = 0;
312 while (getline(&line, &len, pipe_fp) != -1) {
313 auto now = std::chrono::steady_clock::now();
314 double duration =
315 std::chrono::duration_cast<std::chrono::duration<double>>(now - start).count();
316 if (line[0] == '\n') {
317 fprintf(log_fp, "[%12.6lf]\n", duration);
318 } else {
319 fprintf(log_fp, "[%12.6lf] %s", duration, line);
320 }
321 fflush(log_fp);
322 }
323
324 PLOG(ERROR) << "getline failed";
325
Tao Bao6fcd2082019-01-16 09:29:17 -0800326 fclose(pipe_fp);
Tao Bao6d99d4b2018-04-25 16:47:04 -0700327 free(line);
328 check_and_fclose(log_fp, filename);
Tao Bao6d99d4b2018-04-25 16:47:04 -0700329 _exit(EXIT_FAILURE);
330 } else {
331 // Redirect stdout/stderr to the logger process. Close the unused read end.
Tao Bao6fcd2082019-01-16 09:29:17 -0800332 pipe_read.reset();
Tao Bao6d99d4b2018-04-25 16:47:04 -0700333
334 setbuf(stdout, nullptr);
335 setbuf(stderr, nullptr);
336
Tao Bao6fcd2082019-01-16 09:29:17 -0800337 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
Tao Bao6d99d4b2018-04-25 16:47:04 -0700338 PLOG(ERROR) << "dup2 stdout failed";
339 }
Tao Bao6fcd2082019-01-16 09:29:17 -0800340 if (dup2(pipe_write.get(), STDERR_FILENO) == -1) {
Tao Bao6d99d4b2018-04-25 16:47:04 -0700341 PLOG(ERROR) << "dup2 stderr failed";
342 }
Tao Bao6d99d4b2018-04-25 16:47:04 -0700343 }
344}
345
346int main(int argc, char** argv) {
347 // We don't have logcat yet under recovery; so we'll print error on screen and log to stdout
348 // (which is redirected to recovery.log) as we used to do.
349 android::base::InitLogging(argv, &UiLogger);
350
351 // Take last pmsg contents and rewrite it to the current pmsg session.
352 static constexpr const char filter[] = "recovery/";
353 // Do we need to rotate?
354 bool do_rotate = false;
355
356 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logbasename, &do_rotate);
357 // Take action to refresh pmsg contents
358 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logrotate, &do_rotate);
359
Steve Kondika90d0162013-10-19 19:49:20 -0700360 // Clear umask for packages that copy files out to /tmp and then over
361 // to /system without properly setting all permissions (eg. gapps).
362 umask(0);
363
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700364 time_t start = time(nullptr);
365
Tao Bao6d99d4b2018-04-25 16:47:04 -0700366 // redirect_stdio should be called only in non-sideload mode. Otherwise we may have two logger
367 // instances with different timestamps.
368 redirect_stdio(Paths::Get().temporary_log_file().c_str());
369
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700370 load_volume_table();
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700371
Tianjie Xub63a2212019-07-29 14:21:49 -0700372 std::string stage;
373 std::vector<std::string> args = get_args(argc, argv, &stage);
Tao Bao1700cc42018-07-16 22:09:59 -0700374 auto args_to_parse = StringVectorToNullTerminatedArray(args);
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700375
376 static constexpr struct option OPTIONS[] = {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700377 { "fastboot", no_argument, nullptr, 0 },
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700378 { "locale", required_argument, nullptr, 0 },
Tianjie Xub63a2212019-07-29 14:21:49 -0700379 { "reason", required_argument, nullptr, 0 },
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700380 { "show_text", no_argument, nullptr, 't' },
381 { nullptr, 0, nullptr, 0 },
382 };
383
384 bool show_text = false;
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700385 bool fastboot = false;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700386 std::string locale;
Tianjie Xub63a2212019-07-29 14:21:49 -0700387 std::string reason;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700388
Tao Baoff185862019-09-18 13:28:32 -0700389 // The code here is only interested in the options that signal the intent to start fastbootd or
390 // recovery. Unrecognized options are likely meant for recovery, which will be processed later in
391 // start_recovery(). Suppress the warnings for such -- even if some flags were indeed invalid, the
392 // code in start_recovery() will capture and report them.
393 opterr = 0;
394
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700395 int arg;
396 int option_index;
Tao Bao1700cc42018-07-16 22:09:59 -0700397 while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700398 &option_index)) != -1) {
399 switch (arg) {
400 case 't':
401 show_text = true;
402 break;
403 case 0: {
404 std::string option = OPTIONS[option_index].name;
405 if (option == "locale") {
406 locale = optarg;
Tianjie Xub63a2212019-07-29 14:21:49 -0700407 } else if (option == "reason") {
408 reason = optarg;
Hridya Valsaraju7f41a2c2018-09-19 16:29:01 -0700409 } else if (option == "fastboot" &&
Alessandro Astoneda1675f2020-02-26 17:25:54 +0100410 (android::base::GetBoolProperty("ro.boot.dynamic_partitions", false) ||
411 android::base::GetBoolProperty("ro.fastbootd.available", false))) {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700412 fastboot = true;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700413 }
414 break;
415 }
416 }
417 }
Jerry Zhang49fd5d22018-05-17 12:54:41 -0700418 optind = 1;
Tao Baoff185862019-09-18 13:28:32 -0700419 opterr = 1;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700420
421 if (locale.empty()) {
Tianjie Xu164c60a2019-05-15 13:59:39 -0700422 if (HasCache()) {
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700423 locale = load_locale_from_cache();
424 }
425
426 if (locale.empty()) {
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700427 locale = DEFAULT_LOCALE;
428 }
429 }
430
Tao Bao42c45e22018-07-31 09:37:12 -0700431 static constexpr const char* kDefaultLibRecoveryUIExt = "librecovery_ui_ext.so";
432 // Intentionally not calling dlclose(3) to avoid potential gotchas (e.g. `make_device` may have
433 // handed out pointers to code or static [or thread-local] data and doesn't collect them all back
434 // in on dlclose).
435 void* librecovery_ui_ext = dlopen(kDefaultLibRecoveryUIExt, RTLD_NOW);
436
437 using MakeDeviceType = decltype(&make_device);
438 MakeDeviceType make_device_func = nullptr;
439 if (librecovery_ui_ext == nullptr) {
440 printf("Failed to dlopen %s: %s\n", kDefaultLibRecoveryUIExt, dlerror());
441 } else {
442 reinterpret_cast<void*&>(make_device_func) = dlsym(librecovery_ui_ext, "make_device");
443 if (make_device_func == nullptr) {
444 printf("Failed to dlsym make_device: %s\n", dlerror());
445 }
446 }
447
448 Device* device;
449 if (make_device_func == nullptr) {
450 printf("Falling back to the default make_device() instead\n");
451 device = make_device();
452 } else {
453 printf("Loading make_device from %s\n", kDefaultLibRecoveryUIExt);
454 device = (*make_device_func)();
455 }
456
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700457 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
458 printf("Quiescent recovery mode.\n");
459 device->ResetUI(new StubRecoveryUI());
460 } else {
461 if (!device->GetUI()->Init(locale)) {
462 printf("Failed to initialize UI; using stub UI instead.\n");
463 device->ResetUI(new StubRecoveryUI());
464 }
465 }
Tianjie Xub63a2212019-07-29 14:21:49 -0700466
467 BootState boot_state(reason, stage); // recovery_main owns the state of boot.
468 device->SetBootState(&boot_state);
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700469 ui = device->GetUI();
470
Tianjie Xu164c60a2019-05-15 13:59:39 -0700471 if (!HasCache()) {
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700472 device->RemoveMenuItemForAction(Device::WIPE_CACHE);
473 }
474
Richard Hansenb6a02ea2020-05-04 20:46:09 -0400475 if (android::base::GetBoolProperty("ro.build.ab_update", false)) {
476 // There's not much point in formatting the active slot's system partition
477 // because ROMs are flashed to the inactive slot. Removing the menu option
478 // prevents users from accidentally trashing a functioning ROM.
479 device->RemoveMenuItemForAction(Device::WIPE_SYSTEM);
480 }
481
Alessandro Astoneda1675f2020-02-26 17:25:54 +0100482 if (!android::base::GetBoolProperty("ro.boot.dynamic_partitions", false) &&
483 !android::base::GetBoolProperty("ro.fastbootd.available", false)) {
Hridya Valsarajudaa301e2018-09-18 14:48:01 -0700484 device->RemoveMenuItemForAction(Device::ENTER_FASTBOOT);
485 }
486
Michael Bestas447e3d92019-09-27 20:29:42 +0300487 if (get_build_type() != "eng") {
488 device->RemoveMenuItemForAction(Device::RUN_GRAPHICS_TEST);
489 device->RemoveMenuItemForAction(Device::RUN_LOCALE_TEST);
Tao Baoc6dc3252019-04-16 14:22:25 -0700490 device->RemoveMenuItemForAction(Device::ENTER_RESCUE);
491 }
492
LuK1337588c5f92020-04-12 19:04:59 +0200493 if (get_build_type() != "userdebug") {
494 device->RemoveMenuItemForAction(Device::ENABLE_ADB);
495 }
496
Luca Stefani81efcd02020-03-14 00:12:18 +0100497 if (get_build_type() == "user") {
498 device->RemoveMenuItemForAction(Device::WIPE_SYSTEM);
499 device->RemoveMenuItemForAction(Device::MOUNT_SYSTEM);
500 }
501
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700502 ui->SetBackground(RecoveryUI::NONE);
503 if (show_text) ui->ShowText(true);
504
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700505 LOG(INFO) << "Starting recovery (pid " << getpid() << ") on " << ctime(&start);
506 LOG(INFO) << "locale is [" << locale << "]";
507
Tianjie Xu164c60a2019-05-15 13:59:39 -0700508 auto sehandle = selinux_android_file_context_handle();
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700509 selinux_android_set_sehandle(sehandle);
510 if (!sehandle) {
511 ui->Print("Warning: No file_contexts\n");
512 }
513
xunchang2239b9e2019-04-15 15:24:24 -0700514 SetLoggingSehandle(sehandle);
xunchang316e9712019-04-12 16:22:15 -0700515
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700516 std::atomic<Device::BuiltinAction> action;
517 std::thread listener_thread(ListenRecoverySocket, ui, std::ref(action));
518 listener_thread.detach();
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700519
Steve Kondika90d0162013-10-19 19:49:20 -0700520 // Set up adb_keys and enable root before starting ADB.
521 if (IsRoDebuggable() && !fastboot) {
522 copy_userdata_files();
523 android::base::SetProperty("service.adb.root", "1");
524 }
525
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700526 while (true) {
Tianjie Xu7d5c3412019-10-29 21:44:39 -0700527 // We start adbd in recovery for the device with userdebug build or a unlocked bootloader.
528 std::string usb_config =
529 fastboot ? "fastboot" : IsRoDebuggable() || IsDeviceUnlocked() ? "adb" : "none";
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700530 std::string usb_state = android::base::GetProperty("sys.usb.state", "none");
Hongguang Chen04267272020-04-21 20:58:04 -0700531 if (fastboot) {
532 device->PreFastboot();
533 } else {
534 device->PreRecovery();
535 }
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700536 if (usb_config != usb_state) {
537 if (!SetUsbConfig("none")) {
538 LOG(ERROR) << "Failed to clear USB config";
539 }
540 if (!SetUsbConfig(usb_config)) {
541 LOG(ERROR) << "Failed to set USB config to " << usb_config;
542 }
543 }
544
David Anderson983e2d52019-01-02 11:35:38 -0800545 ui->SetEnableFastbootdLogo(fastboot);
546
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700547 auto ret = fastboot ? StartFastboot(device, args) : start_recovery(device, args);
548
549 if (ret == Device::KEY_INTERRUPTED) {
550 ret = action.exchange(ret);
551 if (ret == Device::NO_ACTION) {
552 continue;
553 }
554 }
555 switch (ret) {
556 case Device::SHUTDOWN:
557 ui->Print("Shutting down...\n");
Mark Salyzyn488cc052019-05-20 10:36:16 -0700558 Shutdown("userrequested,recovery");
559 break;
560
561 case Device::SHUTDOWN_FROM_FASTBOOT:
562 ui->Print("Shutting down...\n");
563 Shutdown("userrequested,fastboot");
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700564 break;
565
566 case Device::REBOOT_BOOTLOADER:
567 ui->Print("Rebooting to bootloader...\n");
Tao Bao782dcc12019-04-29 11:23:16 -0700568 Reboot("bootloader");
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700569 break;
570
Tao Baod9cb0142019-04-23 11:46:25 -0700571 case Device::REBOOT_FASTBOOT:
572 ui->Print("Rebooting to recovery/fastboot...\n");
Tao Bao782dcc12019-04-29 11:23:16 -0700573 Reboot("fastboot");
Tao Bao10f441a2019-04-19 15:22:15 -0700574 break;
575
Tao Baod9cb0142019-04-23 11:46:25 -0700576 case Device::REBOOT_RECOVERY:
577 ui->Print("Rebooting to recovery...\n");
Tao Bao782dcc12019-04-29 11:23:16 -0700578 Reboot("recovery");
Tao Baod9cb0142019-04-23 11:46:25 -0700579 break;
580
581 case Device::REBOOT_RESCUE: {
Tao Bao782dcc12019-04-29 11:23:16 -0700582 // Not using `Reboot("rescue")`, as it requires matching support in kernel and/or
Tao Baod9cb0142019-04-23 11:46:25 -0700583 // bootloader.
584 bootloader_message boot = {};
585 strlcpy(boot.command, "boot-rescue", sizeof(boot.command));
586 std::string err;
587 if (!write_bootloader_message(boot, &err)) {
588 LOG(ERROR) << "Failed to write bootloader message: " << err;
589 // Stay under recovery on failure.
590 continue;
591 }
592 ui->Print("Rebooting to recovery/rescue...\n");
Tao Bao782dcc12019-04-29 11:23:16 -0700593 Reboot("recovery");
Tao Baod9cb0142019-04-23 11:46:25 -0700594 break;
595 }
596
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700597 case Device::ENTER_FASTBOOT:
Erfan Abdi700ee7b2020-04-14 23:07:33 +0430598 if (logical_partitions_mapped()) {
David Anderson2b2f4232018-10-29 18:48:56 -0700599 ui->Print("Partitions may be mounted - rebooting to enter fastboot.");
Tao Bao782dcc12019-04-29 11:23:16 -0700600 Reboot("fastboot");
David Anderson2b2f4232018-10-29 18:48:56 -0700601 } else {
602 LOG(INFO) << "Entering fastboot";
603 fastboot = true;
604 }
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700605 break;
606
607 case Device::ENTER_RECOVERY:
608 LOG(INFO) << "Entering recovery";
609 fastboot = false;
Tom Marshall62676152020-03-29 14:36:57 +0200610 device->GoHome();
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700611 break;
612
Mark Salyzyn488cc052019-05-20 10:36:16 -0700613 case Device::REBOOT:
614 ui->Print("Rebooting...\n");
615 Reboot("userrequested,recovery");
616 break;
617
618 case Device::REBOOT_FROM_FASTBOOT:
619 ui->Print("Rebooting...\n");
620 Reboot("userrequested,fastboot");
621 break;
622
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700623 default:
624 ui->Print("Rebooting...\n");
Mark Salyzyn488cc052019-05-20 10:36:16 -0700625 Reboot("unknown" + std::to_string(ret));
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700626 break;
627 }
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700628 }
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700629
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700630 // Should be unreachable.
631 return EXIT_SUCCESS;
Tao Bao6d99d4b2018-04-25 16:47:04 -0700632}