blob: 7b8e32bf43c2f3d5ea11fed23f6e465c33e77b5f [file] [log] [blame]
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001/*
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
Jerry Zhang6a648042018-05-04 11:24:10 -070017#include "recovery.h"
Tao Bao2ac56af2018-04-25 16:47:04 -070018
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080019#include <ctype.h>
20#include <errno.h>
21#include <fcntl.h>
22#include <getopt.h>
Tao Bao862a4c12016-06-02 11:16:50 -070023#include <inttypes.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080024#include <limits.h>
Tao Bao862a4c12016-06-02 11:16:50 -070025#include <linux/fs.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080026#include <linux/input.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080030#include <sys/types.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080031#include <unistd.h>
32
Tao Baoc4a18ef2017-02-10 00:13:30 -080033#include <algorithm>
Tao Bao3aec6962018-04-20 09:24:58 -070034#include <functional>
Tao Baoc4a18ef2017-02-10 00:13:30 -080035#include <memory>
Tao Bao862a4c12016-06-02 11:16:50 -070036#include <string>
37#include <vector>
Tao Bao04ca4262015-09-10 15:32:24 -070038
Elliott Hughes4b166f02015-12-04 15:30:20 -080039#include <android-base/file.h>
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -070040#include <android-base/logging.h>
Tianjie Xu3c62b672016-02-05 18:25:58 -080041#include <android-base/parseint.h>
Elliott Hughescb220402016-09-23 15:30:55 -070042#include <android-base/properties.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080043#include <android-base/stringprintf.h>
Tao Bao862a4c12016-06-02 11:16:50 -070044#include <android-base/strings.h>
45#include <android-base/unique_fd.h>
Yabin Cui8b309f62016-06-24 18:22:02 -070046#include <bootloader_message/bootloader_message.h>
Elliott Hughescb220402016-09-23 15:30:55 -070047#include <cutils/properties.h> /* for property_list */
Yifan Hong056538c2018-07-11 17:04:12 -070048#include <healthhalutils/HealthHalUtils.h>
Tom Marshallbead2612019-01-04 14:37:31 -080049#include <volume_manager/VolumeManager.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070050#include <ziparchive/zip_archive.h>
Yabin Cui99281df2016-02-17 12:21:52 -080051
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080052#include "common.h"
David Andersonedee8362018-05-16 13:43:22 -070053#include "fsck_unshare_blocks.h"
xunchang24788852019-03-22 16:08:52 -070054#include "install/adb_install.h"
55#include "install/fuse_sdcard_install.h"
56#include "install/install.h"
57#include "install/package.h"
xunchang388d2532019-04-12 16:22:15 -070058#include "install/wipe_data.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070059#include "otautil/error_code.h"
xunchang388d2532019-04-12 16:22:15 -070060#include "otautil/logging.h"
Tao Bao641fa972018-04-25 18:59:40 -070061#include "otautil/paths.h"
xunchang24788852019-03-22 16:08:52 -070062#include "otautil/roots.h"
Tao Bao2c526392018-05-03 23:01:13 -070063#include "otautil/sysutil.h"
Tianjie Xu8f397302018-08-20 13:40:47 -070064#include "recovery_ui/screen_ui.h"
65#include "recovery_ui/ui.h"
Tom Marshallbead2612019-01-04 14:37:31 -080066#include "volclient.h"
67
68using android::volmgr::VolumeManager;
69using android::volmgr::VolumeInfo;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080070
Tao Baoaac9d9f2018-04-29 23:38:59 -070071static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
Tao Baoaac9d9f2018-04-29 23:38:59 -070072static constexpr const char* LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
73static constexpr const char* LAST_LOG_FILE = "/cache/recovery/last_log";
74static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
Tianjie Xu06e57ac2016-07-11 14:04:08 -070075
Tao Baoaac9d9f2018-04-29 23:38:59 -070076static constexpr const char* CACHE_ROOT = "/cache";
Nick Kralevicha9ad0322014-10-22 18:38:48 -070077
Tao Baobd0ddcd2017-05-04 13:03:18 -070078// We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
79// into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
80static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
81
xunchang388d2532019-04-12 16:22:15 -070082static bool save_current_log = false;
Tao Baoa8d72bc2016-12-25 18:46:50 -080083std::string stage;
Tao Baoac9d94d2016-11-03 11:37:15 -070084const char* reason = nullptr;
Tao Baoac9d94d2016-11-03 11:37:15 -070085
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080086/*
87 * The recovery tool communicates with the main system through /cache files.
88 * /cache/recovery/command - INPUT - command line for tool, one arg per line
89 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080090 *
91 * The arguments which may be supplied in the recovery.command file:
Doug Zongkerd4208f92010-09-20 12:16:13 -070092 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080093 * --wipe_data - erase user data (and cache), then reboot
Tao Baof9f17342018-04-27 10:44:04 -070094 * --prompt_and_wipe_data - prompt the user that data is corrupt, with their consent erase user
95 * data (and cache), then reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080096 * --wipe_cache - wipe cache (but not user data), then reboot
Tao Baof9f17342018-04-27 10:44:04 -070097 * --show_text - show the recovery text menu, used by some bootloader (e.g. http://b/36872519).
Oscar Montemayor05231562009-11-30 08:40:57 -080098 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -070099 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800100 *
101 * After completing, we remove /cache/recovery/command and reboot.
102 * Arguments may also be supplied in the bootloader control block (BCB).
103 * These important scenarios must be safely restartable at any point:
104 *
105 * FACTORY RESET
106 * 1. user selects "factory reset"
107 * 2. main system writes "--wipe_data" to /cache/recovery/command
108 * 3. main system reboots into recovery
109 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
110 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700111 * 5. erase_volume() reformats /data
112 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800113 * 7. finish_recovery() erases BCB
114 * -- after this, rebooting will restart the main system --
115 * 8. main() calls reboot() to boot main system
116 *
117 * OTA INSTALL
118 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700119 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800120 * 3. main system reboots into recovery
121 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
122 * -- after this, rebooting will attempt to reinstall the update --
123 * 5. install_package() attempts to install the update
124 * NOTE: the package install must itself be restartable from any point
125 * 6. finish_recovery() erases BCB
126 * -- after this, rebooting will (try to) restart the main system --
127 * 7. ** if install failed **
128 * 7a. prompt_and_wait() shows an error icon and waits for the user
Tao Baoc0336392016-12-13 22:29:49 -0800129 * 7b. the user reboots (pulling the battery, etc) into the main system
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800130 */
131
Elliott Hughesf14af802015-02-10 14:46:14 -0800132bool is_ro_debuggable() {
Elliott Hughescb220402016-09-23 15:30:55 -0700133 return android::base::GetBoolProperty("ro.debuggable", false);
Elliott Hughesf14af802015-02-10 14:46:14 -0800134}
135
Michael Bestas6108e702019-09-27 20:29:42 +0300136std::string get_build_type() {
137 return android::base::GetProperty("ro.build.type", "");
138}
139
Tao Baoec579032017-07-21 12:13:15 -0700140// Clear the recovery command and prepare to boot a (hopefully working) system,
Tianjie Xuc14d95d2016-03-24 11:50:34 -0700141// copy our log file to cache as well (for the system to read). This function is
142// idempotent: call it as many times as you like.
Tao Bao551d2c32018-05-09 20:53:13 -0700143static void finish_recovery() {
144 std::string locale = ui->GetLocale();
Tao Baoec579032017-07-21 12:13:15 -0700145 // Save the locale to cache, so if recovery is next started up without a '--locale' argument
146 // (e.g., directly from the bootloader) it will use the last-known locale.
147 if (!locale.empty() && has_cache) {
148 LOG(INFO) << "Saving locale \"" << locale << "\"";
149 if (ensure_path_mounted(LOCALE_FILE) != 0) {
150 LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
151 } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
152 PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
Doug Zongker4f33e552012-08-23 13:16:12 -0700153 }
Tao Baoec579032017-07-21 12:13:15 -0700154 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700155
xunchang388d2532019-04-12 16:22:15 -0700156 copy_logs(save_current_log, has_cache, sehandle);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800157
Tao Baoec579032017-07-21 12:13:15 -0700158 // Reset to normal system boot so recovery won't cycle indefinitely.
159 std::string err;
160 if (!clear_bootloader_message(&err)) {
161 LOG(ERROR) << "Failed to clear BCB message: " << err;
162 }
163
164 // Remove the command file, so recovery won't repeat indefinitely.
165 if (has_cache) {
166 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
167 LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
Yabin Cui8b309f62016-06-24 18:22:02 -0700168 }
Tao Baoec579032017-07-21 12:13:15 -0700169 ensure_path_unmounted(CACHE_ROOT);
170 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800171
Tao Baoec579032017-07-21 12:13:15 -0700172 sync(); // For good measure.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800173}
174
Elliott Hughes30694c92015-03-25 15:16:51 -0700175static bool yes_no(Device* device, const char* question1, const char* question2) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700176 std::vector<std::string> headers{ question1, question2 };
177 std::vector<std::string> items{ " No", " Yes" };
Doug Zongkerddd6a282009-06-09 12:22:33 -0700178
Tao Bao1fe1afe2018-05-01 15:56:05 -0700179 size_t chosen_item = ui->ShowMenu(
Tao Bao3aec6962018-04-20 09:24:58 -0700180 headers, items, 0, true,
181 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
182 return (chosen_item == 1);
Elliott Hughes30694c92015-03-25 15:16:51 -0700183}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800184
Alessandro Astone4e1e8662020-03-17 22:26:22 +0100185bool ask_to_continue_unverified(Device* device) {
Tom Marshall03354052018-06-21 00:57:24 +0200186 if (get_build_type() == "user") {
187 return false;
188 } else {
189 ui->SetProgressType(RecoveryUI::EMPTY);
190 return yes_no(device, "Signature verification failed", "Install anyway?");
191 }
192}
193
Alessandro Astone8b726282020-03-17 23:06:52 +0100194bool ask_to_continue_downgrade(Device* device) {
195 if (get_build_type() == "user") {
196 return false;
197 } else {
198 ui->SetProgressType(RecoveryUI::EMPTY);
199 return yes_no(device, "This package will downgrade your system", "Install anyway?");
200 }
201}
202
Paul Crowley08404b42016-12-19 13:04:23 -0800203static bool ask_to_wipe_data(Device* device) {
Tianjie Xu1a0a30a2018-10-25 15:22:07 -0700204 std::vector<std::string> headers{ "Wipe all user data?", " THIS CAN NOT BE UNDONE!" };
205 std::vector<std::string> items{ " Cancel", " Factory data reset" };
206
Alessandro Astonec6ddbac2020-03-09 23:17:50 +0100207 size_t chosen_item = ui->ShowMenu(
208 headers, items, 0, true,
Tianjie Xu1a0a30a2018-10-25 15:22:07 -0700209 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
210
211 return (chosen_item == 1);
Paul Crowley08404b42016-12-19 13:04:23 -0800212}
Doug Zongker1066d2c2009-04-01 13:57:40 -0700213
Tom Marshallbead2612019-01-04 14:37:31 -0800214static int apply_update_menu(Device* device, RecoveryUI* ui, Device::BuiltinAction* reboot_action){
215 std::vector<std::string> headers{ "Apply update" };
216 std::vector<std::string> items;
217
218 const int item_sideload = 0;
219 std::vector<VolumeInfo> volumes;
220
221 int status = INSTALL_ERROR;
222
223 for (;;) {
224 items.clear();
225 items.push_back("Apply from ADB");
226 VolumeManager::Instance()->getVolumeInfo(volumes);
227 for (auto& vitr : volumes) {
228 items.push_back("Choose from " + vitr.mLabel);
229 }
230
231 int chosen = ui->ShowMenu(
232 headers, items, 0, false,
233 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2),
234 true /* refreshable */);
235 if (chosen == Device::kRefresh) {
236 continue;
237 }
238 if (chosen == Device::kGoBack) {
239 break;
240 }
241 if (chosen == item_sideload) {
242 status = ApplyFromAdb(device, false /* rescue_mode */, reboot_action);
243 } else {
244 status = ApplyFromStorage(device, volumes[chosen - 1], ui);
245 }
246 }
247 return status;
248}
249
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700250static InstallResult prompt_and_wipe_data(Device* device) {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700251 // Use a single string and let ScreenRecoveryUI handles the wrapping.
Tianjie Xub99e6062018-10-16 15:13:09 -0700252 std::vector<std::string> wipe_data_menu_headers{
Tao Bao2bbc6d62017-08-13 23:48:55 -0700253 "Can't load Android system. Your data may be corrupt. "
254 "If you continue to get this message, you may need to "
255 "perform a factory data reset and erase all user data "
Paul Crowley31ac0c62017-03-23 12:32:40 -0700256 "stored on this device.",
Tao Baofc5499f2017-02-23 19:06:53 -0800257 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700258 // clang-format off
Tianjie Xub99e6062018-10-16 15:13:09 -0700259 std::vector<std::string> wipe_data_menu_items {
Paul Crowley31ac0c62017-03-23 12:32:40 -0700260 "Try again",
261 "Factory data reset",
Tao Baofc5499f2017-02-23 19:06:53 -0800262 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700263 // clang-format on
Tao Baofc5499f2017-02-23 19:06:53 -0800264 for (;;) {
Tianjie Xub99e6062018-10-16 15:13:09 -0700265 size_t chosen_item = ui->ShowPromptWipeDataMenu(
266 wipe_data_menu_headers, wipe_data_menu_items,
Tao Bao3aec6962018-04-20 09:24:58 -0700267 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Jerry Zhangb76af932018-05-22 12:08:35 -0700268 // If ShowMenu() returned RecoveryUI::KeyError::INTERRUPTED, WaitKey() was interrupted.
269 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700270 return INSTALL_KEY_INTERRUPTED;
Jerry Zhangb76af932018-05-22 12:08:35 -0700271 }
Tao Baofc5499f2017-02-23 19:06:53 -0800272 if (chosen_item != 1) {
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700273 return INSTALL_SUCCESS; // Just reboot, no wipe; not a failure, user asked for it
Paul Crowley08404b42016-12-19 13:04:23 -0800274 }
Tianjie Xub99e6062018-10-16 15:13:09 -0700275
Tao Baofc5499f2017-02-23 19:06:53 -0800276 if (ask_to_wipe_data(device)) {
xunchang388d2532019-04-12 16:22:15 -0700277 bool convert_fbe = reason && strcmp(reason, "convert_fbe") == 0;
278 if (WipeData(device, convert_fbe)) {
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700279 return INSTALL_SUCCESS;
280 } else {
281 return INSTALL_ERROR;
282 }
Tao Baofc5499f2017-02-23 19:06:53 -0800283 }
284 }
Paul Crowley08404b42016-12-19 13:04:23 -0800285}
286
Tao Bao1b2a98b2017-03-24 10:45:34 -0700287// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
288// BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
Tao Bao862a4c12016-06-02 11:16:50 -0700289static bool secure_wipe_partition(const std::string& partition) {
Tao Bao1b2a98b2017-03-24 10:45:34 -0700290 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
291 if (fd == -1) {
292 PLOG(ERROR) << "Failed to open \"" << partition << "\"";
293 return false;
294 }
295
296 uint64_t range[2] = { 0, 0 };
297 if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
298 PLOG(ERROR) << "Failed to get partition size";
299 return false;
300 }
301 LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
302
303 LOG(INFO) << " Trying BLKSECDISCARD...";
304 if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
305 PLOG(WARNING) << " Failed";
306
307 // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
308 unsigned int zeroes;
309 if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
310 LOG(INFO) << " Trying BLKDISCARD...";
311 if (ioctl(fd, BLKDISCARD, &range) == -1) {
312 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700313 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700314 }
315 } else {
316 LOG(INFO) << " Trying BLKZEROOUT...";
317 if (ioctl(fd, BLKZEROOUT, &range) == -1) {
318 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700319 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700320 }
Tao Bao862a4c12016-06-02 11:16:50 -0700321 }
Tao Bao1b2a98b2017-03-24 10:45:34 -0700322 }
Tao Bao862a4c12016-06-02 11:16:50 -0700323
Tao Bao1b2a98b2017-03-24 10:45:34 -0700324 LOG(INFO) << " Done";
325 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700326}
327
xunchang55e3d222019-03-11 11:28:41 -0700328static std::unique_ptr<Package> ReadWipePackage(size_t wipe_package_size) {
xunchange0d991c2019-03-05 14:50:51 -0800329 if (wipe_package_size == 0) {
330 LOG(ERROR) << "wipe_package_size is zero";
xunchang55e3d222019-03-11 11:28:41 -0700331 return nullptr;
xunchange0d991c2019-03-05 14:50:51 -0800332 }
333
334 std::string wipe_package;
335 std::string err_str;
336 if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
337 PLOG(ERROR) << "Failed to read wipe package" << err_str;
xunchang55e3d222019-03-11 11:28:41 -0700338 return nullptr;
xunchange0d991c2019-03-05 14:50:51 -0800339 }
xunchang55e3d222019-03-11 11:28:41 -0700340
341 return Package::CreateMemoryPackage(
342 std::vector<uint8_t>(wipe_package.begin(), wipe_package.end()), nullptr);
xunchange0d991c2019-03-05 14:50:51 -0800343}
344
345// Checks if the wipe package matches expectation. If the check passes, reads the list of
346// partitions to wipe from the package. Checks include
Yabin Cuifd99a312016-06-09 14:09:39 -0700347// 1. verify the package.
348// 2. check metadata (ota-type, pre-device and serial number if having one).
xunchang55e3d222019-03-11 11:28:41 -0700349static bool CheckWipePackage(Package* wipe_package) {
xunchang24788852019-03-22 16:08:52 -0700350 if (!verify_package(wipe_package, ui)) {
xunchange0d991c2019-03-05 14:50:51 -0800351 LOG(ERROR) << "Failed to verify package";
352 return false;
353 }
Yabin Cuifd99a312016-06-09 14:09:39 -0700354
xunchang55e3d222019-03-11 11:28:41 -0700355 ZipArchiveHandle zip = wipe_package->GetZipArchiveHandle();
356 if (!zip) {
357 LOG(ERROR) << "Failed to get ZipArchiveHandle";
xunchange0d991c2019-03-05 14:50:51 -0800358 return false;
359 }
360
361 std::map<std::string, std::string> metadata;
362 if (!ReadMetadataFromPackage(zip, &metadata)) {
363 LOG(ERROR) << "Failed to parse metadata in the zip file";
364 return false;
365 }
366
xunchang55e3d222019-03-11 11:28:41 -0700367 return CheckPackageMetadata(metadata, OtaType::BRICK) == 0;
xunchange0d991c2019-03-05 14:50:51 -0800368}
369
xunchang55e3d222019-03-11 11:28:41 -0700370std::vector<std::string> GetWipePartitionList(Package* wipe_package) {
371 ZipArchiveHandle zip = wipe_package->GetZipArchiveHandle();
372 if (!zip) {
373 LOG(ERROR) << "Failed to get ZipArchiveHandle";
xunchange0d991c2019-03-05 14:50:51 -0800374 return {};
375 }
376
377 static constexpr const char* RECOVERY_WIPE_ENTRY_NAME = "recovery.wipe";
378
379 std::string partition_list_content;
380 ZipString path(RECOVERY_WIPE_ENTRY_NAME);
381 ZipEntry entry;
382 if (FindEntry(zip, path, &entry) == 0) {
383 uint32_t length = entry.uncompressed_length;
384 partition_list_content = std::string(length, '\0');
385 if (auto err = ExtractToMemory(
386 zip, &entry, reinterpret_cast<uint8_t*>(partition_list_content.data()), length);
387 err != 0) {
388 LOG(ERROR) << "Failed to extract " << RECOVERY_WIPE_ENTRY_NAME << ": "
389 << ErrorCodeString(err);
xunchange0d991c2019-03-05 14:50:51 -0800390 return {};
Yabin Cuifd99a312016-06-09 14:09:39 -0700391 }
xunchange0d991c2019-03-05 14:50:51 -0800392 } else {
393 LOG(INFO) << "Failed to find " << RECOVERY_WIPE_ENTRY_NAME
394 << ", falling back to use the partition list on device.";
Tianjie Xu93b5bf22018-10-25 10:39:01 -0700395
xunchange0d991c2019-03-05 14:50:51 -0800396 static constexpr const char* RECOVERY_WIPE_ON_DEVICE = "/etc/recovery.wipe";
397 if (!android::base::ReadFileToString(RECOVERY_WIPE_ON_DEVICE, &partition_list_content)) {
398 PLOG(ERROR) << "failed to read \"" << RECOVERY_WIPE_ON_DEVICE << "\"";
xunchange0d991c2019-03-05 14:50:51 -0800399 return {};
Yabin Cuifd99a312016-06-09 14:09:39 -0700400 }
xunchange0d991c2019-03-05 14:50:51 -0800401 }
Tianjie Xu93b5bf22018-10-25 10:39:01 -0700402
xunchange0d991c2019-03-05 14:50:51 -0800403 std::vector<std::string> result;
404 std::vector<std::string> lines = android::base::Split(partition_list_content, "\n");
405 for (const std::string& line : lines) {
406 std::string partition = android::base::Trim(line);
407 // Ignore '#' comment or empty lines.
408 if (android::base::StartsWith(partition, "#") || partition.empty()) {
409 continue;
410 }
411 result.push_back(line);
412 }
Yabin Cuifd99a312016-06-09 14:09:39 -0700413
xunchange0d991c2019-03-05 14:50:51 -0800414 return result;
Yabin Cuifd99a312016-06-09 14:09:39 -0700415}
416
Tao Baoaac9d9f2018-04-29 23:38:59 -0700417// Wipes the current A/B device, with a secure wipe of all the partitions in RECOVERY_WIPE.
Yabin Cuifd99a312016-06-09 14:09:39 -0700418static bool wipe_ab_device(size_t wipe_package_size) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700419 ui->SetBackground(RecoveryUI::ERASING);
420 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Tao Bao862a4c12016-06-02 11:16:50 -0700421
xunchang55e3d222019-03-11 11:28:41 -0700422 auto wipe_package = ReadWipePackage(wipe_package_size);
423 if (!wipe_package) {
424 LOG(ERROR) << "Failed to open wipe package";
xunchange0d991c2019-03-05 14:50:51 -0800425 return false;
426 }
427
xunchang55e3d222019-03-11 11:28:41 -0700428 if (!CheckWipePackage(wipe_package.get())) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700429 LOG(ERROR) << "Failed to verify wipe package";
430 return false;
431 }
xunchange0d991c2019-03-05 14:50:51 -0800432
xunchang55e3d222019-03-11 11:28:41 -0700433 auto partition_list = GetWipePartitionList(wipe_package.get());
xunchange0d991c2019-03-05 14:50:51 -0800434 if (partition_list.empty()) {
435 LOG(ERROR) << "Empty wipe ab partition list";
Tao Baoaac9d9f2018-04-29 23:38:59 -0700436 return false;
437 }
438
xunchange0d991c2019-03-05 14:50:51 -0800439 for (const auto& partition : partition_list) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700440 // Proceed anyway even if it fails to wipe some partition.
441 secure_wipe_partition(partition);
442 }
443 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700444}
445
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700446static void choose_recovery_file(Device* device) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800447 std::vector<std::string> entries;
448 if (has_cache) {
449 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
450 auto add_to_entries = [&](const char* filename) {
451 std::string log_file(filename);
452 if (i > 0) {
453 log_file += "." + std::to_string(i);
Tao Baobef39712015-05-04 18:50:27 -0700454 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800455
Yifan Hongd81b8e32018-12-17 14:29:06 -0800456 if (ensure_path_mounted(log_file) == 0 && access(log_file.c_str(), R_OK) == 0) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800457 entries.push_back(std::move(log_file));
458 }
459 };
460
461 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
462 add_to_entries(LAST_LOG_FILE);
463
464 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
465 add_to_entries(LAST_KMSG_FILE);
466 }
467 } else {
468 // If cache partition is not found, view /tmp/recovery.log instead.
Tao Bao641fa972018-04-25 18:59:40 -0700469 if (access(Paths::Get().temporary_log_file().c_str(), R_OK) == -1) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800470 return;
Tianjie Xua54f75e2016-08-17 12:02:46 -0700471 } else {
Tao Bao641fa972018-04-25 18:59:40 -0700472 entries.push_back(Paths::Get().temporary_log_file());
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700473 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800474 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700475
Tao Bao08fc6be2017-03-07 00:56:27 -0800476 entries.push_back("Back");
Elliott Hughesc0491632015-05-06 12:40:05 -0700477
Tao Bao1fe1afe2018-05-01 15:56:05 -0700478 std::vector<std::string> headers{ "Select file to view" };
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700479
Tao Bao1fe1afe2018-05-01 15:56:05 -0700480 size_t chosen_item = 0;
Tao Bao08fc6be2017-03-07 00:56:27 -0800481 while (true) {
Tao Bao3aec6962018-04-20 09:24:58 -0700482 chosen_item = ui->ShowMenu(
Tao Bao1fe1afe2018-05-01 15:56:05 -0700483 headers, entries, chosen_item, true,
Tao Bao3aec6962018-04-20 09:24:58 -0700484 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Jerry Zhangb76af932018-05-22 12:08:35 -0700485
486 // Handle WaitKey() interrupt.
487 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
488 break;
489 }
Tom Marshalld23b5102017-08-24 13:50:01 +0000490 if (chosen_item == Device::kGoHome || chosen_item == Device::kGoBack ||
491 chosen_item == entries.size() - 1) {
492 break;
493 }
Tao Bao1d156b92018-05-02 12:43:18 -0700494 ui->ShowFile(entries[chosen_item]);
Tao Bao08fc6be2017-03-07 00:56:27 -0800495 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700496}
497
Tao Baodb7e8982017-03-06 23:53:16 -0800498static void run_graphics_test() {
499 // Switch to graphics screen.
500 ui->ShowText(false);
Elliott Hughes498cda62016-04-14 16:49:04 -0700501
Tao Baodb7e8982017-03-06 23:53:16 -0800502 ui->SetProgressType(RecoveryUI::INDETERMINATE);
503 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
504 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700505
Tao Baodb7e8982017-03-06 23:53:16 -0800506 ui->SetBackground(RecoveryUI::ERROR);
507 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700508
Tao Baodb7e8982017-03-06 23:53:16 -0800509 ui->SetBackground(RecoveryUI::NO_COMMAND);
510 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700511
Tao Baodb7e8982017-03-06 23:53:16 -0800512 ui->SetBackground(RecoveryUI::ERASING);
513 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700514
Tao Baodb7e8982017-03-06 23:53:16 -0800515 // Calling SetBackground() after SetStage() to trigger a redraw.
516 ui->SetStage(1, 3);
517 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
518 sleep(1);
519 ui->SetStage(2, 3);
520 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
521 sleep(1);
522 ui->SetStage(3, 3);
523 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
524 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700525
Tao Baodb7e8982017-03-06 23:53:16 -0800526 ui->SetStage(-1, -1);
527 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Elliott Hughes498cda62016-04-14 16:49:04 -0700528
Tao Baodb7e8982017-03-06 23:53:16 -0800529 ui->SetProgressType(RecoveryUI::DETERMINATE);
530 ui->ShowProgress(1.0, 10.0);
531 float fraction = 0.0;
532 for (size_t i = 0; i < 100; ++i) {
533 fraction += .01;
534 ui->SetProgress(fraction);
535 usleep(100000);
536 }
537
538 ui->ShowText(true);
Elliott Hughes498cda62016-04-14 16:49:04 -0700539}
540
Tao Bao50dd5322017-03-07 14:57:04 -0800541// Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
542// which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
543static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
544 for (;;) {
Tao Bao551d2c32018-05-09 20:53:13 -0700545 finish_recovery();
Tao Bao50dd5322017-03-07 14:57:04 -0800546 switch (status) {
547 case INSTALL_SUCCESS:
548 case INSTALL_NONE:
549 ui->SetBackground(RecoveryUI::NO_COMMAND);
550 break;
Doug Zongker6c8553d2012-09-24 10:40:47 -0700551
Tao Bao50dd5322017-03-07 14:57:04 -0800552 case INSTALL_ERROR:
553 case INSTALL_CORRUPT:
554 ui->SetBackground(RecoveryUI::ERROR);
555 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800556 }
Tao Bao50dd5322017-03-07 14:57:04 -0800557 ui->SetProgressType(RecoveryUI::EMPTY);
558
Tom Marshall645801f2020-03-29 14:36:57 +0200559change_menu:
Tao Bao1fe1afe2018-05-01 15:56:05 -0700560 size_t chosen_item = ui->ShowMenu(
Tom Marshall645801f2020-03-29 14:36:57 +0200561 device->GetMenuHeaders(), device->GetMenuItems(), 0, false,
Tao Bao3aec6962018-04-20 09:24:58 -0700562 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Jerry Zhangb76af932018-05-22 12:08:35 -0700563 // Handle Interrupt key
564 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
565 return Device::KEY_INTERRUPTED;
566 }
Tom Marshall645801f2020-03-29 14:36:57 +0200567
Tom Marshalld23b5102017-08-24 13:50:01 +0000568 if (chosen_item == Device::kGoBack || chosen_item == Device::kGoHome) {
Tom Marshall645801f2020-03-29 14:36:57 +0200569 device->GoHome();
570 goto change_menu;
Tom Marshalld23b5102017-08-24 13:50:01 +0000571 }
572
Tao Bao50dd5322017-03-07 14:57:04 -0800573 // Device-specific code may take some action here. It may return one of the core actions
574 // handled in the switch statement below.
Jerry Zhangb76af932018-05-22 12:08:35 -0700575 Device::BuiltinAction chosen_action =
576 (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::TIMED_OUT))
577 ? Device::REBOOT
578 : device->InvokeMenuItem(chosen_item);
Tao Bao50dd5322017-03-07 14:57:04 -0800579
Tao Bao50dd5322017-03-07 14:57:04 -0800580 switch (chosen_action) {
Tom Marshall645801f2020-03-29 14:36:57 +0200581 case Device::MENU_BASE:
Tom Marshall645801f2020-03-29 14:36:57 +0200582 case Device::MENU_WIPE:
583 case Device::MENU_ADVANCED:
584 goto change_menu;
585
Tao Bao50dd5322017-03-07 14:57:04 -0800586 case Device::NO_ACTION:
587 break;
588
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700589 case Device::ENTER_FASTBOOT:
590 case Device::ENTER_RECOVERY:
Tao Bao75321ad2019-04-23 11:46:25 -0700591 case Device::REBOOT:
592 case Device::REBOOT_BOOTLOADER:
593 case Device::REBOOT_FASTBOOT:
594 case Device::REBOOT_RECOVERY:
595 case Device::REBOOT_RESCUE:
596 case Device::SHUTDOWN:
Tao Bao50dd5322017-03-07 14:57:04 -0800597 return chosen_action;
598
599 case Device::WIPE_DATA:
xunchang388d2532019-04-12 16:22:15 -0700600 save_current_log = true;
Tao Bao50dd5322017-03-07 14:57:04 -0800601 if (ui->IsTextVisible()) {
602 if (ask_to_wipe_data(device)) {
xunchang388d2532019-04-12 16:22:15 -0700603 WipeData(device, false);
Tao Bao50dd5322017-03-07 14:57:04 -0800604 }
605 } else {
xunchang388d2532019-04-12 16:22:15 -0700606 WipeData(device, false);
Tao Bao50dd5322017-03-07 14:57:04 -0800607 return Device::NO_ACTION;
608 }
609 break;
610
xunchang388d2532019-04-12 16:22:15 -0700611 case Device::WIPE_CACHE: {
612 save_current_log = true;
613 std::function<bool()> confirm_func = [&device]() {
614 return yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!");
615 };
616 WipeCache(ui, ui->IsTextVisible() ? confirm_func : nullptr);
Tao Bao50dd5322017-03-07 14:57:04 -0800617 if (!ui->IsTextVisible()) return Device::NO_ACTION;
618 break;
xunchang388d2532019-04-12 16:22:15 -0700619 }
Tao Bao7b9b7db2019-04-19 15:22:15 -0700620
Michael Bestasc209c072019-09-27 19:52:13 +0300621 case Device::WIPE_SYSTEM: {
622 save_current_log = true;
623 std::function<bool()> confirm_func = [&device]() {
624 return yes_no(device, "Wipe system?", " THIS CAN NOT BE UNDONE!");
625 };
626 WipeSystem(ui, ui->IsTextVisible() ? confirm_func : nullptr);
627 if (!ui->IsTextVisible()) return Device::NO_ACTION;
628 break;
629 }
630
Tom Marshallbead2612019-01-04 14:37:31 -0800631 case Device::APPLY_UPDATE:
Tao Bao378bfbf2019-04-16 14:22:25 -0700632 case Device::ENTER_RESCUE: {
xunchang388d2532019-04-12 16:22:15 -0700633 save_current_log = true;
Tao Bao378bfbf2019-04-16 14:22:25 -0700634
Tao Bao7b9b7db2019-04-19 15:22:15 -0700635 Device::BuiltinAction reboot_action;
Tao Bao378bfbf2019-04-16 14:22:25 -0700636 if (chosen_action == Device::ENTER_RESCUE) {
637 // Switch to graphics screen.
638 ui->ShowText(false);
xunchang5a1916b2019-04-22 12:18:14 -0700639 status = ApplyFromAdb(device, true /* rescue_mode */, &reboot_action);
Tom Marshallbead2612019-01-04 14:37:31 -0800640 } else if (chosen_action == Device::APPLY_UPDATE) {
641 status = apply_update_menu(device, ui, &reboot_action);
Tao Bao50dd5322017-03-07 14:57:04 -0800642 }
xunchang3cc23d52019-03-18 15:03:33 -0700643
Tao Bao7b9b7db2019-04-19 15:22:15 -0700644 if (status == INSTALL_REBOOT) {
645 return reboot_action;
646 }
647
Tom Marshallbead2612019-01-04 14:37:31 -0800648 ui->Print("\nInstall completed with status %d.\n", status);
xunchang3cc23d52019-03-18 15:03:33 -0700649 if (status != INSTALL_SUCCESS) {
650 ui->SetBackground(RecoveryUI::ERROR);
651 ui->Print("Installation aborted.\n");
xunchang388d2532019-04-12 16:22:15 -0700652 copy_logs(save_current_log, has_cache, sehandle);
xunchang3cc23d52019-03-18 15:03:33 -0700653 } else if (!ui->IsTextVisible()) {
654 return Device::NO_ACTION; // reboot if logs aren't visible
xunchang3cc23d52019-03-18 15:03:33 -0700655 }
Tao Bao50dd5322017-03-07 14:57:04 -0800656 break;
xunchang3cc23d52019-03-18 15:03:33 -0700657 }
Tao Bao50dd5322017-03-07 14:57:04 -0800658
659 case Device::VIEW_RECOVERY_LOGS:
660 choose_recovery_file(device);
661 break;
662
663 case Device::RUN_GRAPHICS_TEST:
664 run_graphics_test();
665 break;
666
Tianjie Xu29d55752017-09-20 17:53:46 -0700667 case Device::RUN_LOCALE_TEST: {
668 ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
Tao Bao39c49182018-05-07 22:50:33 -0700669 screen_ui->CheckBackgroundTextImages();
Tianjie Xu29d55752017-09-20 17:53:46 -0700670 break;
671 }
Tao Bao50dd5322017-03-07 14:57:04 -0800672 case Device::MOUNT_SYSTEM:
Jiyong Park8b7af4c2018-06-01 11:58:54 +0900673 // the system partition is mounted at /mnt/system
Yifan Hongd81b8e32018-12-17 14:29:06 -0800674 if (ensure_path_mounted_at(get_system_root(), "/mnt/system") != -1) {
Yifan Hong49327802018-11-26 14:59:09 -0800675 ui->Print("Mounted /system.\n");
Tao Bao50dd5322017-03-07 14:57:04 -0800676 }
677 break;
Jerry Zhangb76af932018-05-22 12:08:35 -0700678
679 case Device::KEY_INTERRUPTED:
680 return Device::KEY_INTERRUPTED;
Tao Bao50dd5322017-03-07 14:57:04 -0800681 }
682 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800683}
684
Tao Bao99f0d9e2016-10-13 12:46:38 -0700685static void print_property(const char* key, const char* name, void* /* cookie */) {
686 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800687}
688
Tao Bao6d90a9d2018-04-26 10:40:36 -0700689static bool is_battery_ok(int* required_battery_level) {
Yifan Honge8e4c402017-11-08 14:56:03 -0800690 using android::hardware::health::V1_0::BatteryStatus;
Yifan Hong056538c2018-07-11 17:04:12 -0700691 using android::hardware::health::V2_0::get_health_service;
692 using android::hardware::health::V2_0::IHealth;
Yifan Honge8e4c402017-11-08 14:56:03 -0800693 using android::hardware::health::V2_0::Result;
694 using android::hardware::health::V2_0::toString;
Yabin Cui99281df2016-02-17 12:21:52 -0800695
Yifan Hong056538c2018-07-11 17:04:12 -0700696 android::sp<IHealth> health = get_health_service();
Yifan Honge8e4c402017-11-08 14:56:03 -0800697
Tao Bao6d90a9d2018-04-26 10:40:36 -0700698 static constexpr int BATTERY_READ_TIMEOUT_IN_SEC = 10;
Yifan Honge8e4c402017-11-08 14:56:03 -0800699 int wait_second = 0;
700 while (true) {
701 auto charge_status = BatteryStatus::UNKNOWN;
Yifan Hong056538c2018-07-11 17:04:12 -0700702
703 if (health == nullptr) {
704 LOG(WARNING) << "no health implementation is found, assuming defaults";
705 } else {
706 health
707 ->getChargeStatus([&charge_status](auto res, auto out_status) {
708 if (res == Result::SUCCESS) {
709 charge_status = out_status;
710 }
711 })
712 .isOk(); // should not have transport error
713 }
Yifan Honge8e4c402017-11-08 14:56:03 -0800714
715 // Treat unknown status as charged.
716 bool charged = (charge_status != BatteryStatus::DISCHARGING &&
717 charge_status != BatteryStatus::NOT_CHARGING);
718
719 Result res = Result::UNKNOWN;
720 int32_t capacity = INT32_MIN;
Yifan Hong056538c2018-07-11 17:04:12 -0700721 if (health != nullptr) {
722 health
723 ->getCapacity([&res, &capacity](auto out_res, auto out_capacity) {
724 res = out_res;
725 capacity = out_capacity;
726 })
727 .isOk(); // should not have transport error
728 }
Yifan Honge8e4c402017-11-08 14:56:03 -0800729
Yifan Hong056538c2018-07-11 17:04:12 -0700730 LOG(INFO) << "charge_status " << toString(charge_status) << ", charged " << charged
731 << ", status " << toString(res) << ", capacity " << capacity;
Yifan Honge8e4c402017-11-08 14:56:03 -0800732 // At startup, the battery drivers in devices like N5X/N6P take some time to load
733 // the battery profile. Before the load finishes, it reports value 50 as a fake
734 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
735 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
736 if (res == Result::SUCCESS && capacity == 50) {
737 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
738 sleep(1);
739 wait_second++;
740 continue;
741 }
742 }
743 // If we can't read battery percentage, it may be a device without battery. In this
744 // situation, use 100 as a fake battery percentage.
745 if (res != Result::SUCCESS) {
746 capacity = 100;
747 }
Tao Bao6d90a9d2018-04-26 10:40:36 -0700748
749 // GmsCore enters recovery mode to install package when having enough battery percentage.
750 // Normally, the threshold is 40% without charger and 20% with charger. So we should check
751 // battery with a slightly lower limitation.
752 static constexpr int BATTERY_OK_PERCENTAGE = 20;
753 static constexpr int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
754 *required_battery_level = charged ? BATTERY_WITH_CHARGER_OK_PERCENTAGE : BATTERY_OK_PERCENTAGE;
755 return capacity >= *required_battery_level;
756 }
Yabin Cui99281df2016-02-17 12:21:52 -0800757}
758
Tianjie Xu99b73be2017-11-28 17:23:06 -0800759// Set the retry count to |retry_count| in BCB.
Tianjie Xu72449c92017-05-16 18:07:31 -0700760static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
761 std::vector<std::string> options;
762 for (const auto& arg : args) {
763 if (!android::base::StartsWith(arg, "--retry_count")) {
764 options.push_back(arg);
Tianjie Xu3c62b672016-02-05 18:25:58 -0800765 }
Tianjie Xu72449c92017-05-16 18:07:31 -0700766 }
Tianjie Xu3c62b672016-02-05 18:25:58 -0800767
Tianjie Xu99b73be2017-11-28 17:23:06 -0800768 // Update the retry counter in BCB.
769 options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
Tianjie Xu72449c92017-05-16 18:07:31 -0700770 std::string err;
771 if (!update_bootloader_message(options, &err)) {
772 LOG(ERROR) << err;
773 }
Tianjie Xu3c62b672016-02-05 18:25:58 -0800774}
775
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700776static bool bootreason_in_blacklist() {
Tao Baoefc35592017-01-08 22:45:47 -0800777 std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
778 if (!bootreason.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700779 // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
780 static const std::vector<std::string> kBootreasonBlacklist{
781 "kernel_panic",
782 "Panic",
783 };
784 for (const auto& str : kBootreasonBlacklist) {
785 if (android::base::EqualsIgnoreCase(str, bootreason)) return true;
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700786 }
Tao Baoefc35592017-01-08 22:45:47 -0800787 }
788 return false;
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700789}
790
Tao Bao641fa972018-04-25 18:59:40 -0700791static void log_failure_code(ErrorCode code, const std::string& update_package) {
792 std::vector<std::string> log_buffer = {
793 update_package,
794 "0", // install result
795 "error: " + std::to_string(code),
796 };
797 std::string log_content = android::base::Join(log_buffer, "\n");
798 const std::string& install_file = Paths::Get().temporary_install_file();
799 if (!android::base::WriteStringToFile(log_content, install_file)) {
800 PLOG(ERROR) << "Failed to write " << install_file;
801 }
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700802
Tao Bao641fa972018-04-25 18:59:40 -0700803 // Also write the info into last_log.
804 LOG(INFO) << log_content;
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700805}
806
Jerry Zhang6a648042018-05-04 11:24:10 -0700807Device::BuiltinAction start_recovery(Device* device, const std::vector<std::string>& args) {
Tao Baof9f17342018-04-27 10:44:04 -0700808 static constexpr struct option OPTIONS[] = {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700809 { "fastboot", no_argument, nullptr, 0 },
David Andersonedee8362018-05-16 13:43:22 -0700810 { "fsck_unshare_blocks", no_argument, nullptr, 0 },
Tao Baof9f17342018-04-27 10:44:04 -0700811 { "just_exit", no_argument, nullptr, 'x' },
812 { "locale", required_argument, nullptr, 0 },
813 { "prompt_and_wipe_data", no_argument, nullptr, 0 },
814 { "reason", required_argument, nullptr, 0 },
Tao Bao75321ad2019-04-23 11:46:25 -0700815 { "rescue", no_argument, nullptr, 0 },
Tao Baof9f17342018-04-27 10:44:04 -0700816 { "retry_count", required_argument, nullptr, 0 },
817 { "security", no_argument, nullptr, 0 },
818 { "show_text", no_argument, nullptr, 't' },
819 { "shutdown_after", no_argument, nullptr, 0 },
820 { "sideload", no_argument, nullptr, 0 },
821 { "sideload_auto_reboot", no_argument, nullptr, 0 },
822 { "update_package", required_argument, nullptr, 0 },
823 { "wipe_ab", no_argument, nullptr, 0 },
824 { "wipe_cache", no_argument, nullptr, 0 },
825 { "wipe_data", no_argument, nullptr, 0 },
826 { "wipe_package_size", required_argument, nullptr, 0 },
827 { nullptr, 0, nullptr, 0 },
828 };
829
Tianjie Xu99b73be2017-11-28 17:23:06 -0800830 const char* update_package = nullptr;
831 bool should_wipe_data = false;
832 bool should_prompt_and_wipe_data = false;
833 bool should_wipe_cache = false;
834 bool should_wipe_ab = false;
835 size_t wipe_package_size = 0;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800836 bool sideload = false;
837 bool sideload_auto_reboot = false;
Tao Bao75321ad2019-04-23 11:46:25 -0700838 bool rescue = false;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800839 bool just_exit = false;
840 bool shutdown_after = false;
David Andersonedee8362018-05-16 13:43:22 -0700841 bool fsck_unshare_blocks = false;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800842 int retry_count = 0;
843 bool security_update = false;
Jerry Zhang2dea53e2018-05-02 17:15:03 -0700844 std::string locale;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800845
Tao Bao1700cc42018-07-16 22:09:59 -0700846 auto args_to_parse = StringVectorToNullTerminatedArray(args);
847
Tianjie Xu99b73be2017-11-28 17:23:06 -0800848 int arg;
849 int option_index;
Tao Bao1700cc42018-07-16 22:09:59 -0700850 // Parse everything before the last element (which must be a nullptr). getopt_long(3) expects a
851 // null-terminated char* array, but without counting null as an arg (i.e. argv[argc] should be
852 // nullptr).
853 while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
Tianjie Xu99b73be2017-11-28 17:23:06 -0800854 &option_index)) != -1) {
855 switch (arg) {
Tianjie Xu99b73be2017-11-28 17:23:06 -0800856 case 't':
Jerry Zhang6a648042018-05-04 11:24:10 -0700857 // Handled in recovery_main.cpp
Tianjie Xu99b73be2017-11-28 17:23:06 -0800858 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800859 case 'x':
860 just_exit = true;
861 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800862 case 0: {
863 std::string option = OPTIONS[option_index].name;
David Andersonedee8362018-05-16 13:43:22 -0700864 if (option == "fsck_unshare_blocks") {
865 fsck_unshare_blocks = true;
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700866 } else if (option == "locale" || option == "fastboot") {
Jerry Zhang6a648042018-05-04 11:24:10 -0700867 // Handled in recovery_main.cpp
Tianjie Xu99b73be2017-11-28 17:23:06 -0800868 } else if (option == "prompt_and_wipe_data") {
869 should_prompt_and_wipe_data = true;
Tao Baof9f17342018-04-27 10:44:04 -0700870 } else if (option == "reason") {
871 reason = optarg;
Tao Bao75321ad2019-04-23 11:46:25 -0700872 } else if (option == "rescue") {
873 rescue = true;
Tao Baof9f17342018-04-27 10:44:04 -0700874 } else if (option == "retry_count") {
875 android::base::ParseInt(optarg, &retry_count, 0);
876 } else if (option == "security") {
877 security_update = true;
878 } else if (option == "sideload") {
879 sideload = true;
880 } else if (option == "sideload_auto_reboot") {
881 sideload = true;
882 sideload_auto_reboot = true;
883 } else if (option == "shutdown_after") {
884 shutdown_after = true;
885 } else if (option == "update_package") {
886 update_package = optarg;
887 } else if (option == "wipe_ab") {
888 should_wipe_ab = true;
889 } else if (option == "wipe_cache") {
890 should_wipe_cache = true;
891 } else if (option == "wipe_data") {
892 should_wipe_data = true;
893 } else if (option == "wipe_package_size") {
894 android::base::ParseUint(optarg, &wipe_package_size);
Tianjie Xu99b73be2017-11-28 17:23:06 -0800895 }
896 break;
897 }
898 case '?':
899 LOG(ERROR) << "Invalid command argument";
900 continue;
Doug Zongker9270a202012-01-09 15:16:13 -0800901 }
Tianjie Xu99b73be2017-11-28 17:23:06 -0800902 }
Jerry Zhang49fd5d22018-05-17 12:54:41 -0700903 optind = 1;
Doug Zongker9270a202012-01-09 15:16:13 -0800904
Tianjie Xu99b73be2017-11-28 17:23:06 -0800905 printf("stage is [%s]\n", stage.c_str());
906 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -0700907
Tom Marshallbead2612019-01-04 14:37:31 -0800908 VolumeClient* volclient = new VolumeClient(device);
909 VolumeManager* volmgr = VolumeManager::Instance();
910 if (!volmgr->start(volclient, sehandle)) {
911 printf("Failed to start volume manager\n");
912 }
913
Tianjie Xu99b73be2017-11-28 17:23:06 -0800914 // Set background string to "installing security update" for security update,
915 // otherwise set it to "installing system update".
916 ui->SetSystemUpdateText(security_update);
917
918 int st_cur, st_max;
919 if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
920 ui->SetStage(st_cur, st_max);
921 }
922
Jerry Zhang0e577ee2018-05-07 11:21:10 -0700923 std::vector<std::string> title_lines =
924 android::base::Split(android::base::GetProperty("ro.bootimage.build.fingerprint", ""), ":");
Nolen Johnsonb146fe92020-02-12 00:03:01 +0000925 title_lines.insert(std::begin(title_lines), "Lineage Recovery");
Jerry Zhang0e577ee2018-05-07 11:21:10 -0700926 ui->SetTitle(title_lines);
927
Jerry Zhangb76af932018-05-22 12:08:35 -0700928 ui->ResetKeyInterruptStatus();
Tianjie Xu99b73be2017-11-28 17:23:06 -0800929 device->StartRecovery();
930
931 printf("Command:");
932 for (const auto& arg : args) {
933 printf(" \"%s\"", arg.c_str());
934 }
935 printf("\n\n");
936
937 property_list(print_property, nullptr);
938 printf("\n");
939
Tianjie Xu99b73be2017-11-28 17:23:06 -0800940 int status = INSTALL_SUCCESS;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700941 // next_action indicates the next target to reboot into upon finishing the install. It could be
942 // overridden to a different reboot target per user request.
943 Device::BuiltinAction next_action = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800944
945 if (update_package != nullptr) {
946 // It's not entirely true that we will modify the flash. But we want
947 // to log the update attempt since update_package is non-NULL.
xunchang388d2532019-04-12 16:22:15 -0700948 save_current_log = true;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800949
Tao Bao6d90a9d2018-04-26 10:40:36 -0700950 int required_battery_level;
951 if (retry_count == 0 && !is_battery_ok(&required_battery_level)) {
952 ui->Print("battery capacity is not enough for installing package: %d%% needed\n",
953 required_battery_level);
Tianjie Xu99b73be2017-11-28 17:23:06 -0800954 // Log the error code to last_install when installation skips due to
955 // low battery.
956 log_failure_code(kLowBattery, update_package);
957 status = INSTALL_SKIPPED;
Tianjie Xua6f49bd2018-03-26 14:32:11 -0700958 } else if (retry_count == 0 && bootreason_in_blacklist()) {
Tianjie Xu99b73be2017-11-28 17:23:06 -0800959 // Skip update-on-reboot when bootreason is kernel_panic or similar
960 ui->Print("bootreason is in the blacklist; skip OTA installation\n");
961 log_failure_code(kBootreasonInBlacklist, update_package);
962 status = INSTALL_SKIPPED;
Dmitri Plotnikov8706a982017-04-18 08:28:26 -0700963 } else {
Tianjie Xu99b73be2017-11-28 17:23:06 -0800964 // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
965 // identify the interrupted update due to unexpected reboots.
966 if (retry_count == 0) {
967 set_retry_bootloader_message(retry_count + 1, args);
Tao Bao7022f332017-07-25 09:52:36 -0700968 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800969
Tom Marshall03354052018-06-21 00:57:24 +0200970 status = install_package(update_package, should_wipe_cache, true, retry_count,
Alessandro Astone8b726282020-03-17 23:06:52 +0100971 true /* verify */, false /* allow_ab_downgrade */, ui);
Tianjie Xu99b73be2017-11-28 17:23:06 -0800972 if (status != INSTALL_SUCCESS) {
973 ui->Print("Installation aborted.\n");
Tao Baoaac9d9f2018-04-29 23:38:59 -0700974
975 // When I/O error or bspatch/imgpatch error happens, reboot and retry installation
976 // RETRY_LIMIT times before we abandon this OTA update.
977 static constexpr int RETRY_LIMIT = 4;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800978 if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
xunchang388d2532019-04-12 16:22:15 -0700979 copy_logs(save_current_log, has_cache, sehandle);
Tianjie Xu99b73be2017-11-28 17:23:06 -0800980 retry_count += 1;
981 set_retry_bootloader_message(retry_count, args);
982 // Print retry count on screen.
983 ui->Print("Retry attempt %d\n", retry_count);
984
985 // Reboot and retry the update
986 if (!reboot("reboot,recovery")) {
987 ui->Print("Reboot failed\n");
988 } else {
989 while (true) {
990 pause();
991 }
992 }
Tianjie Xud9d16292017-04-20 18:08:21 -0700993 }
Tianjie Xu99b73be2017-11-28 17:23:06 -0800994 // If this is an eng or userdebug build, then automatically
995 // turn the text display on if the script fails so the error
996 // message is visible.
997 if (is_ro_debuggable()) {
998 ui->ShowText(true);
Tao Baoc679f932015-03-30 09:43:49 -0700999 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001000 }
Doug Zongker8674a722010-09-15 11:08:23 -07001001 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001002 } else if (should_wipe_data) {
xunchang388d2532019-04-12 16:22:15 -07001003 save_current_log = true;
1004 bool convert_fbe = reason && strcmp(reason, "convert_fbe") == 0;
1005 if (!WipeData(device, convert_fbe)) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001006 status = INSTALL_ERROR;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001007 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001008 } else if (should_prompt_and_wipe_data) {
Tao Baoa5bbcb92018-09-17 14:32:47 -07001009 // Trigger the logging to capture the cause, even if user chooses to not wipe data.
xunchang388d2532019-04-12 16:22:15 -07001010 save_current_log = true;
Tao Baoa5bbcb92018-09-17 14:32:47 -07001011
Tianjie Xu99b73be2017-11-28 17:23:06 -08001012 ui->ShowText(true);
1013 ui->SetBackground(RecoveryUI::ERROR);
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -07001014 status = prompt_and_wipe_data(device);
1015 if (status != INSTALL_KEY_INTERRUPTED) {
1016 ui->ShowText(false);
Tao Bao75238632015-05-27 14:46:17 -07001017 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001018 } else if (should_wipe_cache) {
xunchang388d2532019-04-12 16:22:15 -07001019 save_current_log = true;
1020 if (!WipeCache(ui, nullptr)) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001021 status = INSTALL_ERROR;
1022 }
1023 } else if (should_wipe_ab) {
1024 if (!wipe_ab_device(wipe_package_size)) {
1025 status = INSTALL_ERROR;
1026 }
1027 } else if (sideload) {
Tao Bao7b9b7db2019-04-19 15:22:15 -07001028 // 'adb reboot sideload' acts the same as user presses key combinations to enter the sideload
1029 // mode. When 'sideload-auto-reboot' is used, text display will NOT be turned on by default. And
1030 // it will reboot after sideload finishes even if there are errors. This is to enable automated
Tianjie Xu99b73be2017-11-28 17:23:06 -08001031 // testing.
xunchang388d2532019-04-12 16:22:15 -07001032 save_current_log = true;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001033 if (!sideload_auto_reboot) {
1034 ui->ShowText(true);
1035 }
Alessandro Astone4e1e8662020-03-17 22:26:22 +01001036 status = ApplyFromAdb(device, false /* rescue_mode */, &next_action);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001037 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1038 if (sideload_auto_reboot) {
Tao Bao7b9b7db2019-04-19 15:22:15 -07001039 status = INSTALL_REBOOT;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001040 ui->Print("Rebooting automatically.\n");
1041 }
Tao Bao75321ad2019-04-23 11:46:25 -07001042 } else if (rescue) {
1043 save_current_log = true;
xunchang5a1916b2019-04-22 12:18:14 -07001044 status = ApplyFromAdb(device, true /* rescue_mode */, &next_action);
Tao Bao75321ad2019-04-23 11:46:25 -07001045 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
David Andersonedee8362018-05-16 13:43:22 -07001046 } else if (fsck_unshare_blocks) {
1047 if (!do_fsck_unshare_blocks()) {
1048 status = INSTALL_ERROR;
1049 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001050 } else if (!just_exit) {
Pat Erley85da9942016-01-05 16:50:02 -08001051 // Always show menu if no command is specified.
1052 // Note that this should be called before setting the background to avoid
Tianjie Xu99b73be2017-11-28 17:23:06 -08001053 // flickering the background image.
Pat Erley85da9942016-01-05 16:50:02 -08001054 ui->ShowText(true);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001055 status = INSTALL_NONE; // No command specified
1056 ui->SetBackground(RecoveryUI::NO_COMMAND);
1057 }
1058
1059 if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
1060 ui->SetBackground(RecoveryUI::ERROR);
1061 if (!ui->IsTextVisible()) {
1062 sleep(5);
1063 }
1064 }
1065
Tao Bao7b9b7db2019-04-19 15:22:15 -07001066 // Determine the next action.
1067 // - If the state is INSTALL_REBOOT, device will reboot into the target as specified in
1068 // `next_action`.
1069 // - If the recovery menu is visible, prompt and wait for commands.
1070 // - If the state is INSTALL_NONE, wait for commands (e.g. in user build, one manually boots
1071 // into recovery to sideload a package or to wipe the device).
1072 // - In all other cases, reboot the device. Therefore, normal users will observe the device
1073 // rebooting a) immediately upon successful finish (INSTALL_SUCCESS); or b) an "error" screen
1074 // for 5s followed by an automatic reboot.
1075 if (status != INSTALL_REBOOT) {
1076 if (status == INSTALL_NONE || ui->IsTextVisible()) {
1077 Device::BuiltinAction temp = prompt_and_wait(device, status);
1078 if (temp != Device::NO_ACTION) {
1079 next_action = temp;
1080 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001081 }
1082 }
1083
1084 // Save logs and clean up before rebooting or shutting down.
Tao Bao551d2c32018-05-09 20:53:13 -07001085 finish_recovery();
Tianjie Xu99b73be2017-11-28 17:23:06 -08001086
Tom Marshallbead2612019-01-04 14:37:31 -08001087 volmgr->unmountAll();
1088 volmgr->stop();
1089 delete volclient;
1090
1091 sync();
1092
Tao Bao7b9b7db2019-04-19 15:22:15 -07001093 return next_action;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001094}