blob: 034918498067f0a8d41930ee659b3a3acc77285b [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>
Doug Zongker23ceeea2010-07-08 17:27:55 -070030#include <sys/stat.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080031#include <sys/types.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080032#include <unistd.h>
33
Tao Baoc4a18ef2017-02-10 00:13:30 -080034#include <algorithm>
Tao Bao3aec6962018-04-20 09:24:58 -070035#include <functional>
Tao Baoc4a18ef2017-02-10 00:13:30 -080036#include <memory>
Tao Bao862a4c12016-06-02 11:16:50 -070037#include <string>
38#include <vector>
Tao Bao04ca4262015-09-10 15:32:24 -070039
Elliott Hughes4b166f02015-12-04 15:30:20 -080040#include <android-base/file.h>
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -070041#include <android-base/logging.h>
Tianjie Xu3c62b672016-02-05 18:25:58 -080042#include <android-base/parseint.h>
Elliott Hughescb220402016-09-23 15:30:55 -070043#include <android-base/properties.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080044#include <android-base/stringprintf.h>
Tao Bao862a4c12016-06-02 11:16:50 -070045#include <android-base/strings.h>
46#include <android-base/unique_fd.h>
Yabin Cui8b309f62016-06-24 18:22:02 -070047#include <bootloader_message/bootloader_message.h>
Elliott Hughescb220402016-09-23 15:30:55 -070048#include <cutils/properties.h> /* for property_list */
Yifan Hong056538c2018-07-11 17:04:12 -070049#include <healthhalutils/HealthHalUtils.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"
Jerry Zhangcadf4ed2018-05-02 16:56:00 -070058#include "logging.h"
Tao Bao17054c02018-05-03 22:41:23 -070059#include "otautil/dirutil.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070060#include "otautil/error_code.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"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080066
Tao Baoaac9d9f2018-04-29 23:38:59 -070067static constexpr const char* CACHE_LOG_DIR = "/cache/recovery";
68static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
Tao Baoaac9d9f2018-04-29 23:38:59 -070069static constexpr const char* LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
70static constexpr const char* LAST_LOG_FILE = "/cache/recovery/last_log";
71static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
Tianjie Xu06e57ac2016-07-11 14:04:08 -070072
Tao Baoaac9d9f2018-04-29 23:38:59 -070073static constexpr const char* CACHE_ROOT = "/cache";
74static constexpr const char* DATA_ROOT = "/data";
75static constexpr const char* METADATA_ROOT = "/metadata";
Nick Kralevicha9ad0322014-10-22 18:38:48 -070076
Tao Baobd0ddcd2017-05-04 13:03:18 -070077// We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
78// into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
79static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
80
xunchang24788852019-03-22 16:08:52 -070081static bool modified_flash = false;
Tao Baoa8d72bc2016-12-25 18:46:50 -080082std::string stage;
Tao Baoac9d94d2016-11-03 11:37:15 -070083const char* reason = nullptr;
Tao Baoac9d94d2016-11-03 11:37:15 -070084
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080085/*
86 * The recovery tool communicates with the main system through /cache files.
87 * /cache/recovery/command - INPUT - command line for tool, one arg per line
88 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080089 *
90 * The arguments which may be supplied in the recovery.command file:
Doug Zongkerd4208f92010-09-20 12:16:13 -070091 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080092 * --wipe_data - erase user data (and cache), then reboot
Tao Baof9f17342018-04-27 10:44:04 -070093 * --prompt_and_wipe_data - prompt the user that data is corrupt, with their consent erase user
94 * data (and cache), then reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080095 * --wipe_cache - wipe cache (but not user data), then reboot
Tao Baof9f17342018-04-27 10:44:04 -070096 * --show_text - show the recovery text menu, used by some bootloader (e.g. http://b/36872519).
Oscar Montemayor05231562009-11-30 08:40:57 -080097 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -070098 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080099 *
100 * After completing, we remove /cache/recovery/command and reboot.
101 * Arguments may also be supplied in the bootloader control block (BCB).
102 * These important scenarios must be safely restartable at any point:
103 *
104 * FACTORY RESET
105 * 1. user selects "factory reset"
106 * 2. main system writes "--wipe_data" to /cache/recovery/command
107 * 3. main system reboots into recovery
108 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
109 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700110 * 5. erase_volume() reformats /data
111 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800112 * 7. finish_recovery() erases BCB
113 * -- after this, rebooting will restart the main system --
114 * 8. main() calls reboot() to boot main system
115 *
116 * OTA INSTALL
117 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700118 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800119 * 3. main system reboots into recovery
120 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
121 * -- after this, rebooting will attempt to reinstall the update --
122 * 5. install_package() attempts to install the update
123 * NOTE: the package install must itself be restartable from any point
124 * 6. finish_recovery() erases BCB
125 * -- after this, rebooting will (try to) restart the main system --
126 * 7. ** if install failed **
127 * 7a. prompt_and_wait() shows an error icon and waits for the user
Tao Baoc0336392016-12-13 22:29:49 -0800128 * 7b. the user reboots (pulling the battery, etc) into the main system
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800129 */
130
Elliott Hughesf14af802015-02-10 14:46:14 -0800131bool is_ro_debuggable() {
Elliott Hughescb220402016-09-23 15:30:55 -0700132 return android::base::GetBoolProperty("ro.debuggable", false);
Elliott Hughesf14af802015-02-10 14:46:14 -0800133}
134
Tao Baoec579032017-07-21 12:13:15 -0700135// Clear the recovery command and prepare to boot a (hopefully working) system,
Tianjie Xuc14d95d2016-03-24 11:50:34 -0700136// copy our log file to cache as well (for the system to read). This function is
137// idempotent: call it as many times as you like.
Tao Bao551d2c32018-05-09 20:53:13 -0700138static void finish_recovery() {
139 std::string locale = ui->GetLocale();
Tao Baoec579032017-07-21 12:13:15 -0700140 // Save the locale to cache, so if recovery is next started up without a '--locale' argument
141 // (e.g., directly from the bootloader) it will use the last-known locale.
142 if (!locale.empty() && has_cache) {
143 LOG(INFO) << "Saving locale \"" << locale << "\"";
144 if (ensure_path_mounted(LOCALE_FILE) != 0) {
145 LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
146 } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
147 PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
Doug Zongker4f33e552012-08-23 13:16:12 -0700148 }
Tao Baoec579032017-07-21 12:13:15 -0700149 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700150
Jerry Zhangcadf4ed2018-05-02 16:56:00 -0700151 copy_logs(modified_flash, has_cache);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800152
Tao Baoec579032017-07-21 12:13:15 -0700153 // Reset to normal system boot so recovery won't cycle indefinitely.
154 std::string err;
155 if (!clear_bootloader_message(&err)) {
156 LOG(ERROR) << "Failed to clear BCB message: " << err;
157 }
158
159 // Remove the command file, so recovery won't repeat indefinitely.
160 if (has_cache) {
161 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
162 LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
Yabin Cui8b309f62016-06-24 18:22:02 -0700163 }
Tao Baoec579032017-07-21 12:13:15 -0700164 ensure_path_unmounted(CACHE_ROOT);
165 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800166
Tao Baoec579032017-07-21 12:13:15 -0700167 sync(); // For good measure.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800168}
169
Tao Bao3f5a3822016-12-13 11:14:37 -0800170struct saved_log_file {
171 std::string name;
172 struct stat sb;
173 std::string data;
174};
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700175
Elliott Hughes945548e2015-06-05 17:59:56 -0700176static bool erase_volume(const char* volume) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800177 bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
178 bool is_data = (strcmp(volume, DATA_ROOT) == 0);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700179
Tao Bao3f5a3822016-12-13 11:14:37 -0800180 ui->SetBackground(RecoveryUI::ERASING);
181 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700182
Tao Bao3f5a3822016-12-13 11:14:37 -0800183 std::vector<saved_log_file> log_files;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700184
Tao Bao3f5a3822016-12-13 11:14:37 -0800185 if (is_cache) {
186 // If we're reformatting /cache, we load any past logs
187 // (i.e. "/cache/recovery/last_*") and the current log
188 // ("/cache/recovery/log") into memory, so we can restore them after
189 // the reformat.
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700190
Tao Bao3f5a3822016-12-13 11:14:37 -0800191 ensure_path_mounted(volume);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700192
Tao Bao3f5a3822016-12-13 11:14:37 -0800193 struct dirent* de;
194 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(CACHE_LOG_DIR), closedir);
195 if (d) {
196 while ((de = readdir(d.get())) != nullptr) {
197 if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
198 std::string path = android::base::StringPrintf("%s/%s", CACHE_LOG_DIR, de->d_name);
199
200 struct stat sb;
201 if (stat(path.c_str(), &sb) == 0) {
202 // truncate files to 512kb
203 if (sb.st_size > (1 << 19)) {
204 sb.st_size = 1 << 19;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700205 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800206
207 std::string data(sb.st_size, '\0');
Tianjie Xude6735e2017-07-10 15:13:33 -0700208 FILE* f = fopen(path.c_str(), "rbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800209 fread(&data[0], 1, data.size(), f);
210 fclose(f);
211
212 log_files.emplace_back(saved_log_file{ path, sb, data });
213 }
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700214 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800215 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800216 } else {
Tao Bao3f5a3822016-12-13 11:14:37 -0800217 if (errno != ENOENT) {
218 PLOG(ERROR) << "Failed to opendir " << CACHE_LOG_DIR;
219 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800220 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800221 }
Doug Zongkerd0181b82011-10-19 10:51:12 -0700222
Tao Bao3f5a3822016-12-13 11:14:37 -0800223 ui->Print("Formatting %s...\n", volume);
224
225 ensure_path_unmounted(volume);
226
227 int result;
Tao Bao3f5a3822016-12-13 11:14:37 -0800228 if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700229 static constexpr const char* CONVERT_FBE_DIR = "/tmp/convert_fbe";
230 static constexpr const char* CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
231 // Create convert_fbe breadcrumb file to signal init to convert to file based encryption, not
232 // full disk encryption.
Tao Bao3f5a3822016-12-13 11:14:37 -0800233 if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700234 PLOG(ERROR) << "Failed to mkdir " << CONVERT_FBE_DIR;
235 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800236 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700237 FILE* f = fopen(CONVERT_FBE_FILE, "wbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800238 if (!f) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700239 PLOG(ERROR) << "Failed to convert to file encryption";
240 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800241 }
242 fclose(f);
243 result = format_volume(volume, CONVERT_FBE_DIR);
244 remove(CONVERT_FBE_FILE);
245 rmdir(CONVERT_FBE_DIR);
246 } else {
247 result = format_volume(volume);
248 }
249
250 if (is_cache) {
251 // Re-create the log dir and write back the log entries.
252 if (ensure_path_mounted(CACHE_LOG_DIR) == 0 &&
Tao Baoac3d1ed2017-07-23 00:01:02 -0700253 mkdir_recursively(CACHE_LOG_DIR, 0777, false, sehandle) == 0) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800254 for (const auto& log : log_files) {
255 if (!android::base::WriteStringToFile(log.data, log.name, log.sb.st_mode, log.sb.st_uid,
256 log.sb.st_gid)) {
257 PLOG(ERROR) << "Failed to write to " << log.name;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700258 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800259 }
260 } else {
261 PLOG(ERROR) << "Failed to mount / create " << CACHE_LOG_DIR;
Doug Zongker2c3539e2010-09-29 13:21:30 -0700262 }
263
Tao Bao3f5a3822016-12-13 11:14:37 -0800264 // Any part of the log we'd copied to cache is now gone.
265 // Reset the pointer so we copy from the beginning of the temp
266 // log.
Jerry Zhangcadf4ed2018-05-02 16:56:00 -0700267 reset_tmplog_offset();
268 copy_logs(modified_flash, has_cache);
Tao Bao3f5a3822016-12-13 11:14:37 -0800269 }
270
271 return (result == 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800272}
273
Elliott Hughes30694c92015-03-25 15:16:51 -0700274static bool yes_no(Device* device, const char* question1, const char* question2) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700275 std::vector<std::string> headers{ question1, question2 };
276 std::vector<std::string> items{ " No", " Yes" };
Doug Zongkerddd6a282009-06-09 12:22:33 -0700277
Tao Bao1fe1afe2018-05-01 15:56:05 -0700278 size_t chosen_item = ui->ShowMenu(
Tao Bao3aec6962018-04-20 09:24:58 -0700279 headers, items, 0, true,
280 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
281 return (chosen_item == 1);
Elliott Hughes30694c92015-03-25 15:16:51 -0700282}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800283
Paul Crowley08404b42016-12-19 13:04:23 -0800284static bool ask_to_wipe_data(Device* device) {
Tianjie Xu1a0a30a2018-10-25 15:22:07 -0700285 std::vector<std::string> headers{ "Wipe all user data?", " THIS CAN NOT BE UNDONE!" };
286 std::vector<std::string> items{ " Cancel", " Factory data reset" };
287
288 size_t chosen_item = ui->ShowPromptWipeDataConfirmationMenu(
289 headers, items,
290 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
291
292 return (chosen_item == 1);
Paul Crowley08404b42016-12-19 13:04:23 -0800293}
Doug Zongker1066d2c2009-04-01 13:57:40 -0700294
Paul Crowley08404b42016-12-19 13:04:23 -0800295// Return true on success.
296static bool wipe_data(Device* device) {
Tao Bao682c34b2015-04-07 17:16:35 -0700297 modified_flash = true;
298
Doug Zongker211aebc2011-10-28 15:13:10 -0700299 ui->Print("\n-- Wiping data...\n");
Paul Crowley3b4d5162016-06-08 13:51:41 -0700300 bool success = device->PreWipeData();
301 if (success) {
302 success &= erase_volume(DATA_ROOT);
303 if (has_cache) {
304 success &= erase_volume(CACHE_ROOT);
305 }
306 if (volume_for_mount_point(METADATA_ROOT) != nullptr) {
307 success &= erase_volume(METADATA_ROOT);
308 }
309 }
310 if (success) {
311 success &= device->PostWipeData();
312 }
Elliott Hughes945548e2015-06-05 17:59:56 -0700313 ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
314 return success;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700315}
316
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700317static InstallResult prompt_and_wipe_data(Device* device) {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700318 // Use a single string and let ScreenRecoveryUI handles the wrapping.
Tianjie Xub99e6062018-10-16 15:13:09 -0700319 std::vector<std::string> wipe_data_menu_headers{
Tao Bao2bbc6d62017-08-13 23:48:55 -0700320 "Can't load Android system. Your data may be corrupt. "
321 "If you continue to get this message, you may need to "
322 "perform a factory data reset and erase all user data "
Paul Crowley31ac0c62017-03-23 12:32:40 -0700323 "stored on this device.",
Tao Baofc5499f2017-02-23 19:06:53 -0800324 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700325 // clang-format off
Tianjie Xub99e6062018-10-16 15:13:09 -0700326 std::vector<std::string> wipe_data_menu_items {
Paul Crowley31ac0c62017-03-23 12:32:40 -0700327 "Try again",
328 "Factory data reset",
Tao Baofc5499f2017-02-23 19:06:53 -0800329 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700330 // clang-format on
Tao Baofc5499f2017-02-23 19:06:53 -0800331 for (;;) {
Tianjie Xub99e6062018-10-16 15:13:09 -0700332 size_t chosen_item = ui->ShowPromptWipeDataMenu(
333 wipe_data_menu_headers, wipe_data_menu_items,
Tao Bao3aec6962018-04-20 09:24:58 -0700334 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Jerry Zhangb76af932018-05-22 12:08:35 -0700335 // If ShowMenu() returned RecoveryUI::KeyError::INTERRUPTED, WaitKey() was interrupted.
336 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700337 return INSTALL_KEY_INTERRUPTED;
Jerry Zhangb76af932018-05-22 12:08:35 -0700338 }
Tao Baofc5499f2017-02-23 19:06:53 -0800339 if (chosen_item != 1) {
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700340 return INSTALL_SUCCESS; // Just reboot, no wipe; not a failure, user asked for it
Paul Crowley08404b42016-12-19 13:04:23 -0800341 }
Tianjie Xub99e6062018-10-16 15:13:09 -0700342
Tao Baofc5499f2017-02-23 19:06:53 -0800343 if (ask_to_wipe_data(device)) {
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700344 if (wipe_data(device)) {
345 return INSTALL_SUCCESS;
346 } else {
347 return INSTALL_ERROR;
348 }
Tao Baofc5499f2017-02-23 19:06:53 -0800349 }
350 }
Paul Crowley08404b42016-12-19 13:04:23 -0800351}
352
Tao Baoe39a9bc2015-03-31 12:19:05 -0700353// Return true on success.
354static bool wipe_cache(bool should_confirm, Device* device) {
Tao Bao26112e52016-02-25 12:29:40 -0800355 if (!has_cache) {
356 ui->Print("No /cache partition found.\n");
357 return false;
358 }
359
Elliott Hughes30694c92015-03-25 15:16:51 -0700360 if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
Tao Baoe39a9bc2015-03-31 12:19:05 -0700361 return false;
Elliott Hughes30694c92015-03-25 15:16:51 -0700362 }
363
Tao Bao682c34b2015-04-07 17:16:35 -0700364 modified_flash = true;
365
Elliott Hughes30694c92015-03-25 15:16:51 -0700366 ui->Print("\n-- Wiping cache...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700367 bool success = erase_volume("/cache");
368 ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
369 return success;
Elliott Hughes30694c92015-03-25 15:16:51 -0700370}
371
Tao Bao1b2a98b2017-03-24 10:45:34 -0700372// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
373// BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
Tao Bao862a4c12016-06-02 11:16:50 -0700374static bool secure_wipe_partition(const std::string& partition) {
Tao Bao1b2a98b2017-03-24 10:45:34 -0700375 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
376 if (fd == -1) {
377 PLOG(ERROR) << "Failed to open \"" << partition << "\"";
378 return false;
379 }
380
381 uint64_t range[2] = { 0, 0 };
382 if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
383 PLOG(ERROR) << "Failed to get partition size";
384 return false;
385 }
386 LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
387
388 LOG(INFO) << " Trying BLKSECDISCARD...";
389 if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
390 PLOG(WARNING) << " Failed";
391
392 // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
393 unsigned int zeroes;
394 if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
395 LOG(INFO) << " Trying BLKDISCARD...";
396 if (ioctl(fd, BLKDISCARD, &range) == -1) {
397 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700398 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700399 }
400 } else {
401 LOG(INFO) << " Trying BLKZEROOUT...";
402 if (ioctl(fd, BLKZEROOUT, &range) == -1) {
403 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700404 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700405 }
Tao Bao862a4c12016-06-02 11:16:50 -0700406 }
Tao Bao1b2a98b2017-03-24 10:45:34 -0700407 }
Tao Bao862a4c12016-06-02 11:16:50 -0700408
Tao Bao1b2a98b2017-03-24 10:45:34 -0700409 LOG(INFO) << " Done";
410 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700411}
412
xunchang55e3d222019-03-11 11:28:41 -0700413static std::unique_ptr<Package> ReadWipePackage(size_t wipe_package_size) {
xunchange0d991c2019-03-05 14:50:51 -0800414 if (wipe_package_size == 0) {
415 LOG(ERROR) << "wipe_package_size is zero";
xunchang55e3d222019-03-11 11:28:41 -0700416 return nullptr;
xunchange0d991c2019-03-05 14:50:51 -0800417 }
418
419 std::string wipe_package;
420 std::string err_str;
421 if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
422 PLOG(ERROR) << "Failed to read wipe package" << err_str;
xunchang55e3d222019-03-11 11:28:41 -0700423 return nullptr;
xunchange0d991c2019-03-05 14:50:51 -0800424 }
xunchang55e3d222019-03-11 11:28:41 -0700425
426 return Package::CreateMemoryPackage(
427 std::vector<uint8_t>(wipe_package.begin(), wipe_package.end()), nullptr);
xunchange0d991c2019-03-05 14:50:51 -0800428}
429
430// Checks if the wipe package matches expectation. If the check passes, reads the list of
431// partitions to wipe from the package. Checks include
Yabin Cuifd99a312016-06-09 14:09:39 -0700432// 1. verify the package.
433// 2. check metadata (ota-type, pre-device and serial number if having one).
xunchang55e3d222019-03-11 11:28:41 -0700434static bool CheckWipePackage(Package* wipe_package) {
xunchang24788852019-03-22 16:08:52 -0700435 if (!verify_package(wipe_package, ui)) {
xunchange0d991c2019-03-05 14:50:51 -0800436 LOG(ERROR) << "Failed to verify package";
437 return false;
438 }
Yabin Cuifd99a312016-06-09 14:09:39 -0700439
xunchang55e3d222019-03-11 11:28:41 -0700440 ZipArchiveHandle zip = wipe_package->GetZipArchiveHandle();
441 if (!zip) {
442 LOG(ERROR) << "Failed to get ZipArchiveHandle";
xunchange0d991c2019-03-05 14:50:51 -0800443 return false;
444 }
445
446 std::map<std::string, std::string> metadata;
447 if (!ReadMetadataFromPackage(zip, &metadata)) {
448 LOG(ERROR) << "Failed to parse metadata in the zip file";
449 return false;
450 }
451
xunchang55e3d222019-03-11 11:28:41 -0700452 return CheckPackageMetadata(metadata, OtaType::BRICK) == 0;
xunchange0d991c2019-03-05 14:50:51 -0800453}
454
xunchang55e3d222019-03-11 11:28:41 -0700455std::vector<std::string> GetWipePartitionList(Package* wipe_package) {
456 ZipArchiveHandle zip = wipe_package->GetZipArchiveHandle();
457 if (!zip) {
458 LOG(ERROR) << "Failed to get ZipArchiveHandle";
xunchange0d991c2019-03-05 14:50:51 -0800459 return {};
460 }
461
462 static constexpr const char* RECOVERY_WIPE_ENTRY_NAME = "recovery.wipe";
463
464 std::string partition_list_content;
465 ZipString path(RECOVERY_WIPE_ENTRY_NAME);
466 ZipEntry entry;
467 if (FindEntry(zip, path, &entry) == 0) {
468 uint32_t length = entry.uncompressed_length;
469 partition_list_content = std::string(length, '\0');
470 if (auto err = ExtractToMemory(
471 zip, &entry, reinterpret_cast<uint8_t*>(partition_list_content.data()), length);
472 err != 0) {
473 LOG(ERROR) << "Failed to extract " << RECOVERY_WIPE_ENTRY_NAME << ": "
474 << ErrorCodeString(err);
xunchange0d991c2019-03-05 14:50:51 -0800475 return {};
Yabin Cuifd99a312016-06-09 14:09:39 -0700476 }
xunchange0d991c2019-03-05 14:50:51 -0800477 } else {
478 LOG(INFO) << "Failed to find " << RECOVERY_WIPE_ENTRY_NAME
479 << ", falling back to use the partition list on device.";
Tianjie Xu93b5bf22018-10-25 10:39:01 -0700480
xunchange0d991c2019-03-05 14:50:51 -0800481 static constexpr const char* RECOVERY_WIPE_ON_DEVICE = "/etc/recovery.wipe";
482 if (!android::base::ReadFileToString(RECOVERY_WIPE_ON_DEVICE, &partition_list_content)) {
483 PLOG(ERROR) << "failed to read \"" << RECOVERY_WIPE_ON_DEVICE << "\"";
xunchange0d991c2019-03-05 14:50:51 -0800484 return {};
Yabin Cuifd99a312016-06-09 14:09:39 -0700485 }
xunchange0d991c2019-03-05 14:50:51 -0800486 }
Tianjie Xu93b5bf22018-10-25 10:39:01 -0700487
xunchange0d991c2019-03-05 14:50:51 -0800488 std::vector<std::string> result;
489 std::vector<std::string> lines = android::base::Split(partition_list_content, "\n");
490 for (const std::string& line : lines) {
491 std::string partition = android::base::Trim(line);
492 // Ignore '#' comment or empty lines.
493 if (android::base::StartsWith(partition, "#") || partition.empty()) {
494 continue;
495 }
496 result.push_back(line);
497 }
Yabin Cuifd99a312016-06-09 14:09:39 -0700498
xunchange0d991c2019-03-05 14:50:51 -0800499 return result;
Yabin Cuifd99a312016-06-09 14:09:39 -0700500}
501
Tao Baoaac9d9f2018-04-29 23:38:59 -0700502// Wipes the current A/B device, with a secure wipe of all the partitions in RECOVERY_WIPE.
Yabin Cuifd99a312016-06-09 14:09:39 -0700503static bool wipe_ab_device(size_t wipe_package_size) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700504 ui->SetBackground(RecoveryUI::ERASING);
505 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Tao Bao862a4c12016-06-02 11:16:50 -0700506
xunchang55e3d222019-03-11 11:28:41 -0700507 auto wipe_package = ReadWipePackage(wipe_package_size);
508 if (!wipe_package) {
509 LOG(ERROR) << "Failed to open wipe package";
xunchange0d991c2019-03-05 14:50:51 -0800510 return false;
511 }
512
xunchang55e3d222019-03-11 11:28:41 -0700513 if (!CheckWipePackage(wipe_package.get())) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700514 LOG(ERROR) << "Failed to verify wipe package";
515 return false;
516 }
xunchange0d991c2019-03-05 14:50:51 -0800517
xunchang55e3d222019-03-11 11:28:41 -0700518 auto partition_list = GetWipePartitionList(wipe_package.get());
xunchange0d991c2019-03-05 14:50:51 -0800519 if (partition_list.empty()) {
520 LOG(ERROR) << "Empty wipe ab partition list";
Tao Baoaac9d9f2018-04-29 23:38:59 -0700521 return false;
522 }
523
xunchange0d991c2019-03-05 14:50:51 -0800524 for (const auto& partition : partition_list) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700525 // Proceed anyway even if it fails to wipe some partition.
526 secure_wipe_partition(partition);
527 }
528 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700529}
530
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700531static void choose_recovery_file(Device* device) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800532 std::vector<std::string> entries;
533 if (has_cache) {
534 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
535 auto add_to_entries = [&](const char* filename) {
536 std::string log_file(filename);
537 if (i > 0) {
538 log_file += "." + std::to_string(i);
Tao Baobef39712015-05-04 18:50:27 -0700539 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800540
Yifan Hongd81b8e32018-12-17 14:29:06 -0800541 if (ensure_path_mounted(log_file) == 0 && access(log_file.c_str(), R_OK) == 0) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800542 entries.push_back(std::move(log_file));
543 }
544 };
545
546 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
547 add_to_entries(LAST_LOG_FILE);
548
549 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
550 add_to_entries(LAST_KMSG_FILE);
551 }
552 } else {
553 // If cache partition is not found, view /tmp/recovery.log instead.
Tao Bao641fa972018-04-25 18:59:40 -0700554 if (access(Paths::Get().temporary_log_file().c_str(), R_OK) == -1) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800555 return;
Tianjie Xua54f75e2016-08-17 12:02:46 -0700556 } else {
Tao Bao641fa972018-04-25 18:59:40 -0700557 entries.push_back(Paths::Get().temporary_log_file());
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700558 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800559 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700560
Tao Bao08fc6be2017-03-07 00:56:27 -0800561 entries.push_back("Back");
Elliott Hughesc0491632015-05-06 12:40:05 -0700562
Tao Bao1fe1afe2018-05-01 15:56:05 -0700563 std::vector<std::string> headers{ "Select file to view" };
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700564
Tao Bao1fe1afe2018-05-01 15:56:05 -0700565 size_t chosen_item = 0;
Tao Bao08fc6be2017-03-07 00:56:27 -0800566 while (true) {
Tao Bao3aec6962018-04-20 09:24:58 -0700567 chosen_item = ui->ShowMenu(
Tao Bao1fe1afe2018-05-01 15:56:05 -0700568 headers, entries, chosen_item, true,
Tao Bao3aec6962018-04-20 09:24:58 -0700569 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Jerry Zhangb76af932018-05-22 12:08:35 -0700570
571 // Handle WaitKey() interrupt.
572 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
573 break;
574 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800575 if (entries[chosen_item] == "Back") break;
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700576
Tao Bao1d156b92018-05-02 12:43:18 -0700577 ui->ShowFile(entries[chosen_item]);
Tao Bao08fc6be2017-03-07 00:56:27 -0800578 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700579}
580
Tao Baodb7e8982017-03-06 23:53:16 -0800581static void run_graphics_test() {
582 // Switch to graphics screen.
583 ui->ShowText(false);
Elliott Hughes498cda62016-04-14 16:49:04 -0700584
Tao Baodb7e8982017-03-06 23:53:16 -0800585 ui->SetProgressType(RecoveryUI::INDETERMINATE);
586 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
587 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700588
Tao Baodb7e8982017-03-06 23:53:16 -0800589 ui->SetBackground(RecoveryUI::ERROR);
590 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700591
Tao Baodb7e8982017-03-06 23:53:16 -0800592 ui->SetBackground(RecoveryUI::NO_COMMAND);
593 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700594
Tao Baodb7e8982017-03-06 23:53:16 -0800595 ui->SetBackground(RecoveryUI::ERASING);
596 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700597
Tao Baodb7e8982017-03-06 23:53:16 -0800598 // Calling SetBackground() after SetStage() to trigger a redraw.
599 ui->SetStage(1, 3);
600 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
601 sleep(1);
602 ui->SetStage(2, 3);
603 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
604 sleep(1);
605 ui->SetStage(3, 3);
606 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
607 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700608
Tao Baodb7e8982017-03-06 23:53:16 -0800609 ui->SetStage(-1, -1);
610 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Elliott Hughes498cda62016-04-14 16:49:04 -0700611
Tao Baodb7e8982017-03-06 23:53:16 -0800612 ui->SetProgressType(RecoveryUI::DETERMINATE);
613 ui->ShowProgress(1.0, 10.0);
614 float fraction = 0.0;
615 for (size_t i = 0; i < 100; ++i) {
616 fraction += .01;
617 ui->SetProgress(fraction);
618 usleep(100000);
619 }
620
621 ui->ShowText(true);
Elliott Hughes498cda62016-04-14 16:49:04 -0700622}
623
Tao Bao50dd5322017-03-07 14:57:04 -0800624// Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
625// which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
626static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
627 for (;;) {
Tao Bao551d2c32018-05-09 20:53:13 -0700628 finish_recovery();
Tao Bao50dd5322017-03-07 14:57:04 -0800629 switch (status) {
630 case INSTALL_SUCCESS:
631 case INSTALL_NONE:
632 ui->SetBackground(RecoveryUI::NO_COMMAND);
633 break;
Doug Zongker6c8553d2012-09-24 10:40:47 -0700634
Tao Bao50dd5322017-03-07 14:57:04 -0800635 case INSTALL_ERROR:
636 case INSTALL_CORRUPT:
637 ui->SetBackground(RecoveryUI::ERROR);
638 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800639 }
Tao Bao50dd5322017-03-07 14:57:04 -0800640 ui->SetProgressType(RecoveryUI::EMPTY);
641
Tao Bao1fe1afe2018-05-01 15:56:05 -0700642 size_t chosen_item = ui->ShowMenu(
643 {}, device->GetMenuItems(), 0, false,
Tao Bao3aec6962018-04-20 09:24:58 -0700644 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Jerry Zhangb76af932018-05-22 12:08:35 -0700645 // Handle Interrupt key
646 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
647 return Device::KEY_INTERRUPTED;
648 }
Tao Bao50dd5322017-03-07 14:57:04 -0800649 // Device-specific code may take some action here. It may return one of the core actions
650 // handled in the switch statement below.
Jerry Zhangb76af932018-05-22 12:08:35 -0700651 Device::BuiltinAction chosen_action =
652 (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::TIMED_OUT))
653 ? Device::REBOOT
654 : device->InvokeMenuItem(chosen_item);
Tao Bao50dd5322017-03-07 14:57:04 -0800655
656 bool should_wipe_cache = false;
657 switch (chosen_action) {
658 case Device::NO_ACTION:
659 break;
660
661 case Device::REBOOT:
662 case Device::SHUTDOWN:
663 case Device::REBOOT_BOOTLOADER:
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700664 case Device::ENTER_FASTBOOT:
665 case Device::ENTER_RECOVERY:
Tao Bao50dd5322017-03-07 14:57:04 -0800666 return chosen_action;
667
668 case Device::WIPE_DATA:
669 if (ui->IsTextVisible()) {
670 if (ask_to_wipe_data(device)) {
671 wipe_data(device);
672 }
673 } else {
674 wipe_data(device);
675 return Device::NO_ACTION;
676 }
677 break;
678
679 case Device::WIPE_CACHE:
680 wipe_cache(ui->IsTextVisible(), device);
681 if (!ui->IsTextVisible()) return Device::NO_ACTION;
682 break;
683
684 case Device::APPLY_ADB_SIDELOAD:
xunchang3cc23d52019-03-18 15:03:33 -0700685 case Device::APPLY_SDCARD: {
686 modified_flash = true;
687 bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD);
688 if (adb) {
xunchang24788852019-03-22 16:08:52 -0700689 status = apply_from_adb(&should_wipe_cache, ui);
xunchang3cc23d52019-03-18 15:03:33 -0700690 } else {
691 status = ApplyFromSdcard(device, &should_wipe_cache, ui);
692 }
Tao Bao50dd5322017-03-07 14:57:04 -0800693
xunchang3cc23d52019-03-18 15:03:33 -0700694 if (status == INSTALL_SUCCESS && should_wipe_cache) {
695 if (!wipe_cache(false, device)) {
696 status = INSTALL_ERROR;
Tao Bao50dd5322017-03-07 14:57:04 -0800697 }
698 }
xunchang3cc23d52019-03-18 15:03:33 -0700699
700 if (status != INSTALL_SUCCESS) {
701 ui->SetBackground(RecoveryUI::ERROR);
702 ui->Print("Installation aborted.\n");
703 copy_logs(modified_flash, has_cache);
704 } else if (!ui->IsTextVisible()) {
705 return Device::NO_ACTION; // reboot if logs aren't visible
706 } else {
707 ui->Print("\nInstall from %s complete.\n", adb ? "ADB" : "SD card");
708 }
Tao Bao50dd5322017-03-07 14:57:04 -0800709 break;
xunchang3cc23d52019-03-18 15:03:33 -0700710 }
Tao Bao50dd5322017-03-07 14:57:04 -0800711
712 case Device::VIEW_RECOVERY_LOGS:
713 choose_recovery_file(device);
714 break;
715
716 case Device::RUN_GRAPHICS_TEST:
717 run_graphics_test();
718 break;
719
Tianjie Xu29d55752017-09-20 17:53:46 -0700720 case Device::RUN_LOCALE_TEST: {
721 ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
Tao Bao39c49182018-05-07 22:50:33 -0700722 screen_ui->CheckBackgroundTextImages();
Tianjie Xu29d55752017-09-20 17:53:46 -0700723 break;
724 }
Tao Bao50dd5322017-03-07 14:57:04 -0800725 case Device::MOUNT_SYSTEM:
Jiyong Park8b7af4c2018-06-01 11:58:54 +0900726 // the system partition is mounted at /mnt/system
Yifan Hongd81b8e32018-12-17 14:29:06 -0800727 if (ensure_path_mounted_at(get_system_root(), "/mnt/system") != -1) {
Yifan Hong49327802018-11-26 14:59:09 -0800728 ui->Print("Mounted /system.\n");
Tao Bao50dd5322017-03-07 14:57:04 -0800729 }
730 break;
Jerry Zhangb76af932018-05-22 12:08:35 -0700731
732 case Device::KEY_INTERRUPTED:
733 return Device::KEY_INTERRUPTED;
Tao Bao50dd5322017-03-07 14:57:04 -0800734 }
735 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800736}
737
Tao Bao99f0d9e2016-10-13 12:46:38 -0700738static void print_property(const char* key, const char* name, void* /* cookie */) {
739 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800740}
741
Tao Bao6d90a9d2018-04-26 10:40:36 -0700742static bool is_battery_ok(int* required_battery_level) {
Yifan Honge8e4c402017-11-08 14:56:03 -0800743 using android::hardware::health::V1_0::BatteryStatus;
Yifan Hong056538c2018-07-11 17:04:12 -0700744 using android::hardware::health::V2_0::get_health_service;
745 using android::hardware::health::V2_0::IHealth;
Yifan Honge8e4c402017-11-08 14:56:03 -0800746 using android::hardware::health::V2_0::Result;
747 using android::hardware::health::V2_0::toString;
Yabin Cui99281df2016-02-17 12:21:52 -0800748
Yifan Hong056538c2018-07-11 17:04:12 -0700749 android::sp<IHealth> health = get_health_service();
Yifan Honge8e4c402017-11-08 14:56:03 -0800750
Tao Bao6d90a9d2018-04-26 10:40:36 -0700751 static constexpr int BATTERY_READ_TIMEOUT_IN_SEC = 10;
Yifan Honge8e4c402017-11-08 14:56:03 -0800752 int wait_second = 0;
753 while (true) {
754 auto charge_status = BatteryStatus::UNKNOWN;
Yifan Hong056538c2018-07-11 17:04:12 -0700755
756 if (health == nullptr) {
757 LOG(WARNING) << "no health implementation is found, assuming defaults";
758 } else {
759 health
760 ->getChargeStatus([&charge_status](auto res, auto out_status) {
761 if (res == Result::SUCCESS) {
762 charge_status = out_status;
763 }
764 })
765 .isOk(); // should not have transport error
766 }
Yifan Honge8e4c402017-11-08 14:56:03 -0800767
768 // Treat unknown status as charged.
769 bool charged = (charge_status != BatteryStatus::DISCHARGING &&
770 charge_status != BatteryStatus::NOT_CHARGING);
771
772 Result res = Result::UNKNOWN;
773 int32_t capacity = INT32_MIN;
Yifan Hong056538c2018-07-11 17:04:12 -0700774 if (health != nullptr) {
775 health
776 ->getCapacity([&res, &capacity](auto out_res, auto out_capacity) {
777 res = out_res;
778 capacity = out_capacity;
779 })
780 .isOk(); // should not have transport error
781 }
Yifan Honge8e4c402017-11-08 14:56:03 -0800782
Yifan Hong056538c2018-07-11 17:04:12 -0700783 LOG(INFO) << "charge_status " << toString(charge_status) << ", charged " << charged
784 << ", status " << toString(res) << ", capacity " << capacity;
Yifan Honge8e4c402017-11-08 14:56:03 -0800785 // At startup, the battery drivers in devices like N5X/N6P take some time to load
786 // the battery profile. Before the load finishes, it reports value 50 as a fake
787 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
788 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
789 if (res == Result::SUCCESS && capacity == 50) {
790 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
791 sleep(1);
792 wait_second++;
793 continue;
794 }
795 }
796 // If we can't read battery percentage, it may be a device without battery. In this
797 // situation, use 100 as a fake battery percentage.
798 if (res != Result::SUCCESS) {
799 capacity = 100;
800 }
Tao Bao6d90a9d2018-04-26 10:40:36 -0700801
802 // GmsCore enters recovery mode to install package when having enough battery percentage.
803 // Normally, the threshold is 40% without charger and 20% with charger. So we should check
804 // battery with a slightly lower limitation.
805 static constexpr int BATTERY_OK_PERCENTAGE = 20;
806 static constexpr int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
807 *required_battery_level = charged ? BATTERY_WITH_CHARGER_OK_PERCENTAGE : BATTERY_OK_PERCENTAGE;
808 return capacity >= *required_battery_level;
809 }
Yabin Cui99281df2016-02-17 12:21:52 -0800810}
811
Tianjie Xu99b73be2017-11-28 17:23:06 -0800812// Set the retry count to |retry_count| in BCB.
Tianjie Xu72449c92017-05-16 18:07:31 -0700813static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
814 std::vector<std::string> options;
815 for (const auto& arg : args) {
816 if (!android::base::StartsWith(arg, "--retry_count")) {
817 options.push_back(arg);
Tianjie Xu3c62b672016-02-05 18:25:58 -0800818 }
Tianjie Xu72449c92017-05-16 18:07:31 -0700819 }
Tianjie Xu3c62b672016-02-05 18:25:58 -0800820
Tianjie Xu99b73be2017-11-28 17:23:06 -0800821 // Update the retry counter in BCB.
822 options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
Tianjie Xu72449c92017-05-16 18:07:31 -0700823 std::string err;
824 if (!update_bootloader_message(options, &err)) {
825 LOG(ERROR) << err;
826 }
Tianjie Xu3c62b672016-02-05 18:25:58 -0800827}
828
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700829static bool bootreason_in_blacklist() {
Tao Baoefc35592017-01-08 22:45:47 -0800830 std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
831 if (!bootreason.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700832 // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
833 static const std::vector<std::string> kBootreasonBlacklist{
834 "kernel_panic",
835 "Panic",
836 };
837 for (const auto& str : kBootreasonBlacklist) {
838 if (android::base::EqualsIgnoreCase(str, bootreason)) return true;
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700839 }
Tao Baoefc35592017-01-08 22:45:47 -0800840 }
841 return false;
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700842}
843
Tao Bao641fa972018-04-25 18:59:40 -0700844static void log_failure_code(ErrorCode code, const std::string& update_package) {
845 std::vector<std::string> log_buffer = {
846 update_package,
847 "0", // install result
848 "error: " + std::to_string(code),
849 };
850 std::string log_content = android::base::Join(log_buffer, "\n");
851 const std::string& install_file = Paths::Get().temporary_install_file();
852 if (!android::base::WriteStringToFile(log_content, install_file)) {
853 PLOG(ERROR) << "Failed to write " << install_file;
854 }
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700855
Tao Bao641fa972018-04-25 18:59:40 -0700856 // Also write the info into last_log.
857 LOG(INFO) << log_content;
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700858}
859
Jerry Zhang6a648042018-05-04 11:24:10 -0700860Device::BuiltinAction start_recovery(Device* device, const std::vector<std::string>& args) {
Tao Baof9f17342018-04-27 10:44:04 -0700861 static constexpr struct option OPTIONS[] = {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700862 { "fastboot", no_argument, nullptr, 0 },
David Andersonedee8362018-05-16 13:43:22 -0700863 { "fsck_unshare_blocks", no_argument, nullptr, 0 },
Tao Baof9f17342018-04-27 10:44:04 -0700864 { "just_exit", no_argument, nullptr, 'x' },
865 { "locale", required_argument, nullptr, 0 },
866 { "prompt_and_wipe_data", no_argument, nullptr, 0 },
867 { "reason", required_argument, nullptr, 0 },
868 { "retry_count", required_argument, nullptr, 0 },
869 { "security", no_argument, nullptr, 0 },
870 { "show_text", no_argument, nullptr, 't' },
871 { "shutdown_after", no_argument, nullptr, 0 },
872 { "sideload", no_argument, nullptr, 0 },
873 { "sideload_auto_reboot", no_argument, nullptr, 0 },
874 { "update_package", required_argument, nullptr, 0 },
875 { "wipe_ab", no_argument, nullptr, 0 },
876 { "wipe_cache", no_argument, nullptr, 0 },
877 { "wipe_data", no_argument, nullptr, 0 },
878 { "wipe_package_size", required_argument, nullptr, 0 },
879 { nullptr, 0, nullptr, 0 },
880 };
881
Tianjie Xu99b73be2017-11-28 17:23:06 -0800882 const char* update_package = nullptr;
883 bool should_wipe_data = false;
884 bool should_prompt_and_wipe_data = false;
885 bool should_wipe_cache = false;
886 bool should_wipe_ab = false;
887 size_t wipe_package_size = 0;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800888 bool sideload = false;
889 bool sideload_auto_reboot = false;
890 bool just_exit = false;
891 bool shutdown_after = false;
David Andersonedee8362018-05-16 13:43:22 -0700892 bool fsck_unshare_blocks = false;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800893 int retry_count = 0;
894 bool security_update = false;
Jerry Zhang2dea53e2018-05-02 17:15:03 -0700895 std::string locale;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800896
Tao Bao1700cc42018-07-16 22:09:59 -0700897 auto args_to_parse = StringVectorToNullTerminatedArray(args);
898
Tianjie Xu99b73be2017-11-28 17:23:06 -0800899 int arg;
900 int option_index;
Tao Bao1700cc42018-07-16 22:09:59 -0700901 // Parse everything before the last element (which must be a nullptr). getopt_long(3) expects a
902 // null-terminated char* array, but without counting null as an arg (i.e. argv[argc] should be
903 // nullptr).
904 while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
Tianjie Xu99b73be2017-11-28 17:23:06 -0800905 &option_index)) != -1) {
906 switch (arg) {
Tianjie Xu99b73be2017-11-28 17:23:06 -0800907 case 't':
Jerry Zhang6a648042018-05-04 11:24:10 -0700908 // Handled in recovery_main.cpp
Tianjie Xu99b73be2017-11-28 17:23:06 -0800909 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800910 case 'x':
911 just_exit = true;
912 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800913 case 0: {
914 std::string option = OPTIONS[option_index].name;
David Andersonedee8362018-05-16 13:43:22 -0700915 if (option == "fsck_unshare_blocks") {
916 fsck_unshare_blocks = true;
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700917 } else if (option == "locale" || option == "fastboot") {
Jerry Zhang6a648042018-05-04 11:24:10 -0700918 // Handled in recovery_main.cpp
Tianjie Xu99b73be2017-11-28 17:23:06 -0800919 } else if (option == "prompt_and_wipe_data") {
920 should_prompt_and_wipe_data = true;
Tao Baof9f17342018-04-27 10:44:04 -0700921 } else if (option == "reason") {
922 reason = optarg;
923 } else if (option == "retry_count") {
924 android::base::ParseInt(optarg, &retry_count, 0);
925 } else if (option == "security") {
926 security_update = true;
927 } else if (option == "sideload") {
928 sideload = true;
929 } else if (option == "sideload_auto_reboot") {
930 sideload = true;
931 sideload_auto_reboot = true;
932 } else if (option == "shutdown_after") {
933 shutdown_after = true;
934 } else if (option == "update_package") {
935 update_package = optarg;
936 } else if (option == "wipe_ab") {
937 should_wipe_ab = true;
938 } else if (option == "wipe_cache") {
939 should_wipe_cache = true;
940 } else if (option == "wipe_data") {
941 should_wipe_data = true;
942 } else if (option == "wipe_package_size") {
943 android::base::ParseUint(optarg, &wipe_package_size);
Tianjie Xu99b73be2017-11-28 17:23:06 -0800944 }
945 break;
946 }
947 case '?':
948 LOG(ERROR) << "Invalid command argument";
949 continue;
Doug Zongker9270a202012-01-09 15:16:13 -0800950 }
Tianjie Xu99b73be2017-11-28 17:23:06 -0800951 }
Jerry Zhang49fd5d22018-05-17 12:54:41 -0700952 optind = 1;
Doug Zongker9270a202012-01-09 15:16:13 -0800953
Tianjie Xu99b73be2017-11-28 17:23:06 -0800954 printf("stage is [%s]\n", stage.c_str());
955 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -0700956
Tianjie Xu99b73be2017-11-28 17:23:06 -0800957 // Set background string to "installing security update" for security update,
958 // otherwise set it to "installing system update".
959 ui->SetSystemUpdateText(security_update);
960
961 int st_cur, st_max;
962 if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
963 ui->SetStage(st_cur, st_max);
964 }
965
Jerry Zhang0e577ee2018-05-07 11:21:10 -0700966 std::vector<std::string> title_lines =
967 android::base::Split(android::base::GetProperty("ro.bootimage.build.fingerprint", ""), ":");
968 title_lines.insert(std::begin(title_lines), "Android Recovery");
969 ui->SetTitle(title_lines);
970
Jerry Zhangb76af932018-05-22 12:08:35 -0700971 ui->ResetKeyInterruptStatus();
Tianjie Xu99b73be2017-11-28 17:23:06 -0800972 device->StartRecovery();
973
974 printf("Command:");
975 for (const auto& arg : args) {
976 printf(" \"%s\"", arg.c_str());
977 }
978 printf("\n\n");
979
980 property_list(print_property, nullptr);
981 printf("\n");
982
983 ui->Print("Supported API: %d\n", kRecoveryApiVersion);
984
985 int status = INSTALL_SUCCESS;
986
987 if (update_package != nullptr) {
988 // It's not entirely true that we will modify the flash. But we want
989 // to log the update attempt since update_package is non-NULL.
990 modified_flash = true;
991
Tao Bao6d90a9d2018-04-26 10:40:36 -0700992 int required_battery_level;
993 if (retry_count == 0 && !is_battery_ok(&required_battery_level)) {
994 ui->Print("battery capacity is not enough for installing package: %d%% needed\n",
995 required_battery_level);
Tianjie Xu99b73be2017-11-28 17:23:06 -0800996 // Log the error code to last_install when installation skips due to
997 // low battery.
998 log_failure_code(kLowBattery, update_package);
999 status = INSTALL_SKIPPED;
Tianjie Xua6f49bd2018-03-26 14:32:11 -07001000 } else if (retry_count == 0 && bootreason_in_blacklist()) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001001 // Skip update-on-reboot when bootreason is kernel_panic or similar
1002 ui->Print("bootreason is in the blacklist; skip OTA installation\n");
1003 log_failure_code(kBootreasonInBlacklist, update_package);
1004 status = INSTALL_SKIPPED;
Dmitri Plotnikov8706a982017-04-18 08:28:26 -07001005 } else {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001006 // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
1007 // identify the interrupted update due to unexpected reboots.
1008 if (retry_count == 0) {
1009 set_retry_bootloader_message(retry_count + 1, args);
Tao Bao7022f332017-07-25 09:52:36 -07001010 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001011
xunchang24788852019-03-22 16:08:52 -07001012 modified_flash = true;
1013 status = install_package(update_package, &should_wipe_cache, true, retry_count, ui);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001014 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1015 wipe_cache(false, device);
1016 }
1017 if (status != INSTALL_SUCCESS) {
1018 ui->Print("Installation aborted.\n");
Tao Baoaac9d9f2018-04-29 23:38:59 -07001019
1020 // When I/O error or bspatch/imgpatch error happens, reboot and retry installation
1021 // RETRY_LIMIT times before we abandon this OTA update.
1022 static constexpr int RETRY_LIMIT = 4;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001023 if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
Jerry Zhangcadf4ed2018-05-02 16:56:00 -07001024 copy_logs(modified_flash, has_cache);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001025 retry_count += 1;
1026 set_retry_bootloader_message(retry_count, args);
1027 // Print retry count on screen.
1028 ui->Print("Retry attempt %d\n", retry_count);
1029
1030 // Reboot and retry the update
1031 if (!reboot("reboot,recovery")) {
1032 ui->Print("Reboot failed\n");
1033 } else {
1034 while (true) {
1035 pause();
1036 }
1037 }
Tianjie Xud9d16292017-04-20 18:08:21 -07001038 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001039 // If this is an eng or userdebug build, then automatically
1040 // turn the text display on if the script fails so the error
1041 // message is visible.
1042 if (is_ro_debuggable()) {
1043 ui->ShowText(true);
Tao Baoc679f932015-03-30 09:43:49 -07001044 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001045 }
Doug Zongker8674a722010-09-15 11:08:23 -07001046 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001047 } else if (should_wipe_data) {
1048 if (!wipe_data(device)) {
1049 status = INSTALL_ERROR;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001050 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001051 } else if (should_prompt_and_wipe_data) {
Tao Baoa5bbcb92018-09-17 14:32:47 -07001052 // Trigger the logging to capture the cause, even if user chooses to not wipe data.
1053 modified_flash = true;
1054
Tianjie Xu99b73be2017-11-28 17:23:06 -08001055 ui->ShowText(true);
1056 ui->SetBackground(RecoveryUI::ERROR);
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -07001057 status = prompt_and_wipe_data(device);
1058 if (status != INSTALL_KEY_INTERRUPTED) {
1059 ui->ShowText(false);
Tao Bao75238632015-05-27 14:46:17 -07001060 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001061 } else if (should_wipe_cache) {
1062 if (!wipe_cache(false, device)) {
1063 status = INSTALL_ERROR;
1064 }
1065 } else if (should_wipe_ab) {
1066 if (!wipe_ab_device(wipe_package_size)) {
1067 status = INSTALL_ERROR;
1068 }
1069 } else if (sideload) {
1070 // 'adb reboot sideload' acts the same as user presses key combinations
1071 // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
1072 // display will NOT be turned on by default. And it will reboot after
1073 // sideload finishes even if there are errors. Unless one turns on the
1074 // text display during the installation. This is to enable automated
1075 // testing.
1076 if (!sideload_auto_reboot) {
1077 ui->ShowText(true);
1078 }
xunchang24788852019-03-22 16:08:52 -07001079 status = apply_from_adb(&should_wipe_cache, ui);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001080 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1081 if (!wipe_cache(false, device)) {
1082 status = INSTALL_ERROR;
1083 }
1084 }
1085 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1086 if (sideload_auto_reboot) {
1087 ui->Print("Rebooting automatically.\n");
1088 }
David Andersonedee8362018-05-16 13:43:22 -07001089 } else if (fsck_unshare_blocks) {
1090 if (!do_fsck_unshare_blocks()) {
1091 status = INSTALL_ERROR;
1092 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001093 } else if (!just_exit) {
1094 // If this is an eng or userdebug build, automatically turn on the text display if no command
1095 // is specified. Note that this should be called before setting the background to avoid
1096 // flickering the background image.
1097 if (is_ro_debuggable()) {
1098 ui->ShowText(true);
1099 }
1100 status = INSTALL_NONE; // No command specified
1101 ui->SetBackground(RecoveryUI::NO_COMMAND);
1102 }
1103
1104 if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
1105 ui->SetBackground(RecoveryUI::ERROR);
1106 if (!ui->IsTextVisible()) {
1107 sleep(5);
1108 }
1109 }
1110
1111 Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
1112 // 1. If the recovery menu is visible, prompt and wait for commands.
1113 // 2. If the state is INSTALL_NONE, wait for commands. (i.e. In user build, manually reboot into
1114 // recovery to sideload a package.)
1115 // 3. sideload_auto_reboot is an option only available in user-debug build, reboot the device
1116 // without waiting.
1117 // 4. In all other cases, reboot the device. Therefore, normal users will observe the device
1118 // reboot after it shows the "error" screen for 5s.
1119 if ((status == INSTALL_NONE && !sideload_auto_reboot) || ui->IsTextVisible()) {
1120 Device::BuiltinAction temp = prompt_and_wait(device, status);
1121 if (temp != Device::NO_ACTION) {
1122 after = temp;
1123 }
1124 }
1125
1126 // Save logs and clean up before rebooting or shutting down.
Tao Bao551d2c32018-05-09 20:53:13 -07001127 finish_recovery();
Tianjie Xu99b73be2017-11-28 17:23:06 -08001128
Jerry Zhang6a648042018-05-04 11:24:10 -07001129 return after;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001130}