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