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