blob: f23c86b02eceb1b5c52e6431752be7ca8cffb15d [file] [log] [blame]
Tao Bao6d99d4b2018-04-25 16:47:04 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
Steve Kondikf1e0f172013-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 Kondikf1e0f172013-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 Kondikf1e0f172013-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 Marshall70e6f562018-06-21 00:57:24 +020080std::string get_build_type() {
Michael Bestas680527d2019-09-27 20:29:42 +030081 return android::base::GetProperty("ro.build.type", "");
82}
83
Steve Kondikf1e0f172013-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 }
Kelvin Zhang73549942024-01-04 16:43:53 -0800144 LOG(INFO) << "Got " << args.size() << " arguments from boot message " << android::base::Join(args, ", ");
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700145 } 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.
Roy Luocdcdf522024-04-05 18:06:52 +0000169 // This should only be done for boot-recovery command so that other commands
170 // won't be overwritten.
171 if (boot_command == "boot-recovery") {
172 std::vector<std::string> options(args.cbegin() + 1, args.cend());
173 if (!update_bootloader_message(options, &err)) {
174 LOG(ERROR) << "Failed to set BCB message: " << err;
175 }
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700176 }
177
David Andersoneee4e262018-08-21 13:10:45 -0700178 // Finally, if no arguments were specified, check whether we should boot
Tao Baod9cb0142019-04-23 11:46:25 -0700179 // into fastboot or rescue mode.
David Andersoneee4e262018-08-21 13:10:45 -0700180 if (args.size() == 1 && boot_command == "boot-fastboot") {
181 args.emplace_back("--fastboot");
Tao Baod9cb0142019-04-23 11:46:25 -0700182 } else if (args.size() == 1 && boot_command == "boot-rescue") {
183 args.emplace_back("--rescue");
David Andersoneee4e262018-08-21 13:10:45 -0700184 }
185
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700186 return args;
187}
188
189static std::string load_locale_from_cache() {
190 if (ensure_path_mounted(LOCALE_FILE) != 0) {
191 LOG(ERROR) << "Can't mount " << LOCALE_FILE;
192 return "";
193 }
194
195 std::string content;
196 if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
197 PLOG(ERROR) << "Can't read " << LOCALE_FILE;
198 return "";
199 }
200
201 return android::base::Trim(content);
202}
203
Steve Kondikf1e0f172013-10-19 19:49:20 -0700204static void copy_userdata_files() {
Alessandro392d8132020-04-06 23:55:07 +0200205 android::base::SetLogger(android::base::StdioLogger);
Steve Kondikf1e0f172013-10-19 19:49:20 -0700206 if (ensure_path_mounted("/data") == 0) {
207 if (access(adb_keys_root, F_OK) != 0) {
208 if (access(adb_keys_data, R_OK) == 0) {
209 std::error_code ec; // to invoke the overloaded copy_file() that won't throw.
210 if (!fs::copy_file(adb_keys_data, adb_keys_root, ec)) {
211 PLOG(ERROR) << "Failed to copy adb keys";
212 }
213 }
214 }
215 ensure_path_unmounted("/data");
216 }
Alessandro392d8132020-04-06 23:55:07 +0200217 android::base::SetLogger(UiLogger);
Steve Kondikf1e0f172013-10-19 19:49:20 -0700218}
219
Tao Baoe0cfab32019-03-29 15:53:23 -0700220// Sets the usb config to 'state'.
221static bool SetUsbConfig(const std::string& state) {
222 android::base::SetProperty("sys.usb.config", state);
223 return android::base::WaitForProperty("sys.usb.state", state);
224}
225
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700226static void ListenRecoverySocket(RecoveryUI* ui, std::atomic<Device::BuiltinAction>& action) {
227 android::base::unique_fd sock_fd(android_get_control_socket("recovery"));
228 if (sock_fd < 0) {
229 PLOG(ERROR) << "Failed to open recovery socket";
230 return;
231 }
232 listen(sock_fd, 4);
233
234 while (true) {
235 android::base::unique_fd connection_fd;
236 connection_fd.reset(accept(sock_fd, nullptr, nullptr));
237 if (connection_fd < 0) {
238 PLOG(ERROR) << "Failed to accept socket connection";
239 continue;
240 }
241 char msg;
242 constexpr char kSwitchToFastboot = 'f';
243 constexpr char kSwitchToRecovery = 'r';
244 ssize_t ret = TEMP_FAILURE_RETRY(read(connection_fd, &msg, sizeof(msg)));
245 if (ret != sizeof(msg)) {
246 PLOG(ERROR) << "Couldn't read from socket";
247 continue;
248 }
249 switch (msg) {
250 case kSwitchToRecovery:
251 action = Device::BuiltinAction::ENTER_RECOVERY;
252 break;
253 case kSwitchToFastboot:
254 action = Device::BuiltinAction::ENTER_FASTBOOT;
255 break;
256 default:
257 LOG(ERROR) << "Unrecognized char from socket " << msg;
258 continue;
259 }
260 ui->InterruptKey();
261 }
262}
263
Tao Bao6d99d4b2018-04-25 16:47:04 -0700264static void redirect_stdio(const char* filename) {
Tao Bao6fcd2082019-01-16 09:29:17 -0800265 android::base::unique_fd pipe_read, pipe_write;
266 // Create a pipe that allows parent process sending logs over.
267 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
268 PLOG(ERROR) << "Failed to create pipe for redirecting stdio";
Tao Bao6d99d4b2018-04-25 16:47:04 -0700269
270 // Fall back to traditional logging mode without timestamps. If these fail, there's not really
271 // anywhere to complain...
272 freopen(filename, "a", stdout);
273 setbuf(stdout, nullptr);
274 freopen(filename, "a", stderr);
275 setbuf(stderr, nullptr);
276
277 return;
278 }
279
280 pid_t pid = fork();
281 if (pid == -1) {
Tao Bao6fcd2082019-01-16 09:29:17 -0800282 PLOG(ERROR) << "Failed to fork for redirecting stdio";
Tao Bao6d99d4b2018-04-25 16:47:04 -0700283
284 // Fall back to traditional logging mode without timestamps. If these fail, there's not really
285 // anywhere to complain...
286 freopen(filename, "a", stdout);
287 setbuf(stdout, nullptr);
288 freopen(filename, "a", stderr);
289 setbuf(stderr, nullptr);
290
291 return;
292 }
293
294 if (pid == 0) {
Tao Bao6fcd2082019-01-16 09:29:17 -0800295 // Child process reads the incoming logs and doesn't write to the pipe.
296 pipe_write.reset();
Tao Bao6d99d4b2018-04-25 16:47:04 -0700297
298 auto start = std::chrono::steady_clock::now();
299
300 // Child logger to actually write to the log file.
301 FILE* log_fp = fopen(filename, "ae");
302 if (log_fp == nullptr) {
303 PLOG(ERROR) << "fopen \"" << filename << "\" failed";
Tao Bao6d99d4b2018-04-25 16:47:04 -0700304 _exit(EXIT_FAILURE);
305 }
306
Tao Bao6fcd2082019-01-16 09:29:17 -0800307 FILE* pipe_fp = android::base::Fdopen(std::move(pipe_read), "r");
Tao Bao6d99d4b2018-04-25 16:47:04 -0700308 if (pipe_fp == nullptr) {
309 PLOG(ERROR) << "fdopen failed";
310 check_and_fclose(log_fp, filename);
Tao Bao6d99d4b2018-04-25 16:47:04 -0700311 _exit(EXIT_FAILURE);
312 }
313
314 char* line = nullptr;
315 size_t len = 0;
316 while (getline(&line, &len, pipe_fp) != -1) {
317 auto now = std::chrono::steady_clock::now();
318 double duration =
319 std::chrono::duration_cast<std::chrono::duration<double>>(now - start).count();
320 if (line[0] == '\n') {
321 fprintf(log_fp, "[%12.6lf]\n", duration);
322 } else {
323 fprintf(log_fp, "[%12.6lf] %s", duration, line);
324 }
325 fflush(log_fp);
326 }
327
328 PLOG(ERROR) << "getline failed";
329
Tao Bao6fcd2082019-01-16 09:29:17 -0800330 fclose(pipe_fp);
Tao Bao6d99d4b2018-04-25 16:47:04 -0700331 free(line);
332 check_and_fclose(log_fp, filename);
Tao Bao6d99d4b2018-04-25 16:47:04 -0700333 _exit(EXIT_FAILURE);
334 } else {
335 // Redirect stdout/stderr to the logger process. Close the unused read end.
Tao Bao6fcd2082019-01-16 09:29:17 -0800336 pipe_read.reset();
Tao Bao6d99d4b2018-04-25 16:47:04 -0700337
338 setbuf(stdout, nullptr);
339 setbuf(stderr, nullptr);
340
Tao Bao6fcd2082019-01-16 09:29:17 -0800341 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
Tao Bao6d99d4b2018-04-25 16:47:04 -0700342 PLOG(ERROR) << "dup2 stdout failed";
343 }
Tao Bao6fcd2082019-01-16 09:29:17 -0800344 if (dup2(pipe_write.get(), STDERR_FILENO) == -1) {
Tao Bao6d99d4b2018-04-25 16:47:04 -0700345 PLOG(ERROR) << "dup2 stderr failed";
346 }
Tao Bao6d99d4b2018-04-25 16:47:04 -0700347 }
348}
349
350int main(int argc, char** argv) {
351 // We don't have logcat yet under recovery; so we'll print error on screen and log to stdout
352 // (which is redirected to recovery.log) as we used to do.
353 android::base::InitLogging(argv, &UiLogger);
354
355 // Take last pmsg contents and rewrite it to the current pmsg session.
356 static constexpr const char filter[] = "recovery/";
357 // Do we need to rotate?
358 bool do_rotate = false;
359
360 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logbasename, &do_rotate);
361 // Take action to refresh pmsg contents
362 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logrotate, &do_rotate);
363
Steve Kondikf1e0f172013-10-19 19:49:20 -0700364 // Clear umask for packages that copy files out to /tmp and then over
365 // to /system without properly setting all permissions (eg. gapps).
366 umask(0);
367
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700368 time_t start = time(nullptr);
369
Tao Bao6d99d4b2018-04-25 16:47:04 -0700370 // redirect_stdio should be called only in non-sideload mode. Otherwise we may have two logger
371 // instances with different timestamps.
372 redirect_stdio(Paths::Get().temporary_log_file().c_str());
373
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700374 load_volume_table();
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700375
Tianjie Xub63a2212019-07-29 14:21:49 -0700376 std::string stage;
377 std::vector<std::string> args = get_args(argc, argv, &stage);
Tao Bao1700cc42018-07-16 22:09:59 -0700378 auto args_to_parse = StringVectorToNullTerminatedArray(args);
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700379
380 static constexpr struct option OPTIONS[] = {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700381 { "fastboot", no_argument, nullptr, 0 },
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700382 { "locale", required_argument, nullptr, 0 },
Tianjie Xub63a2212019-07-29 14:21:49 -0700383 { "reason", required_argument, nullptr, 0 },
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700384 { "show_text", no_argument, nullptr, 't' },
385 { nullptr, 0, nullptr, 0 },
386 };
387
388 bool show_text = false;
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700389 bool fastboot = false;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700390 std::string locale;
Tianjie Xub63a2212019-07-29 14:21:49 -0700391 std::string reason;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700392
Tao Baoff185862019-09-18 13:28:32 -0700393 // The code here is only interested in the options that signal the intent to start fastbootd or
394 // recovery. Unrecognized options are likely meant for recovery, which will be processed later in
395 // start_recovery(). Suppress the warnings for such -- even if some flags were indeed invalid, the
396 // code in start_recovery() will capture and report them.
397 opterr = 0;
398
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700399 int arg;
400 int option_index;
Tao Bao1700cc42018-07-16 22:09:59 -0700401 while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700402 &option_index)) != -1) {
403 switch (arg) {
404 case 't':
405 show_text = true;
406 break;
407 case 0: {
408 std::string option = OPTIONS[option_index].name;
409 if (option == "locale") {
410 locale = optarg;
Tianjie Xub63a2212019-07-29 14:21:49 -0700411 } else if (option == "reason") {
412 reason = optarg;
Hridya Valsaraju7f41a2c2018-09-19 16:29:01 -0700413 } else if (option == "fastboot" &&
Alessandro Astoneec80d7a2020-02-26 17:25:54 +0100414 (android::base::GetBoolProperty("ro.boot.dynamic_partitions", false) ||
415 android::base::GetBoolProperty("ro.fastbootd.available", false))) {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700416 fastboot = true;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700417 }
418 break;
419 }
420 }
421 }
Jerry Zhang49fd5d22018-05-17 12:54:41 -0700422 optind = 1;
Tao Baoff185862019-09-18 13:28:32 -0700423 opterr = 1;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700424
425 if (locale.empty()) {
Tianjie Xu164c60a2019-05-15 13:59:39 -0700426 if (HasCache()) {
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700427 locale = load_locale_from_cache();
428 }
429
430 if (locale.empty()) {
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700431 locale = DEFAULT_LOCALE;
432 }
433 }
434
Tao Bao42c45e22018-07-31 09:37:12 -0700435 static constexpr const char* kDefaultLibRecoveryUIExt = "librecovery_ui_ext.so";
436 // Intentionally not calling dlclose(3) to avoid potential gotchas (e.g. `make_device` may have
437 // handed out pointers to code or static [or thread-local] data and doesn't collect them all back
438 // in on dlclose).
439 void* librecovery_ui_ext = dlopen(kDefaultLibRecoveryUIExt, RTLD_NOW);
440
441 using MakeDeviceType = decltype(&make_device);
442 MakeDeviceType make_device_func = nullptr;
443 if (librecovery_ui_ext == nullptr) {
444 printf("Failed to dlopen %s: %s\n", kDefaultLibRecoveryUIExt, dlerror());
445 } else {
446 reinterpret_cast<void*&>(make_device_func) = dlsym(librecovery_ui_ext, "make_device");
447 if (make_device_func == nullptr) {
448 printf("Failed to dlsym make_device: %s\n", dlerror());
449 }
450 }
451
452 Device* device;
453 if (make_device_func == nullptr) {
454 printf("Falling back to the default make_device() instead\n");
455 device = make_device();
456 } else {
457 printf("Loading make_device from %s\n", kDefaultLibRecoveryUIExt);
458 device = (*make_device_func)();
459 }
460
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700461 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
462 printf("Quiescent recovery mode.\n");
463 device->ResetUI(new StubRecoveryUI());
464 } else {
465 if (!device->GetUI()->Init(locale)) {
466 printf("Failed to initialize UI; using stub UI instead.\n");
467 device->ResetUI(new StubRecoveryUI());
468 }
469 }
Tianjie Xub63a2212019-07-29 14:21:49 -0700470
471 BootState boot_state(reason, stage); // recovery_main owns the state of boot.
472 device->SetBootState(&boot_state);
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700473 ui = device->GetUI();
474
Tianjie Xu164c60a2019-05-15 13:59:39 -0700475 if (!HasCache()) {
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700476 device->RemoveMenuItemForAction(Device::WIPE_CACHE);
477 }
478
Richard Hansen464d3482020-05-04 20:46:09 -0400479 if (android::base::GetBoolProperty("ro.build.ab_update", false)) {
480 // There's not much point in formatting the active slot's system partition
481 // because ROMs are flashed to the inactive slot. Removing the menu option
482 // prevents users from accidentally trashing a functioning ROM.
483 device->RemoveMenuItemForAction(Device::WIPE_SYSTEM);
Ethan Yonker0880a2e2021-01-03 23:47:09 -0800484 } else {
485 device->RemoveMenuItemForAction(Device::SWAP_SLOT);
Richard Hansen464d3482020-05-04 20:46:09 -0400486 }
487
Alessandro Astoneec80d7a2020-02-26 17:25:54 +0100488 if (!android::base::GetBoolProperty("ro.boot.dynamic_partitions", false) &&
489 !android::base::GetBoolProperty("ro.fastbootd.available", false)) {
Hridya Valsarajudaa301e2018-09-18 14:48:01 -0700490 device->RemoveMenuItemForAction(Device::ENTER_FASTBOOT);
491 }
492
Michael Bestas680527d2019-09-27 20:29:42 +0300493 if (get_build_type() != "eng") {
494 device->RemoveMenuItemForAction(Device::RUN_GRAPHICS_TEST);
495 device->RemoveMenuItemForAction(Device::RUN_LOCALE_TEST);
Tao Baoc6dc3252019-04-16 14:22:25 -0700496 device->RemoveMenuItemForAction(Device::ENTER_RESCUE);
497 }
498
LuK1337d55e9a92020-04-12 19:04:59 +0200499 if (get_build_type() != "userdebug") {
500 device->RemoveMenuItemForAction(Device::ENABLE_ADB);
501 }
502
Luca Stefanie4548622020-03-14 00:12:18 +0100503 if (get_build_type() == "user") {
504 device->RemoveMenuItemForAction(Device::WIPE_SYSTEM);
505 device->RemoveMenuItemForAction(Device::MOUNT_SYSTEM);
506 }
507
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700508 ui->SetBackground(RecoveryUI::NONE);
509 if (show_text) ui->ShowText(true);
510
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700511 LOG(INFO) << "Starting recovery (pid " << getpid() << ") on " << ctime(&start);
512 LOG(INFO) << "locale is [" << locale << "]";
513
Tianjie Xu164c60a2019-05-15 13:59:39 -0700514 auto sehandle = selinux_android_file_context_handle();
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700515 selinux_android_set_sehandle(sehandle);
516 if (!sehandle) {
517 ui->Print("Warning: No file_contexts\n");
518 }
519
xunchang2239b9e2019-04-15 15:24:24 -0700520 SetLoggingSehandle(sehandle);
xunchang316e9712019-04-12 16:22:15 -0700521
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700522 std::atomic<Device::BuiltinAction> action;
523 std::thread listener_thread(ListenRecoverySocket, ui, std::ref(action));
524 listener_thread.detach();
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700525
Steve Kondikf1e0f172013-10-19 19:49:20 -0700526 // Set up adb_keys and enable root before starting ADB.
527 if (IsRoDebuggable() && !fastboot) {
528 copy_userdata_files();
529 android::base::SetProperty("service.adb.root", "1");
530 }
531
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700532 while (true) {
Tianjie Xu7d5c3412019-10-29 21:44:39 -0700533 // We start adbd in recovery for the device with userdebug build or a unlocked bootloader.
534 std::string usb_config =
535 fastboot ? "fastboot" : IsRoDebuggable() || IsDeviceUnlocked() ? "adb" : "none";
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700536 std::string usb_state = android::base::GetProperty("sys.usb.state", "none");
Hongguang Chen04267272020-04-21 20:58:04 -0700537 if (fastboot) {
538 device->PreFastboot();
539 } else {
540 device->PreRecovery();
541 }
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700542 if (usb_config != usb_state) {
543 if (!SetUsbConfig("none")) {
544 LOG(ERROR) << "Failed to clear USB config";
545 }
546 if (!SetUsbConfig(usb_config)) {
547 LOG(ERROR) << "Failed to set USB config to " << usb_config;
548 }
549 }
550
551 auto ret = fastboot ? StartFastboot(device, args) : start_recovery(device, args);
552
553 if (ret == Device::KEY_INTERRUPTED) {
554 ret = action.exchange(ret);
555 if (ret == Device::NO_ACTION) {
556 continue;
557 }
558 }
559 switch (ret) {
560 case Device::SHUTDOWN:
561 ui->Print("Shutting down...\n");
Mark Salyzyn488cc052019-05-20 10:36:16 -0700562 Shutdown("userrequested,recovery");
563 break;
564
565 case Device::SHUTDOWN_FROM_FASTBOOT:
566 ui->Print("Shutting down...\n");
567 Shutdown("userrequested,fastboot");
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700568 break;
569
570 case Device::REBOOT_BOOTLOADER:
571 ui->Print("Rebooting to bootloader...\n");
Tao Bao782dcc12019-04-29 11:23:16 -0700572 Reboot("bootloader");
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700573 break;
574
Tao Baod9cb0142019-04-23 11:46:25 -0700575 case Device::REBOOT_FASTBOOT:
576 ui->Print("Rebooting to recovery/fastboot...\n");
Tao Bao782dcc12019-04-29 11:23:16 -0700577 Reboot("fastboot");
Tao Bao10f441a2019-04-19 15:22:15 -0700578 break;
579
Tao Baod9cb0142019-04-23 11:46:25 -0700580 case Device::REBOOT_RECOVERY:
581 ui->Print("Rebooting to recovery...\n");
Tao Bao782dcc12019-04-29 11:23:16 -0700582 Reboot("recovery");
Tao Baod9cb0142019-04-23 11:46:25 -0700583 break;
584
585 case Device::REBOOT_RESCUE: {
Tao Bao782dcc12019-04-29 11:23:16 -0700586 // Not using `Reboot("rescue")`, as it requires matching support in kernel and/or
Tao Baod9cb0142019-04-23 11:46:25 -0700587 // bootloader.
588 bootloader_message boot = {};
589 strlcpy(boot.command, "boot-rescue", sizeof(boot.command));
590 std::string err;
591 if (!write_bootloader_message(boot, &err)) {
592 LOG(ERROR) << "Failed to write bootloader message: " << err;
593 // Stay under recovery on failure.
594 continue;
595 }
596 ui->Print("Rebooting to recovery/rescue...\n");
Tao Bao782dcc12019-04-29 11:23:16 -0700597 Reboot("recovery");
Tao Baod9cb0142019-04-23 11:46:25 -0700598 break;
599 }
600
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700601 case Device::ENTER_FASTBOOT:
Erfan Abdib28d9dd2020-04-14 23:07:33 +0430602 if (logical_partitions_mapped()) {
David Anderson2b2f4232018-10-29 18:48:56 -0700603 ui->Print("Partitions may be mounted - rebooting to enter fastboot.");
Tao Bao782dcc12019-04-29 11:23:16 -0700604 Reboot("fastboot");
David Anderson2b2f4232018-10-29 18:48:56 -0700605 } else {
606 LOG(INFO) << "Entering fastboot";
607 fastboot = true;
608 }
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700609 break;
610
611 case Device::ENTER_RECOVERY:
612 LOG(INFO) << "Entering recovery";
613 fastboot = false;
LuK13373db4f602024-03-11 16:22:34 +0100614 ui->SetEnableFastbootdLogo(fastboot);
Tom Marshallcc6d2c52020-03-29 14:36:57 +0200615 device->GoHome();
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700616 break;
617
Mark Salyzyn488cc052019-05-20 10:36:16 -0700618 case Device::REBOOT:
619 ui->Print("Rebooting...\n");
620 Reboot("userrequested,recovery");
621 break;
622
623 case Device::REBOOT_FROM_FASTBOOT:
624 ui->Print("Rebooting...\n");
625 Reboot("userrequested,fastboot");
626 break;
627
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700628 default:
629 ui->Print("Rebooting...\n");
Mark Salyzyn488cc052019-05-20 10:36:16 -0700630 Reboot("unknown" + std::to_string(ret));
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700631 break;
632 }
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700633 }
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700634
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700635 // Should be unreachable.
636 return EXIT_SUCCESS;
Tao Bao6d99d4b2018-04-25 16:47:04 -0700637}