Home | History | Annotate | Download | only in recovery
      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 <fcntl.h>
     22 #include <getopt.h>
     23 #include <inttypes.h>
     24 #include <limits.h>
     25 #include <linux/fs.h>
     26 #include <linux/input.h>
     27 #include <stdio.h>
     28 #include <stdlib.h>
     29 #include <string.h>
     30 #include <sys/types.h>
     31 #include <unistd.h>
     32 
     33 #include <algorithm>
     34 #include <functional>
     35 #include <memory>
     36 #include <string>
     37 #include <vector>
     38 
     39 #include <android-base/file.h>
     40 #include <android-base/logging.h>
     41 #include <android-base/parseint.h>
     42 #include <android-base/properties.h>
     43 #include <android-base/stringprintf.h>
     44 #include <android-base/strings.h>
     45 #include <android-base/unique_fd.h>
     46 #include <bootloader_message/bootloader_message.h>
     47 #include <cutils/properties.h> /* for property_list */
     48 #include <healthhalutils/HealthHalUtils.h>
     49 #include <ziparchive/zip_archive.h>
     50 
     51 #include "common.h"
     52 #include "fsck_unshare_blocks.h"
     53 #include "install/adb_install.h"
     54 #include "install/fuse_sdcard_install.h"
     55 #include "install/install.h"
     56 #include "install/package.h"
     57 #include "install/wipe_data.h"
     58 #include "otautil/error_code.h"
     59 #include "otautil/logging.h"
     60 #include "otautil/paths.h"
     61 #include "otautil/roots.h"
     62 #include "otautil/sysutil.h"
     63 #include "recovery_ui/screen_ui.h"
     64 #include "recovery_ui/ui.h"
     65 
     66 static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
     67 static constexpr const char* LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
     68 static constexpr const char* LAST_LOG_FILE = "/cache/recovery/last_log";
     69 static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
     70 
     71 static constexpr const char* CACHE_ROOT = "/cache";
     72 
     73 // We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
     74 // into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
     75 static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
     76 
     77 static bool save_current_log = false;
     78 std::string stage;
     79 const char* reason = nullptr;
     80 
     81 /*
     82  * The recovery tool communicates with the main system through /cache files.
     83  *   /cache/recovery/command - INPUT - command line for tool, one arg per line
     84  *   /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
     85  *
     86  * The arguments which may be supplied in the recovery.command file:
     87  *   --update_package=path - verify install an OTA package file
     88  *   --wipe_data - erase user data (and cache), then reboot
     89  *   --prompt_and_wipe_data - prompt the user that data is corrupt, with their consent erase user
     90  *       data (and cache), then reboot
     91  *   --wipe_cache - wipe cache (but not user data), then reboot
     92  *   --show_text - show the recovery text menu, used by some bootloader (e.g. http://b/36872519).
     93  *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
     94  *   --just_exit - do nothing; exit and reboot
     95  *
     96  * After completing, we remove /cache/recovery/command and reboot.
     97  * Arguments may also be supplied in the bootloader control block (BCB).
     98  * These important scenarios must be safely restartable at any point:
     99  *
    100  * FACTORY RESET
    101  * 1. user selects "factory reset"
    102  * 2. main system writes "--wipe_data" to /cache/recovery/command
    103  * 3. main system reboots into recovery
    104  * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
    105  *    -- after this, rebooting will restart the erase --
    106  * 5. erase_volume() reformats /data
    107  * 6. erase_volume() reformats /cache
    108  * 7. finish_recovery() erases BCB
    109  *    -- after this, rebooting will restart the main system --
    110  * 8. main() calls reboot() to boot main system
    111  *
    112  * OTA INSTALL
    113  * 1. main system downloads OTA package to /cache/some-filename.zip
    114  * 2. main system writes "--update_package=/cache/some-filename.zip"
    115  * 3. main system reboots into recovery
    116  * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
    117  *    -- after this, rebooting will attempt to reinstall the update --
    118  * 5. install_package() attempts to install the update
    119  *    NOTE: the package install must itself be restartable from any point
    120  * 6. finish_recovery() erases BCB
    121  *    -- after this, rebooting will (try to) restart the main system --
    122  * 7. ** if install failed **
    123  *    7a. prompt_and_wait() shows an error icon and waits for the user
    124  *    7b. the user reboots (pulling the battery, etc) into the main system
    125  */
    126 
    127 bool is_ro_debuggable() {
    128     return android::base::GetBoolProperty("ro.debuggable", false);
    129 }
    130 
    131 // Clear the recovery command and prepare to boot a (hopefully working) system,
    132 // copy our log file to cache as well (for the system to read). This function is
    133 // idempotent: call it as many times as you like.
    134 static void finish_recovery() {
    135   std::string locale = ui->GetLocale();
    136   // Save the locale to cache, so if recovery is next started up without a '--locale' argument
    137   // (e.g., directly from the bootloader) it will use the last-known locale.
    138   if (!locale.empty() && has_cache) {
    139     LOG(INFO) << "Saving locale \"" << locale << "\"";
    140     if (ensure_path_mounted(LOCALE_FILE) != 0) {
    141       LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
    142     } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
    143       PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
    144     }
    145   }
    146 
    147   copy_logs(save_current_log, has_cache, sehandle);
    148 
    149   // Reset to normal system boot so recovery won't cycle indefinitely.
    150   std::string err;
    151   if (!clear_bootloader_message(&err)) {
    152     LOG(ERROR) << "Failed to clear BCB message: " << err;
    153   }
    154 
    155   // Remove the command file, so recovery won't repeat indefinitely.
    156   if (has_cache) {
    157     if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
    158       LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
    159     }
    160     ensure_path_unmounted(CACHE_ROOT);
    161   }
    162 
    163   sync();  // For good measure.
    164 }
    165 
    166 static bool yes_no(Device* device, const char* question1, const char* question2) {
    167   std::vector<std::string> headers{ question1, question2 };
    168   std::vector<std::string> items{ " No", " Yes" };
    169 
    170   size_t chosen_item = ui->ShowMenu(
    171       headers, items, 0, true,
    172       std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
    173   return (chosen_item == 1);
    174 }
    175 
    176 static bool ask_to_wipe_data(Device* device) {
    177   std::vector<std::string> headers{ "Wipe all user data?", "  THIS CAN NOT BE UNDONE!" };
    178   std::vector<std::string> items{ " Cancel", " Factory data reset" };
    179 
    180   size_t chosen_item = ui->ShowPromptWipeDataConfirmationMenu(
    181       headers, items,
    182       std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
    183 
    184   return (chosen_item == 1);
    185 }
    186 
    187 static InstallResult prompt_and_wipe_data(Device* device) {
    188   // Use a single string and let ScreenRecoveryUI handles the wrapping.
    189   std::vector<std::string> wipe_data_menu_headers{
    190     "Can't load Android system. Your data may be corrupt. "
    191     "If you continue to get this message, you may need to "
    192     "perform a factory data reset and erase all user data "
    193     "stored on this device.",
    194   };
    195   // clang-format off
    196   std::vector<std::string> wipe_data_menu_items {
    197     "Try again",
    198     "Factory data reset",
    199   };
    200   // clang-format on
    201   for (;;) {
    202     size_t chosen_item = ui->ShowPromptWipeDataMenu(
    203         wipe_data_menu_headers, wipe_data_menu_items,
    204         std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
    205     // If ShowMenu() returned RecoveryUI::KeyError::INTERRUPTED, WaitKey() was interrupted.
    206     if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
    207       return INSTALL_KEY_INTERRUPTED;
    208     }
    209     if (chosen_item != 1) {
    210       return INSTALL_SUCCESS;  // Just reboot, no wipe; not a failure, user asked for it
    211     }
    212 
    213     if (ask_to_wipe_data(device)) {
    214       bool convert_fbe = reason && strcmp(reason, "convert_fbe") == 0;
    215       if (WipeData(device, convert_fbe)) {
    216         return INSTALL_SUCCESS;
    217       } else {
    218         return INSTALL_ERROR;
    219       }
    220     }
    221   }
    222 }
    223 
    224 // Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
    225 // BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
    226 static bool secure_wipe_partition(const std::string& partition) {
    227   android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
    228   if (fd == -1) {
    229     PLOG(ERROR) << "Failed to open \"" << partition << "\"";
    230     return false;
    231   }
    232 
    233   uint64_t range[2] = { 0, 0 };
    234   if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
    235     PLOG(ERROR) << "Failed to get partition size";
    236     return false;
    237   }
    238   LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
    239 
    240   LOG(INFO) << "  Trying BLKSECDISCARD...";
    241   if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
    242     PLOG(WARNING) << "  Failed";
    243 
    244     // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
    245     unsigned int zeroes;
    246     if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
    247       LOG(INFO) << "  Trying BLKDISCARD...";
    248       if (ioctl(fd, BLKDISCARD, &range) == -1) {
    249         PLOG(ERROR) << "  Failed";
    250         return false;
    251       }
    252     } else {
    253       LOG(INFO) << "  Trying BLKZEROOUT...";
    254       if (ioctl(fd, BLKZEROOUT, &range) == -1) {
    255         PLOG(ERROR) << "  Failed";
    256         return false;
    257       }
    258     }
    259   }
    260 
    261   LOG(INFO) << "  Done";
    262   return true;
    263 }
    264 
    265 static std::unique_ptr<Package> ReadWipePackage(size_t wipe_package_size) {
    266   if (wipe_package_size == 0) {
    267     LOG(ERROR) << "wipe_package_size is zero";
    268     return nullptr;
    269   }
    270 
    271   std::string wipe_package;
    272   std::string err_str;
    273   if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
    274     PLOG(ERROR) << "Failed to read wipe package" << err_str;
    275     return nullptr;
    276   }
    277 
    278   return Package::CreateMemoryPackage(
    279       std::vector<uint8_t>(wipe_package.begin(), wipe_package.end()), nullptr);
    280 }
    281 
    282 // Checks if the wipe package matches expectation. If the check passes, reads the list of
    283 // partitions to wipe from the package. Checks include
    284 // 1. verify the package.
    285 // 2. check metadata (ota-type, pre-device and serial number if having one).
    286 static bool CheckWipePackage(Package* wipe_package) {
    287   if (!verify_package(wipe_package, ui)) {
    288     LOG(ERROR) << "Failed to verify package";
    289     return false;
    290   }
    291 
    292   ZipArchiveHandle zip = wipe_package->GetZipArchiveHandle();
    293   if (!zip) {
    294     LOG(ERROR) << "Failed to get ZipArchiveHandle";
    295     return false;
    296   }
    297 
    298   std::map<std::string, std::string> metadata;
    299   if (!ReadMetadataFromPackage(zip, &metadata)) {
    300     LOG(ERROR) << "Failed to parse metadata in the zip file";
    301     return false;
    302   }
    303 
    304   return CheckPackageMetadata(metadata, OtaType::BRICK) == 0;
    305 }
    306 
    307 std::vector<std::string> GetWipePartitionList(Package* wipe_package) {
    308   ZipArchiveHandle zip = wipe_package->GetZipArchiveHandle();
    309   if (!zip) {
    310     LOG(ERROR) << "Failed to get ZipArchiveHandle";
    311     return {};
    312   }
    313 
    314   static constexpr const char* RECOVERY_WIPE_ENTRY_NAME = "recovery.wipe";
    315 
    316   std::string partition_list_content;
    317   ZipString path(RECOVERY_WIPE_ENTRY_NAME);
    318   ZipEntry entry;
    319   if (FindEntry(zip, path, &entry) == 0) {
    320     uint32_t length = entry.uncompressed_length;
    321     partition_list_content = std::string(length, '\0');
    322     if (auto err = ExtractToMemory(
    323             zip, &entry, reinterpret_cast<uint8_t*>(partition_list_content.data()), length);
    324         err != 0) {
    325       LOG(ERROR) << "Failed to extract " << RECOVERY_WIPE_ENTRY_NAME << ": "
    326                  << ErrorCodeString(err);
    327       return {};
    328     }
    329   } else {
    330     LOG(INFO) << "Failed to find " << RECOVERY_WIPE_ENTRY_NAME
    331               << ", falling back to use the partition list on device.";
    332 
    333     static constexpr const char* RECOVERY_WIPE_ON_DEVICE = "/etc/recovery.wipe";
    334     if (!android::base::ReadFileToString(RECOVERY_WIPE_ON_DEVICE, &partition_list_content)) {
    335       PLOG(ERROR) << "failed to read \"" << RECOVERY_WIPE_ON_DEVICE << "\"";
    336       return {};
    337     }
    338   }
    339 
    340   std::vector<std::string> result;
    341   std::vector<std::string> lines = android::base::Split(partition_list_content, "\n");
    342   for (const std::string& line : lines) {
    343     std::string partition = android::base::Trim(line);
    344     // Ignore '#' comment or empty lines.
    345     if (android::base::StartsWith(partition, "#") || partition.empty()) {
    346       continue;
    347     }
    348     result.push_back(line);
    349   }
    350 
    351   return result;
    352 }
    353 
    354 // Wipes the current A/B device, with a secure wipe of all the partitions in RECOVERY_WIPE.
    355 static bool wipe_ab_device(size_t wipe_package_size) {
    356   ui->SetBackground(RecoveryUI::ERASING);
    357   ui->SetProgressType(RecoveryUI::INDETERMINATE);
    358 
    359   auto wipe_package = ReadWipePackage(wipe_package_size);
    360   if (!wipe_package) {
    361     LOG(ERROR) << "Failed to open wipe package";
    362     return false;
    363   }
    364 
    365   if (!CheckWipePackage(wipe_package.get())) {
    366     LOG(ERROR) << "Failed to verify wipe package";
    367     return false;
    368   }
    369 
    370   auto partition_list = GetWipePartitionList(wipe_package.get());
    371   if (partition_list.empty()) {
    372     LOG(ERROR) << "Empty wipe ab partition list";
    373     return false;
    374   }
    375 
    376   for (const auto& partition : partition_list) {
    377     // Proceed anyway even if it fails to wipe some partition.
    378     secure_wipe_partition(partition);
    379   }
    380   return true;
    381 }
    382 
    383 static void choose_recovery_file(Device* device) {
    384   std::vector<std::string> entries;
    385   if (has_cache) {
    386     for (int i = 0; i < KEEP_LOG_COUNT; i++) {
    387       auto add_to_entries = [&](const char* filename) {
    388         std::string log_file(filename);
    389         if (i > 0) {
    390           log_file += "." + std::to_string(i);
    391         }
    392 
    393         if (ensure_path_mounted(log_file) == 0 && access(log_file.c_str(), R_OK) == 0) {
    394           entries.push_back(std::move(log_file));
    395         }
    396       };
    397 
    398       // Add LAST_LOG_FILE + LAST_LOG_FILE.x
    399       add_to_entries(LAST_LOG_FILE);
    400 
    401       // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
    402       add_to_entries(LAST_KMSG_FILE);
    403     }
    404   } else {
    405     // If cache partition is not found, view /tmp/recovery.log instead.
    406     if (access(Paths::Get().temporary_log_file().c_str(), R_OK) == -1) {
    407       return;
    408     } else {
    409       entries.push_back(Paths::Get().temporary_log_file());
    410     }
    411   }
    412 
    413   entries.push_back("Back");
    414 
    415   std::vector<std::string> headers{ "Select file to view" };
    416 
    417   size_t chosen_item = 0;
    418   while (true) {
    419     chosen_item = ui->ShowMenu(
    420         headers, entries, chosen_item, true,
    421         std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
    422 
    423     // Handle WaitKey() interrupt.
    424     if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
    425       break;
    426     }
    427     if (entries[chosen_item] == "Back") break;
    428 
    429     ui->ShowFile(entries[chosen_item]);
    430   }
    431 }
    432 
    433 static void run_graphics_test() {
    434   // Switch to graphics screen.
    435   ui->ShowText(false);
    436 
    437   ui->SetProgressType(RecoveryUI::INDETERMINATE);
    438   ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
    439   sleep(1);
    440 
    441   ui->SetBackground(RecoveryUI::ERROR);
    442   sleep(1);
    443 
    444   ui->SetBackground(RecoveryUI::NO_COMMAND);
    445   sleep(1);
    446 
    447   ui->SetBackground(RecoveryUI::ERASING);
    448   sleep(1);
    449 
    450   // Calling SetBackground() after SetStage() to trigger a redraw.
    451   ui->SetStage(1, 3);
    452   ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
    453   sleep(1);
    454   ui->SetStage(2, 3);
    455   ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
    456   sleep(1);
    457   ui->SetStage(3, 3);
    458   ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
    459   sleep(1);
    460 
    461   ui->SetStage(-1, -1);
    462   ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
    463 
    464   ui->SetProgressType(RecoveryUI::DETERMINATE);
    465   ui->ShowProgress(1.0, 10.0);
    466   float fraction = 0.0;
    467   for (size_t i = 0; i < 100; ++i) {
    468     fraction += .01;
    469     ui->SetProgress(fraction);
    470     usleep(100000);
    471   }
    472 
    473   ui->ShowText(true);
    474 }
    475 
    476 // Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
    477 // which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
    478 static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
    479   for (;;) {
    480     finish_recovery();
    481     switch (status) {
    482       case INSTALL_SUCCESS:
    483       case INSTALL_NONE:
    484         ui->SetBackground(RecoveryUI::NO_COMMAND);
    485         break;
    486 
    487       case INSTALL_ERROR:
    488       case INSTALL_CORRUPT:
    489         ui->SetBackground(RecoveryUI::ERROR);
    490         break;
    491     }
    492     ui->SetProgressType(RecoveryUI::EMPTY);
    493 
    494     size_t chosen_item = ui->ShowMenu(
    495         {}, device->GetMenuItems(), 0, false,
    496         std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
    497     // Handle Interrupt key
    498     if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
    499       return Device::KEY_INTERRUPTED;
    500     }
    501     // Device-specific code may take some action here. It may return one of the core actions
    502     // handled in the switch statement below.
    503     Device::BuiltinAction chosen_action =
    504         (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::TIMED_OUT))
    505             ? Device::REBOOT
    506             : device->InvokeMenuItem(chosen_item);
    507 
    508     switch (chosen_action) {
    509       case Device::NO_ACTION:
    510         break;
    511 
    512       case Device::ENTER_FASTBOOT:
    513       case Device::ENTER_RECOVERY:
    514       case Device::REBOOT:
    515       case Device::REBOOT_BOOTLOADER:
    516       case Device::REBOOT_FASTBOOT:
    517       case Device::REBOOT_RECOVERY:
    518       case Device::REBOOT_RESCUE:
    519       case Device::SHUTDOWN:
    520         return chosen_action;
    521 
    522       case Device::WIPE_DATA:
    523         save_current_log = true;
    524         if (ui->IsTextVisible()) {
    525           if (ask_to_wipe_data(device)) {
    526             WipeData(device, false);
    527           }
    528         } else {
    529           WipeData(device, false);
    530           return Device::NO_ACTION;
    531         }
    532         break;
    533 
    534       case Device::WIPE_CACHE: {
    535         save_current_log = true;
    536         std::function<bool()> confirm_func = [&device]() {
    537           return yes_no(device, "Wipe cache?", "  THIS CAN NOT BE UNDONE!");
    538         };
    539         WipeCache(ui, ui->IsTextVisible() ? confirm_func : nullptr);
    540         if (!ui->IsTextVisible()) return Device::NO_ACTION;
    541         break;
    542       }
    543 
    544       case Device::APPLY_ADB_SIDELOAD:
    545       case Device::APPLY_SDCARD:
    546       case Device::ENTER_RESCUE: {
    547         save_current_log = true;
    548 
    549         bool adb = true;
    550         Device::BuiltinAction reboot_action;
    551         if (chosen_action == Device::ENTER_RESCUE) {
    552           // Switch to graphics screen.
    553           ui->ShowText(false);
    554           status = ApplyFromAdb(device, true /* rescue_mode */, &reboot_action);
    555         } else if (chosen_action == Device::APPLY_ADB_SIDELOAD) {
    556           status = ApplyFromAdb(device, false /* rescue_mode */, &reboot_action);
    557         } else {
    558           adb = false;
    559           status = ApplyFromSdcard(device, ui);
    560         }
    561 
    562         ui->Print("\nInstall from %s completed with status %d.\n", adb ? "ADB" : "SD card", status);
    563         if (status == INSTALL_REBOOT) {
    564           return reboot_action;
    565         }
    566 
    567         if (status != INSTALL_SUCCESS) {
    568           ui->SetBackground(RecoveryUI::ERROR);
    569           ui->Print("Installation aborted.\n");
    570           copy_logs(save_current_log, has_cache, sehandle);
    571         } else if (!ui->IsTextVisible()) {
    572           return Device::NO_ACTION;  // reboot if logs aren't visible
    573         }
    574         break;
    575       }
    576 
    577       case Device::VIEW_RECOVERY_LOGS:
    578         choose_recovery_file(device);
    579         break;
    580 
    581       case Device::RUN_GRAPHICS_TEST:
    582         run_graphics_test();
    583         break;
    584 
    585       case Device::RUN_LOCALE_TEST: {
    586         ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
    587         screen_ui->CheckBackgroundTextImages();
    588         break;
    589       }
    590       case Device::MOUNT_SYSTEM:
    591         // the system partition is mounted at /mnt/system
    592         if (ensure_path_mounted_at(get_system_root(), "/mnt/system") != -1) {
    593           ui->Print("Mounted /system.\n");
    594         }
    595         break;
    596 
    597       case Device::KEY_INTERRUPTED:
    598         return Device::KEY_INTERRUPTED;
    599     }
    600   }
    601 }
    602 
    603 static void print_property(const char* key, const char* name, void* /* cookie */) {
    604   printf("%s=%s\n", key, name);
    605 }
    606 
    607 static bool is_battery_ok(int* required_battery_level) {
    608   using android::hardware::health::V1_0::BatteryStatus;
    609   using android::hardware::health::V2_0::get_health_service;
    610   using android::hardware::health::V2_0::IHealth;
    611   using android::hardware::health::V2_0::Result;
    612   using android::hardware::health::V2_0::toString;
    613 
    614   android::sp<IHealth> health = get_health_service();
    615 
    616   static constexpr int BATTERY_READ_TIMEOUT_IN_SEC = 10;
    617   int wait_second = 0;
    618   while (true) {
    619     auto charge_status = BatteryStatus::UNKNOWN;
    620 
    621     if (health == nullptr) {
    622       LOG(WARNING) << "no health implementation is found, assuming defaults";
    623     } else {
    624       health
    625           ->getChargeStatus([&charge_status](auto res, auto out_status) {
    626             if (res == Result::SUCCESS) {
    627               charge_status = out_status;
    628             }
    629           })
    630           .isOk();  // should not have transport error
    631     }
    632 
    633     // Treat unknown status as charged.
    634     bool charged = (charge_status != BatteryStatus::DISCHARGING &&
    635                     charge_status != BatteryStatus::NOT_CHARGING);
    636 
    637     Result res = Result::UNKNOWN;
    638     int32_t capacity = INT32_MIN;
    639     if (health != nullptr) {
    640       health
    641           ->getCapacity([&res, &capacity](auto out_res, auto out_capacity) {
    642             res = out_res;
    643             capacity = out_capacity;
    644           })
    645           .isOk();  // should not have transport error
    646     }
    647 
    648     LOG(INFO) << "charge_status " << toString(charge_status) << ", charged " << charged
    649               << ", status " << toString(res) << ", capacity " << capacity;
    650     // At startup, the battery drivers in devices like N5X/N6P take some time to load
    651     // the battery profile. Before the load finishes, it reports value 50 as a fake
    652     // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
    653     // to finish loading the battery profile earlier than 10 seconds after kernel startup.
    654     if (res == Result::SUCCESS && capacity == 50) {
    655       if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
    656         sleep(1);
    657         wait_second++;
    658         continue;
    659       }
    660     }
    661     // If we can't read battery percentage, it may be a device without battery. In this
    662     // situation, use 100 as a fake battery percentage.
    663     if (res != Result::SUCCESS) {
    664       capacity = 100;
    665     }
    666 
    667     // GmsCore enters recovery mode to install package when having enough battery percentage.
    668     // Normally, the threshold is 40% without charger and 20% with charger. So we should check
    669     // battery with a slightly lower limitation.
    670     static constexpr int BATTERY_OK_PERCENTAGE = 20;
    671     static constexpr int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
    672     *required_battery_level = charged ? BATTERY_WITH_CHARGER_OK_PERCENTAGE : BATTERY_OK_PERCENTAGE;
    673     return capacity >= *required_battery_level;
    674   }
    675 }
    676 
    677 // Set the retry count to |retry_count| in BCB.
    678 static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
    679   std::vector<std::string> options;
    680   for (const auto& arg : args) {
    681     if (!android::base::StartsWith(arg, "--retry_count")) {
    682       options.push_back(arg);
    683     }
    684   }
    685 
    686   // Update the retry counter in BCB.
    687   options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
    688   std::string err;
    689   if (!update_bootloader_message(options, &err)) {
    690     LOG(ERROR) << err;
    691   }
    692 }
    693 
    694 static bool bootreason_in_blacklist() {
    695   std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
    696   if (!bootreason.empty()) {
    697     // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
    698     static const std::vector<std::string> kBootreasonBlacklist{
    699       "kernel_panic",
    700       "Panic",
    701     };
    702     for (const auto& str : kBootreasonBlacklist) {
    703       if (android::base::EqualsIgnoreCase(str, bootreason)) return true;
    704     }
    705   }
    706   return false;
    707 }
    708 
    709 static void log_failure_code(ErrorCode code, const std::string& update_package) {
    710   std::vector<std::string> log_buffer = {
    711     update_package,
    712     "0",  // install result
    713     "error: " + std::to_string(code),
    714   };
    715   std::string log_content = android::base::Join(log_buffer, "\n");
    716   const std::string& install_file = Paths::Get().temporary_install_file();
    717   if (!android::base::WriteStringToFile(log_content, install_file)) {
    718     PLOG(ERROR) << "Failed to write " << install_file;
    719   }
    720 
    721   // Also write the info into last_log.
    722   LOG(INFO) << log_content;
    723 }
    724 
    725 Device::BuiltinAction start_recovery(Device* device, const std::vector<std::string>& args) {
    726   static constexpr struct option OPTIONS[] = {
    727     { "fastboot", no_argument, nullptr, 0 },
    728     { "fsck_unshare_blocks", no_argument, nullptr, 0 },
    729     { "just_exit", no_argument, nullptr, 'x' },
    730     { "locale", required_argument, nullptr, 0 },
    731     { "prompt_and_wipe_data", no_argument, nullptr, 0 },
    732     { "reason", required_argument, nullptr, 0 },
    733     { "rescue", no_argument, nullptr, 0 },
    734     { "retry_count", required_argument, nullptr, 0 },
    735     { "security", no_argument, nullptr, 0 },
    736     { "show_text", no_argument, nullptr, 't' },
    737     { "shutdown_after", no_argument, nullptr, 0 },
    738     { "sideload", no_argument, nullptr, 0 },
    739     { "sideload_auto_reboot", no_argument, nullptr, 0 },
    740     { "update_package", required_argument, nullptr, 0 },
    741     { "wipe_ab", no_argument, nullptr, 0 },
    742     { "wipe_cache", no_argument, nullptr, 0 },
    743     { "wipe_data", no_argument, nullptr, 0 },
    744     { "wipe_package_size", required_argument, nullptr, 0 },
    745     { nullptr, 0, nullptr, 0 },
    746   };
    747 
    748   const char* update_package = nullptr;
    749   bool should_wipe_data = false;
    750   bool should_prompt_and_wipe_data = false;
    751   bool should_wipe_cache = false;
    752   bool should_wipe_ab = false;
    753   size_t wipe_package_size = 0;
    754   bool sideload = false;
    755   bool sideload_auto_reboot = false;
    756   bool rescue = false;
    757   bool just_exit = false;
    758   bool shutdown_after = false;
    759   bool fsck_unshare_blocks = false;
    760   int retry_count = 0;
    761   bool security_update = false;
    762   std::string locale;
    763 
    764   auto args_to_parse = StringVectorToNullTerminatedArray(args);
    765 
    766   int arg;
    767   int option_index;
    768   // Parse everything before the last element (which must be a nullptr). getopt_long(3) expects a
    769   // null-terminated char* array, but without counting null as an arg (i.e. argv[argc] should be
    770   // nullptr).
    771   while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
    772                             &option_index)) != -1) {
    773     switch (arg) {
    774       case 't':
    775         // Handled in recovery_main.cpp
    776         break;
    777       case 'x':
    778         just_exit = true;
    779         break;
    780       case 0: {
    781         std::string option = OPTIONS[option_index].name;
    782         if (option == "fsck_unshare_blocks") {
    783           fsck_unshare_blocks = true;
    784         } else if (option == "locale" || option == "fastboot") {
    785           // Handled in recovery_main.cpp
    786         } else if (option == "prompt_and_wipe_data") {
    787           should_prompt_and_wipe_data = true;
    788         } else if (option == "reason") {
    789           reason = optarg;
    790         } else if (option == "rescue") {
    791           rescue = true;
    792         } else if (option == "retry_count") {
    793           android::base::ParseInt(optarg, &retry_count, 0);
    794         } else if (option == "security") {
    795           security_update = true;
    796         } else if (option == "sideload") {
    797           sideload = true;
    798         } else if (option == "sideload_auto_reboot") {
    799           sideload = true;
    800           sideload_auto_reboot = true;
    801         } else if (option == "shutdown_after") {
    802           shutdown_after = true;
    803         } else if (option == "update_package") {
    804           update_package = optarg;
    805         } else if (option == "wipe_ab") {
    806           should_wipe_ab = true;
    807         } else if (option == "wipe_cache") {
    808           should_wipe_cache = true;
    809         } else if (option == "wipe_data") {
    810           should_wipe_data = true;
    811         } else if (option == "wipe_package_size") {
    812           android::base::ParseUint(optarg, &wipe_package_size);
    813         }
    814         break;
    815       }
    816       case '?':
    817         LOG(ERROR) << "Invalid command argument";
    818         continue;
    819     }
    820   }
    821   optind = 1;
    822 
    823   printf("stage is [%s]\n", stage.c_str());
    824   printf("reason is [%s]\n", reason);
    825 
    826   // Set background string to "installing security update" for security update,
    827   // otherwise set it to "installing system update".
    828   ui->SetSystemUpdateText(security_update);
    829 
    830   int st_cur, st_max;
    831   if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
    832     ui->SetStage(st_cur, st_max);
    833   }
    834 
    835   std::vector<std::string> title_lines =
    836       android::base::Split(android::base::GetProperty("ro.bootimage.build.fingerprint", ""), ":");
    837   title_lines.insert(std::begin(title_lines), "Android Recovery");
    838   ui->SetTitle(title_lines);
    839 
    840   ui->ResetKeyInterruptStatus();
    841   device->StartRecovery();
    842 
    843   printf("Command:");
    844   for (const auto& arg : args) {
    845     printf(" \"%s\"", arg.c_str());
    846   }
    847   printf("\n\n");
    848 
    849   property_list(print_property, nullptr);
    850   printf("\n");
    851 
    852   ui->Print("Supported API: %d\n", kRecoveryApiVersion);
    853 
    854   int status = INSTALL_SUCCESS;
    855   // next_action indicates the next target to reboot into upon finishing the install. It could be
    856   // overridden to a different reboot target per user request.
    857   Device::BuiltinAction next_action = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
    858 
    859   if (update_package != nullptr) {
    860     // It's not entirely true that we will modify the flash. But we want
    861     // to log the update attempt since update_package is non-NULL.
    862     save_current_log = true;
    863 
    864     int required_battery_level;
    865     if (retry_count == 0 && !is_battery_ok(&required_battery_level)) {
    866       ui->Print("battery capacity is not enough for installing package: %d%% needed\n",
    867                 required_battery_level);
    868       // Log the error code to last_install when installation skips due to
    869       // low battery.
    870       log_failure_code(kLowBattery, update_package);
    871       status = INSTALL_SKIPPED;
    872     } else if (retry_count == 0 && bootreason_in_blacklist()) {
    873       // Skip update-on-reboot when bootreason is kernel_panic or similar
    874       ui->Print("bootreason is in the blacklist; skip OTA installation\n");
    875       log_failure_code(kBootreasonInBlacklist, update_package);
    876       status = INSTALL_SKIPPED;
    877     } else {
    878       // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
    879       // identify the interrupted update due to unexpected reboots.
    880       if (retry_count == 0) {
    881         set_retry_bootloader_message(retry_count + 1, args);
    882       }
    883 
    884       status = install_package(update_package, should_wipe_cache, true, retry_count, ui);
    885       if (status != INSTALL_SUCCESS) {
    886         ui->Print("Installation aborted.\n");
    887 
    888         // When I/O error or bspatch/imgpatch error happens, reboot and retry installation
    889         // RETRY_LIMIT times before we abandon this OTA update.
    890         static constexpr int RETRY_LIMIT = 4;
    891         if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
    892           copy_logs(save_current_log, has_cache, sehandle);
    893           retry_count += 1;
    894           set_retry_bootloader_message(retry_count, args);
    895           // Print retry count on screen.
    896           ui->Print("Retry attempt %d\n", retry_count);
    897 
    898           // Reboot and retry the update
    899           if (!reboot("reboot,recovery")) {
    900             ui->Print("Reboot failed\n");
    901           } else {
    902             while (true) {
    903               pause();
    904             }
    905           }
    906         }
    907         // If this is an eng or userdebug build, then automatically
    908         // turn the text display on if the script fails so the error
    909         // message is visible.
    910         if (is_ro_debuggable()) {
    911           ui->ShowText(true);
    912         }
    913       }
    914     }
    915   } else if (should_wipe_data) {
    916     save_current_log = true;
    917     bool convert_fbe = reason && strcmp(reason, "convert_fbe") == 0;
    918     if (!WipeData(device, convert_fbe)) {
    919       status = INSTALL_ERROR;
    920     }
    921   } else if (should_prompt_and_wipe_data) {
    922     // Trigger the logging to capture the cause, even if user chooses to not wipe data.
    923     save_current_log = true;
    924 
    925     ui->ShowText(true);
    926     ui->SetBackground(RecoveryUI::ERROR);
    927     status = prompt_and_wipe_data(device);
    928     if (status != INSTALL_KEY_INTERRUPTED) {
    929       ui->ShowText(false);
    930     }
    931   } else if (should_wipe_cache) {
    932     save_current_log = true;
    933     if (!WipeCache(ui, nullptr)) {
    934       status = INSTALL_ERROR;
    935     }
    936   } else if (should_wipe_ab) {
    937     if (!wipe_ab_device(wipe_package_size)) {
    938       status = INSTALL_ERROR;
    939     }
    940   } else if (sideload) {
    941     // 'adb reboot sideload' acts the same as user presses key combinations to enter the sideload
    942     // mode. When 'sideload-auto-reboot' is used, text display will NOT be turned on by default. And
    943     // it will reboot after sideload finishes even if there are errors. This is to enable automated
    944     // testing.
    945     save_current_log = true;
    946     if (!sideload_auto_reboot) {
    947       ui->ShowText(true);
    948     }
    949     status = ApplyFromAdb(device, false /* rescue_mode */, &next_action);
    950     ui->Print("\nInstall from ADB complete (status: %d).\n", status);
    951     if (sideload_auto_reboot) {
    952       status = INSTALL_REBOOT;
    953       ui->Print("Rebooting automatically.\n");
    954     }
    955   } else if (rescue) {
    956     save_current_log = true;
    957     status = ApplyFromAdb(device, true /* rescue_mode */, &next_action);
    958     ui->Print("\nInstall from ADB complete (status: %d).\n", status);
    959   } else if (fsck_unshare_blocks) {
    960     if (!do_fsck_unshare_blocks()) {
    961       status = INSTALL_ERROR;
    962     }
    963   } else if (!just_exit) {
    964     // If this is an eng or userdebug build, automatically turn on the text display if no command
    965     // is specified. Note that this should be called before setting the background to avoid
    966     // flickering the background image.
    967     if (is_ro_debuggable()) {
    968       ui->ShowText(true);
    969     }
    970     status = INSTALL_NONE;  // No command specified
    971     ui->SetBackground(RecoveryUI::NO_COMMAND);
    972   }
    973 
    974   if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
    975     ui->SetBackground(RecoveryUI::ERROR);
    976     if (!ui->IsTextVisible()) {
    977       sleep(5);
    978     }
    979   }
    980 
    981   // Determine the next action.
    982   //  - If the state is INSTALL_REBOOT, device will reboot into the target as specified in
    983   //    `next_action`.
    984   //  - If the recovery menu is visible, prompt and wait for commands.
    985   //  - If the state is INSTALL_NONE, wait for commands (e.g. in user build, one manually boots
    986   //    into recovery to sideload a package or to wipe the device).
    987   //  - In all other cases, reboot the device. Therefore, normal users will observe the device
    988   //    rebooting a) immediately upon successful finish (INSTALL_SUCCESS); or b) an "error" screen
    989   //    for 5s followed by an automatic reboot.
    990   if (status != INSTALL_REBOOT) {
    991     if (status == INSTALL_NONE || ui->IsTextVisible()) {
    992       Device::BuiltinAction temp = prompt_and_wait(device, status);
    993       if (temp != Device::NO_ACTION) {
    994         next_action = temp;
    995       }
    996     }
    997   }
    998 
    999   // Save logs and clean up before rebooting or shutting down.
   1000   finish_recovery();
   1001 
   1002   return next_action;
   1003 }
   1004