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