1 /*
2 * Copyright (C) 2007 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
17 #include "recovery.h"
18
19 #include <errno.h>
20 #include <getopt.h>
21 #include <linux/input.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27
28 #include <functional>
29 #include <iterator>
30 #include <memory>
31 #include <string>
32 #include <vector>
33
34 #include <android-base/file.h>
35 #include <android-base/logging.h>
36 #include <android-base/parseint.h>
37 #include <android-base/properties.h>
38 #include <android-base/stringprintf.h>
39 #include <android-base/strings.h>
40 #include <cutils/properties.h> /* for property_list */
41 #include <fs_mgr/roots.h>
42 #include <ziparchive/zip_archive.h>
43
44 #include "bootloader_message/bootloader_message.h"
45 #include "install/adb_install.h"
46 #include "install/fuse_install.h"
47 #include "install/install.h"
48 #include "install/snapshot_utils.h"
49 #include "install/wipe_data.h"
50 #include "install/wipe_device.h"
51 #include "otautil/error_code.h"
52 #include "otautil/package.h"
53 #include "otautil/paths.h"
54 #include "otautil/sysutil.h"
55 #include "recovery_ui/screen_ui.h"
56 #include "recovery_ui/ui.h"
57 #include "recovery_utils/battery_utils.h"
58 #include "recovery_utils/logging.h"
59 #include "recovery_utils/roots.h"
60
61 static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
62 static constexpr const char* LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
63 static constexpr const char* LAST_LOG_FILE = "/cache/recovery/last_log";
64 static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
65
66 static constexpr const char* CACHE_ROOT = "/cache";
67
68 static bool save_current_log = false;
69
70 /*
71 * The recovery tool communicates with the main system through /cache files.
72 * /cache/recovery/command - INPUT - command line for tool, one arg per line
73 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
74 *
75 * The arguments which may be supplied in the recovery.command file:
76 * --update_package=path - verify install an OTA package file
77 * --install_with_fuse - install the update package with FUSE. This allows installation of large
78 * packages on LP32 builds. Since the mmap will otherwise fail due to out of memory.
79 * --wipe_data - erase user data (and cache), then reboot
80 * --prompt_and_wipe_data - prompt the user that data is corrupt, with their consent erase user
81 * data (and cache), then reboot
82 * --wipe_cache - wipe cache (but not user data), then reboot
83 * --show_text - show the recovery text menu, used by some bootloader (e.g. http://b/36872519).
84 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
85 * --just_exit - do nothing; exit and reboot
86 *
87 * After completing, we remove /cache/recovery/command and reboot.
88 * Arguments may also be supplied in the bootloader control block (BCB).
89 * These important scenarios must be safely restartable at any point:
90 *
91 * FACTORY RESET
92 * 1. user selects "factory reset"
93 * 2. main system writes "--wipe_data" to /cache/recovery/command
94 * 3. main system reboots into recovery
95 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
96 * -- after this, rebooting will restart the erase --
97 * 5. erase_volume() reformats /data
98 * 6. erase_volume() reformats /cache
99 * 7. FinishRecovery() erases BCB
100 * -- after this, rebooting will restart the main system --
101 * 8. main() calls reboot() to boot main system
102 *
103 * OTA INSTALL
104 * 1. main system downloads OTA package to /cache/some-filename.zip
105 * 2. main system writes "--update_package=/cache/some-filename.zip"
106 * 3. main system reboots into recovery
107 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
108 * -- after this, rebooting will attempt to reinstall the update --
109 * 5. InstallPackage() attempts to install the update
110 * NOTE: the package install must itself be restartable from any point
111 * 6. FinishRecovery() erases BCB
112 * -- after this, rebooting will (try to) restart the main system --
113 * 7. ** if install failed **
114 * 7a. PromptAndWait() shows an error icon and waits for the user
115 * 7b. the user reboots (pulling the battery, etc) into the main system
116 */
117
IsRoDebuggable()118 static bool IsRoDebuggable() {
119 return android::base::GetBoolProperty("ro.debuggable", false);
120 }
121
122 // Clear the recovery command and prepare to boot a (hopefully working) system,
123 // copy our log file to cache as well (for the system to read). This function is
124 // idempotent: call it as many times as you like.
FinishRecovery(RecoveryUI * ui)125 static void FinishRecovery(RecoveryUI* ui) {
126 std::string locale = ui->GetLocale();
127 // Save the locale to cache, so if recovery is next started up without a '--locale' argument
128 // (e.g., directly from the bootloader) it will use the last-known locale.
129 if (!locale.empty() && HasCache()) {
130 LOG(INFO) << "Saving locale \"" << locale << "\"";
131 if (ensure_path_mounted(LOCALE_FILE) != 0) {
132 LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
133 } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
134 PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
135 }
136 }
137
138 copy_logs(save_current_log);
139
140 // Reset to normal system boot so recovery won't cycle indefinitely.
141 std::string err;
142 if (!clear_bootloader_message(&err)) {
143 LOG(ERROR) << "Failed to clear BCB message: " << err;
144 }
145
146 // Remove the command file, so recovery won't repeat indefinitely.
147 if (HasCache()) {
148 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
149 LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
150 }
151 ensure_path_unmounted(CACHE_ROOT);
152 }
153
154 sync(); // For good measure.
155 }
156
yes_no(Device * device,const char * question1,const char * question2)157 static bool yes_no(Device* device, const char* question1, const char* question2) {
158 std::vector<std::string> headers{ question1, question2 };
159 std::vector<std::string> items{ " No", " Yes" };
160
161 size_t chosen_item = device->GetUI()->ShowMenu(
162 headers, items, 0, true,
163 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
164 return (chosen_item == 1);
165 }
166
ask_to_wipe_data(Device * device)167 static bool ask_to_wipe_data(Device* device) {
168 std::vector<std::string> headers{ "Wipe all user data?", " THIS CAN NOT BE UNDONE!" };
169 std::vector<std::string> items{ " Cancel", " Factory data reset" };
170
171 size_t chosen_item = device->GetUI()->ShowPromptWipeDataConfirmationMenu(
172 headers, items,
173 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
174
175 return (chosen_item == 1);
176 }
177
prompt_and_wipe_data(Device * device)178 static InstallResult prompt_and_wipe_data(Device* device) {
179 // Reset to normal system boot so recovery won't cycle indefinitely.
180 std::string err;
181 if (!clear_bootloader_message(&err)) {
182 LOG(ERROR) << "Failed to clear BCB message: " << err;
183 }
184 // Use a single string and let ScreenRecoveryUI handles the wrapping.
185 std::vector<std::string> wipe_data_menu_headers{
186 "Can't load Android system. Your data may be corrupt. "
187 "If you continue to get this message, you may need to "
188 "perform a factory data reset and erase all user data "
189 "stored on this device.",
190 };
191 // clang-format off
192 std::vector<std::string> wipe_data_menu_items {
193 "Try again",
194 "Factory data reset",
195 };
196 // clang-format on
197 for (;;) {
198 size_t chosen_item = device->GetUI()->ShowPromptWipeDataMenu(
199 wipe_data_menu_headers, wipe_data_menu_items,
200 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
201 // If ShowMenu() returned RecoveryUI::KeyError::INTERRUPTED, WaitKey() was interrupted.
202 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
203 return INSTALL_KEY_INTERRUPTED;
204 }
205 if (chosen_item != 1) {
206 return INSTALL_SUCCESS; // Just reboot, no wipe; not a failure, user asked for it
207 }
208
209 if (ask_to_wipe_data(device)) {
210 CHECK(device->GetReason().has_value());
211 if (WipeData(device)) {
212 return INSTALL_SUCCESS;
213 } else {
214 return INSTALL_ERROR;
215 }
216 }
217 }
218 }
219
choose_recovery_file(Device * device)220 static void choose_recovery_file(Device* device) {
221 std::vector<std::string> entries;
222 if (HasCache()) {
223 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
224 auto add_to_entries = [&](const char* filename) {
225 std::string log_file(filename);
226 if (i > 0) {
227 log_file += "." + std::to_string(i);
228 }
229
230 if (ensure_path_mounted(log_file) == 0 && access(log_file.c_str(), R_OK) == 0) {
231 entries.push_back(std::move(log_file));
232 }
233 };
234
235 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
236 add_to_entries(LAST_LOG_FILE);
237
238 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
239 add_to_entries(LAST_KMSG_FILE);
240 }
241 } else {
242 // If cache partition is not found, view /tmp/recovery.log instead.
243 if (access(Paths::Get().temporary_log_file().c_str(), R_OK) == -1) {
244 return;
245 } else {
246 entries.push_back(Paths::Get().temporary_log_file());
247 }
248 }
249
250 entries.push_back("Back");
251
252 std::vector<std::string> headers{ "Select file to view" };
253
254 size_t chosen_item = 0;
255 while (true) {
256 chosen_item = device->GetUI()->ShowMenu(
257 headers, entries, chosen_item, true,
258 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
259
260 // Handle WaitKey() interrupt.
261 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
262 break;
263 }
264 if (entries[chosen_item] == "Back") break;
265
266 device->GetUI()->ShowFile(entries[chosen_item]);
267 }
268 }
269
run_graphics_test(RecoveryUI * ui)270 static void run_graphics_test(RecoveryUI* ui) {
271 // Switch to graphics screen.
272 ui->ShowText(false);
273
274 ui->SetProgressType(RecoveryUI::INDETERMINATE);
275 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
276 sleep(1);
277
278 ui->SetBackground(RecoveryUI::ERROR);
279 sleep(1);
280
281 ui->SetBackground(RecoveryUI::NO_COMMAND);
282 sleep(1);
283
284 ui->SetBackground(RecoveryUI::ERASING);
285 sleep(1);
286
287 // Calling SetBackground() after SetStage() to trigger a redraw.
288 ui->SetStage(1, 3);
289 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
290 sleep(1);
291 ui->SetStage(2, 3);
292 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
293 sleep(1);
294 ui->SetStage(3, 3);
295 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
296 sleep(1);
297
298 ui->SetStage(-1, -1);
299 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
300
301 ui->SetProgressType(RecoveryUI::DETERMINATE);
302 ui->ShowProgress(1.0, 10.0);
303 float fraction = 0.0;
304 for (size_t i = 0; i < 100; ++i) {
305 fraction += .01;
306 ui->SetProgress(fraction);
307 usleep(100000);
308 }
309
310 ui->ShowText(true);
311 }
312
WriteUpdateInProgress()313 static void WriteUpdateInProgress() {
314 std::string err;
315 if (!update_bootloader_message({ "--reason=update_in_progress" }, &err)) {
316 LOG(ERROR) << "Failed to WriteUpdateInProgress: " << err;
317 }
318 }
319
AskToReboot(Device * device,Device::BuiltinAction chosen_action)320 static bool AskToReboot(Device* device, Device::BuiltinAction chosen_action) {
321 bool is_non_ab = android::base::GetProperty("ro.boot.slot_suffix", "").empty();
322 bool is_virtual_ab = android::base::GetBoolProperty("ro.virtual_ab.enabled", false);
323 if (!is_non_ab && !is_virtual_ab) {
324 // Only prompt for non-A/B or Virtual A/B devices.
325 return true;
326 }
327
328 std::string header_text;
329 std::string item_text;
330 switch (chosen_action) {
331 case Device::REBOOT:
332 header_text = "reboot";
333 item_text = " Reboot system now";
334 break;
335 case Device::SHUTDOWN:
336 header_text = "power off";
337 item_text = " Power off";
338 break;
339 default:
340 LOG(FATAL) << "Invalid chosen action " << chosen_action;
341 break;
342 }
343
344 std::vector<std::string> headers{ "WARNING: Previous installation has failed.",
345 " Your device may fail to boot if you " + header_text +
346 " now.",
347 " Confirm reboot?" };
348 std::vector<std::string> items{ " Cancel", item_text };
349
350 size_t chosen_item = device->GetUI()->ShowMenu(
351 headers, items, 0, true /* menu_only */,
352 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
353
354 return (chosen_item == 1);
355 }
356
357 // Shows the recovery UI and waits for user input. Returns one of the device builtin actions, such
358 // as REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default, which
359 // is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
PromptAndWait(Device * device,InstallResult status)360 static Device::BuiltinAction PromptAndWait(Device* device, InstallResult status) {
361 auto ui = device->GetUI();
362 bool update_in_progress = (device->GetReason().value_or("") == "update_in_progress");
363 for (;;) {
364 FinishRecovery(ui);
365 switch (status) {
366 case INSTALL_SUCCESS:
367 case INSTALL_NONE:
368 case INSTALL_SKIPPED:
369 case INSTALL_RETRY:
370 case INSTALL_KEY_INTERRUPTED:
371 ui->SetBackground(RecoveryUI::NO_COMMAND);
372 break;
373
374 case INSTALL_ERROR:
375 case INSTALL_CORRUPT:
376 ui->SetBackground(RecoveryUI::ERROR);
377 break;
378
379 case INSTALL_REBOOT:
380 // All the reboots should have been handled prior to entering PromptAndWait() or immediately
381 // after installing a package.
382 LOG(FATAL) << "Invalid status code of INSTALL_REBOOT";
383 break;
384 }
385 ui->SetProgressType(RecoveryUI::EMPTY);
386
387 std::vector<std::string> headers;
388 if (update_in_progress) {
389 headers = { "WARNING: Previous installation has failed.",
390 " Your device may fail to boot if you reboot or power off now." };
391 }
392
393 size_t chosen_item = ui->ShowMenu(
394 headers, device->GetMenuItems(), 0, false,
395 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
396 // Handle Interrupt key
397 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
398 return Device::KEY_INTERRUPTED;
399 }
400 // Device-specific code may take some action here. It may return one of the core actions
401 // handled in the switch statement below.
402 Device::BuiltinAction chosen_action =
403 (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::TIMED_OUT))
404 ? Device::REBOOT
405 : device->InvokeMenuItem(chosen_item);
406
407 switch (chosen_action) {
408 case Device::REBOOT_FROM_FASTBOOT: // Can not happen
409 case Device::SHUTDOWN_FROM_FASTBOOT: // Can not happen
410 case Device::NO_ACTION:
411 break;
412
413 case Device::ENTER_FASTBOOT:
414 case Device::ENTER_RECOVERY:
415 case Device::REBOOT_BOOTLOADER:
416 case Device::REBOOT_FASTBOOT:
417 case Device::REBOOT_RECOVERY:
418 case Device::REBOOT_RESCUE:
419 return chosen_action;
420
421 case Device::REBOOT:
422 case Device::SHUTDOWN:
423 if (!ui->IsTextVisible()) {
424 return chosen_action;
425 }
426 // okay to reboot; no need to ask.
427 if (!update_in_progress) {
428 return chosen_action;
429 }
430 // An update might have been failed. Ask if user really wants to reboot.
431 if (AskToReboot(device, chosen_action)) {
432 return chosen_action;
433 }
434 break;
435
436 case Device::WIPE_DATA:
437 save_current_log = true;
438 if (ui->IsTextVisible()) {
439 if (ask_to_wipe_data(device)) {
440 WipeData(device);
441 }
442 } else {
443 WipeData(device);
444 return Device::NO_ACTION;
445 }
446 break;
447
448 case Device::WIPE_CACHE: {
449 save_current_log = true;
450 std::function<bool()> confirm_func = [&device]() {
451 return yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!");
452 };
453 WipeCache(ui, ui->IsTextVisible() ? confirm_func : nullptr);
454 if (!ui->IsTextVisible()) return Device::NO_ACTION;
455 break;
456 }
457
458 case Device::APPLY_ADB_SIDELOAD:
459 case Device::APPLY_SDCARD:
460 case Device::ENTER_RESCUE: {
461 save_current_log = true;
462
463 update_in_progress = true;
464 WriteUpdateInProgress();
465
466 bool adb = true;
467 Device::BuiltinAction reboot_action{};
468 if (chosen_action == Device::ENTER_RESCUE) {
469 // Switch to graphics screen.
470 ui->ShowText(false);
471 status = ApplyFromAdb(device, true /* rescue_mode */, &reboot_action);
472 } else if (chosen_action == Device::APPLY_ADB_SIDELOAD) {
473 status = ApplyFromAdb(device, false /* rescue_mode */, &reboot_action);
474 } else {
475 adb = false;
476 status = ApplyFromSdcard(device);
477 }
478
479 ui->Print("\nInstall from %s completed with status %d.\n", adb ? "ADB" : "SD card", status);
480 if (status == INSTALL_REBOOT) {
481 return reboot_action;
482 }
483
484 if (status == INSTALL_SUCCESS) {
485 update_in_progress = false;
486 if (!ui->IsTextVisible()) {
487 return Device::NO_ACTION; // reboot if logs aren't visible
488 }
489 } else {
490 ui->SetBackground(RecoveryUI::ERROR);
491 ui->Print("Installation aborted.\n");
492 copy_logs(save_current_log);
493 }
494 break;
495 }
496
497 case Device::VIEW_RECOVERY_LOGS:
498 choose_recovery_file(device);
499 break;
500
501 case Device::RUN_GRAPHICS_TEST:
502 run_graphics_test(ui);
503 break;
504
505 case Device::RUN_LOCALE_TEST: {
506 ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
507 screen_ui->CheckBackgroundTextImages();
508 break;
509 }
510
511 case Device::MOUNT_SYSTEM:
512 // For Virtual A/B, set up the snapshot devices (if exist).
513 if (!CreateSnapshotPartitions()) {
514 ui->Print("Virtual A/B: snapshot partitions creation failed.\n");
515 break;
516 }
517 if (ensure_path_mounted_at(android::fs_mgr::GetSystemRoot(), "/mnt/system") != -1) {
518 ui->Print("Mounted /system.\n");
519 }
520 break;
521
522 case Device::KEY_INTERRUPTED:
523 return Device::KEY_INTERRUPTED;
524 }
525 }
526 }
527
print_property(const char * key,const char * name,void *)528 static void print_property(const char* key, const char* name, void* /* cookie */) {
529 printf("%s=%s\n", key, name);
530 }
531
IsBatteryOk(int * required_battery_level)532 static bool IsBatteryOk(int* required_battery_level) {
533 // GmsCore enters recovery mode to install package when having enough battery percentage.
534 // Normally, the threshold is 40% without charger and 20% with charger. So we check the battery
535 // level against a slightly lower limit.
536 constexpr int BATTERY_OK_PERCENTAGE = 20;
537 constexpr int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
538
539 auto battery_info = GetBatteryInfo();
540 *required_battery_level =
541 battery_info.charging ? BATTERY_WITH_CHARGER_OK_PERCENTAGE : BATTERY_OK_PERCENTAGE;
542 return battery_info.capacity >= *required_battery_level;
543 }
544
545 // Set the retry count to |retry_count| in BCB.
set_retry_bootloader_message(int retry_count,const std::vector<std::string> & args)546 static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
547 std::vector<std::string> options;
548 for (const auto& arg : args) {
549 if (!android::base::StartsWith(arg, "--retry_count")) {
550 options.push_back(arg);
551 }
552 }
553
554 // Update the retry counter in BCB.
555 options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
556 std::string err;
557 if (!update_bootloader_message(options, &err)) {
558 LOG(ERROR) << err;
559 }
560 }
561
bootreason_in_blocklist()562 static bool bootreason_in_blocklist() {
563 std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
564 if (!bootreason.empty()) {
565 // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
566 static const std::vector<std::string> kBootreasonBlocklist{
567 "kernel_panic",
568 "Panic",
569 };
570 for (const auto& str : kBootreasonBlocklist) {
571 if (android::base::EqualsIgnoreCase(str, bootreason)) return true;
572 }
573 }
574 return false;
575 }
576
log_failure_code(ErrorCode code,const std::string & update_package)577 static void log_failure_code(ErrorCode code, const std::string& update_package) {
578 std::vector<std::string> log_buffer = {
579 update_package,
580 "0", // install result
581 "error: " + std::to_string(code),
582 };
583 std::string log_content = android::base::Join(log_buffer, "\n");
584 const std::string& install_file = Paths::Get().temporary_install_file();
585 if (!android::base::WriteStringToFile(log_content, install_file)) {
586 PLOG(ERROR) << "Failed to write " << install_file;
587 }
588
589 // Also write the info into last_log.
590 LOG(INFO) << log_content;
591 }
592
start_recovery(Device * device,const std::vector<std::string> & args)593 Device::BuiltinAction start_recovery(Device* device, const std::vector<std::string>& args) {
594 static constexpr struct option OPTIONS[] = {
595 { "fastboot", no_argument, nullptr, 0 },
596 { "install_with_fuse", no_argument, nullptr, 0 },
597 { "just_exit", no_argument, nullptr, 'x' },
598 { "locale", required_argument, nullptr, 0 },
599 { "prompt_and_wipe_data", no_argument, nullptr, 0 },
600 { "reason", required_argument, nullptr, 0 },
601 { "rescue", no_argument, nullptr, 0 },
602 { "retry_count", required_argument, nullptr, 0 },
603 { "security", no_argument, nullptr, 0 },
604 { "show_text", no_argument, nullptr, 't' },
605 { "shutdown_after", no_argument, nullptr, 0 },
606 { "sideload", no_argument, nullptr, 0 },
607 { "sideload_auto_reboot", no_argument, nullptr, 0 },
608 { "update_package", required_argument, nullptr, 0 },
609 { "wipe_ab", no_argument, nullptr, 0 },
610 { "wipe_cache", no_argument, nullptr, 0 },
611 { "wipe_data", no_argument, nullptr, 0 },
612 { "keep_memtag_mode", no_argument, nullptr, 0 },
613 { "wipe_package_size", required_argument, nullptr, 0 },
614 { "reformat_data", required_argument, nullptr, 0 },
615 { nullptr, 0, nullptr, 0 },
616 };
617
618 const char* update_package = nullptr;
619 bool install_with_fuse = false; // memory map the update package by default.
620 bool should_wipe_data = false;
621 bool should_prompt_and_wipe_data = false;
622 bool should_keep_memtag_mode = false;
623 bool should_wipe_cache = false;
624 bool should_wipe_ab = false;
625 size_t wipe_package_size = 0;
626 bool sideload = false;
627 bool sideload_auto_reboot = false;
628 bool rescue = false;
629 bool just_exit = false;
630 bool shutdown_after = false;
631 int retry_count = 0;
632 bool security_update = false;
633 std::string locale;
634
635 auto args_to_parse = StringVectorToNullTerminatedArray(args);
636
637 int arg = 0;
638 int option_index = 0;
639 std::string data_fstype;
640 // Parse everything before the last element (which must be a nullptr). getopt_long(3) expects a
641 // null-terminated char* array, but without counting null as an arg (i.e. argv[argc] should be
642 // nullptr).
643 while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
644 &option_index)) != -1) {
645 switch (arg) {
646 case 't':
647 // Handled in recovery_main.cpp
648 break;
649 case 'x':
650 just_exit = true;
651 break;
652 case 0: {
653 std::string option = OPTIONS[option_index].name;
654 if (option == "install_with_fuse") {
655 install_with_fuse = true;
656 } else if (option == "locale" || option == "fastboot" || option == "reason") {
657 // Handled in recovery_main.cpp
658 } else if (option == "prompt_and_wipe_data") {
659 should_prompt_and_wipe_data = true;
660 } else if (option == "rescue") {
661 rescue = true;
662 } else if (option == "retry_count") {
663 android::base::ParseInt(optarg, &retry_count, 0);
664 } else if (option == "security") {
665 security_update = true;
666 } else if (option == "sideload") {
667 sideload = true;
668 } else if (option == "sideload_auto_reboot") {
669 sideload = true;
670 sideload_auto_reboot = true;
671 } else if (option == "shutdown_after") {
672 shutdown_after = true;
673 } else if (option == "update_package") {
674 update_package = optarg;
675 } else if (option == "wipe_ab") {
676 should_wipe_ab = true;
677 } else if (option == "wipe_cache") {
678 should_wipe_cache = true;
679 } else if (option == "wipe_data") {
680 should_wipe_data = true;
681 } else if (option == "wipe_package_size") {
682 android::base::ParseUint(optarg, &wipe_package_size);
683 } else if (option == "reformat_data") {
684 data_fstype = optarg;
685 } else if (option == "keep_memtag_mode") {
686 should_keep_memtag_mode = true;
687 }
688 break;
689 }
690 case '?':
691 LOG(ERROR) << "Invalid command argument";
692 continue;
693 }
694 }
695 optind = 1;
696
697 printf("stage is [%s]\n", device->GetStage().value_or("").c_str());
698 printf("reason is [%s]\n", device->GetReason().value_or("").c_str());
699
700 auto ui = device->GetUI();
701
702 // Set background string to "installing security update" for security update,
703 // otherwise set it to "installing system update".
704 ui->SetSystemUpdateText(security_update);
705
706 int st_cur = 0, st_max = 0;
707 if (!device->GetStage().has_value() &&
708 sscanf(device->GetStage().value().c_str(), "%d/%d", &st_cur, &st_max) == 2) {
709 ui->SetStage(st_cur, st_max);
710 }
711
712 std::vector<std::string> title_lines =
713 android::base::Split(android::base::GetProperty("ro.build.fingerprint", ""), ":");
714 title_lines.insert(std::begin(title_lines), "Android Recovery");
715 ui->SetTitle(title_lines);
716
717 ui->ResetKeyInterruptStatus();
718 device->StartRecovery();
719
720 printf("Command:");
721 for (const auto& arg : args) {
722 printf(" \"%s\"", arg.c_str());
723 }
724 printf("\n\n");
725
726 property_list(print_property, nullptr);
727 printf("\n");
728
729 InstallResult status = INSTALL_SUCCESS;
730 // next_action indicates the next target to reboot into upon finishing the install. It could be
731 // overridden to a different reboot target per user request.
732 Device::BuiltinAction next_action = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
733
734 if (update_package != nullptr) {
735 // It's not entirely true that we will modify the flash. But we want
736 // to log the update attempt since update_package is non-NULL.
737 save_current_log = true;
738
739 if (int required_battery_level = 0; retry_count == 0 && !IsBatteryOk(&required_battery_level)) {
740 ui->Print("battery capacity is not enough for installing package: %d%% needed\n",
741 required_battery_level);
742 // Log the error code to last_install when installation skips due to low battery.
743 log_failure_code(kLowBattery, update_package);
744 status = INSTALL_SKIPPED;
745 } else if (retry_count == 0 && bootreason_in_blocklist()) {
746 // Skip update-on-reboot when bootreason is kernel_panic or similar
747 ui->Print("bootreason is in the blocklist; skip OTA installation\n");
748 log_failure_code(kBootreasonInBlocklist, update_package);
749 status = INSTALL_SKIPPED;
750 } else {
751 // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
752 // identify the interrupted update due to unexpected reboots.
753 if (retry_count == 0) {
754 set_retry_bootloader_message(retry_count + 1, args);
755 }
756
757 bool should_use_fuse = false;
758 if (!SetupPackageMount(update_package, &should_use_fuse)) {
759 LOG(INFO) << "Failed to set up the package access, skipping installation";
760 status = INSTALL_ERROR;
761 } else if (install_with_fuse || should_use_fuse) {
762 LOG(INFO) << "Installing package " << update_package << " with fuse";
763 status = InstallWithFuseFromPath(update_package, device);
764 } else if (auto memory_package = Package::CreateMemoryPackage(
765 update_package,
766 std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
767 memory_package != nullptr) {
768 status = InstallPackage(memory_package.get(), update_package, should_wipe_cache,
769 retry_count, device);
770 } else {
771 // We may fail to memory map the package on 32 bit builds for packages with 2GiB+ size.
772 // In such cases, we will try to install the package with fuse. This is not the default
773 // installation method because it introduces a layer of indirection from the kernel space.
774 LOG(WARNING) << "Failed to memory map package " << update_package
775 << "; falling back to install with fuse";
776 status = InstallWithFuseFromPath(update_package, device);
777 }
778 if (status != INSTALL_SUCCESS) {
779 ui->Print("Installation aborted.\n");
780
781 // When I/O error or bspatch/imgpatch error happens, reboot and retry installation
782 // RETRY_LIMIT times before we abandon this OTA update.
783 static constexpr int RETRY_LIMIT = 4;
784 if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
785 copy_logs(save_current_log);
786 retry_count += 1;
787 set_retry_bootloader_message(retry_count, args);
788 // Print retry count on screen.
789 ui->Print("Retry attempt %d\n", retry_count);
790
791 // Reboot back into recovery to retry the update.
792 Reboot("recovery");
793 }
794 // If this is an eng or userdebug build, then automatically
795 // turn the text display on if the script fails so the error
796 // message is visible.
797 if (IsRoDebuggable()) {
798 ui->ShowText(true);
799 }
800 }
801 }
802 } else if (should_wipe_data) {
803 save_current_log = true;
804 CHECK(device->GetReason().has_value());
805 if (!WipeData(device, should_keep_memtag_mode, data_fstype)) {
806 status = INSTALL_ERROR;
807 }
808 } else if (should_prompt_and_wipe_data) {
809 // Trigger the logging to capture the cause, even if user chooses to not wipe data.
810 save_current_log = true;
811
812 ui->ShowText(true);
813 ui->SetBackground(RecoveryUI::ERROR);
814 status = prompt_and_wipe_data(device);
815 if (status != INSTALL_KEY_INTERRUPTED) {
816 ui->ShowText(false);
817 }
818 } else if (should_wipe_cache) {
819 save_current_log = true;
820 if (!WipeCache(ui, nullptr, data_fstype)) {
821 status = INSTALL_ERROR;
822 }
823 } else if (should_wipe_ab) {
824 if (!WipeAbDevice(device, wipe_package_size)) {
825 status = INSTALL_ERROR;
826 }
827 } else if (sideload) {
828 // 'adb reboot sideload' acts the same as user presses key combinations to enter the sideload
829 // mode. When 'sideload-auto-reboot' is used, text display will NOT be turned on by default. And
830 // it will reboot after sideload finishes even if there are errors. This is to enable automated
831 // testing.
832 save_current_log = true;
833 if (!sideload_auto_reboot) {
834 ui->ShowText(true);
835 }
836 status = ApplyFromAdb(device, false /* rescue_mode */, &next_action);
837 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
838 if (sideload_auto_reboot) {
839 status = INSTALL_REBOOT;
840 ui->Print("Rebooting automatically.\n");
841 }
842 } else if (rescue) {
843 save_current_log = true;
844 status = ApplyFromAdb(device, true /* rescue_mode */, &next_action);
845 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
846 } else if (!just_exit) {
847 // If this is an eng or userdebug build, automatically turn on the text display if no command
848 // is specified. Note that this should be called before setting the background to avoid
849 // flickering the background image.
850 if (IsRoDebuggable()) {
851 ui->ShowText(true);
852 }
853 status = INSTALL_NONE; // No command specified
854 ui->SetBackground(RecoveryUI::NO_COMMAND);
855 }
856
857 if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
858 ui->SetBackground(RecoveryUI::ERROR);
859 if (!ui->IsTextVisible()) {
860 sleep(5);
861 }
862 }
863
864 // Determine the next action.
865 // - If the state is INSTALL_REBOOT, device will reboot into the target as specified in
866 // `next_action`.
867 // - If the recovery menu is visible, prompt and wait for commands.
868 // - If the state is INSTALL_NONE, wait for commands (e.g. in user build, one manually boots
869 // into recovery to sideload a package or to wipe the device).
870 // - In all other cases, reboot the device. Therefore, normal users will observe the device
871 // rebooting a) immediately upon successful finish (INSTALL_SUCCESS); or b) an "error" screen
872 // for 5s followed by an automatic reboot.
873 if (status != INSTALL_REBOOT) {
874 if (status == INSTALL_NONE || ui->IsTextVisible()) {
875 auto temp = PromptAndWait(device, status);
876 if (temp != Device::NO_ACTION) {
877 next_action = temp;
878 }
879 }
880 }
881
882 // Save logs and clean up before rebooting or shutting down.
883 FinishRecovery(ui);
884
885 return next_action;
886 }
887