blob: 90ca3f0eca7f0fc1c70f5db8f4f4f50cca156543 [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>
Doug Zongker7c3ae452013-05-14 11:03:02 -070027#include <stdarg.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080028#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
Doug Zongker23ceeea2010-07-08 17:27:55 -070031#include <sys/stat.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080032#include <sys/types.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080033#include <unistd.h>
34
Tao Baoc4a18ef2017-02-10 00:13:30 -080035#include <algorithm>
Tao Bao3aec6962018-04-20 09:24:58 -070036#include <functional>
Tao Baoc4a18ef2017-02-10 00:13:30 -080037#include <memory>
Tao Bao862a4c12016-06-02 11:16:50 -070038#include <string>
39#include <vector>
Tao Bao04ca4262015-09-10 15:32:24 -070040
Elliott Hughes4b166f02015-12-04 15:30:20 -080041#include <android-base/file.h>
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -070042#include <android-base/logging.h>
Tianjie Xu3c62b672016-02-05 18:25:58 -080043#include <android-base/parseint.h>
Elliott Hughescb220402016-09-23 15:30:55 -070044#include <android-base/properties.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080045#include <android-base/stringprintf.h>
Tao Bao862a4c12016-06-02 11:16:50 -070046#include <android-base/strings.h>
47#include <android-base/unique_fd.h>
Yabin Cui8b309f62016-06-24 18:22:02 -070048#include <bootloader_message/bootloader_message.h>
Elliott Hughescb220402016-09-23 15:30:55 -070049#include <cutils/properties.h> /* for property_list */
Yifan Hong056538c2018-07-11 17:04:12 -070050#include <healthhalutils/HealthHalUtils.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070051#include <ziparchive/zip_archive.h>
Yabin Cui99281df2016-02-17 12:21:52 -080052
Tao Bao75238632015-05-27 14:46:17 -070053#include "adb_install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080054#include "common.h"
Tao Bao75238632015-05-27 14:46:17 -070055#include "device.h"
David Andersonedee8362018-05-16 13:43:22 -070056#include "fsck_unshare_blocks.h"
xunchangea2912f2019-03-17 16:45:12 -070057#include "fuse_sdcard_install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080058#include "install.h"
Jerry Zhangcadf4ed2018-05-02 16:56:00 -070059#include "logging.h"
Tao Bao17054c02018-05-03 22:41:23 -070060#include "otautil/dirutil.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070061#include "otautil/error_code.h"
Tao Bao641fa972018-04-25 18:59:40 -070062#include "otautil/paths.h"
Tao Bao2c526392018-05-03 23:01:13 -070063#include "otautil/sysutil.h"
xunchangf07ed2e2019-02-25 14:14:01 -080064#include "package.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080065#include "roots.h"
Doug Zongker211aebc2011-10-28 15:13:10 -070066#include "screen_ui.h"
Tianjie Xue113e4d2016-10-21 17:46:13 -070067#include "ui.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080068
Tao Baoaac9d9f2018-04-29 23:38:59 -070069static constexpr const char* CACHE_LOG_DIR = "/cache/recovery";
70static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
Tao Baoaac9d9f2018-04-29 23:38:59 -070071static constexpr const char* LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
72static constexpr const char* LAST_LOG_FILE = "/cache/recovery/last_log";
73static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
Tianjie Xu06e57ac2016-07-11 14:04:08 -070074
Tao Baoaac9d9f2018-04-29 23:38:59 -070075static constexpr const char* CACHE_ROOT = "/cache";
76static constexpr const char* DATA_ROOT = "/data";
77static constexpr const char* METADATA_ROOT = "/metadata";
Nick Kralevicha9ad0322014-10-22 18:38:48 -070078
Tao Baobd0ddcd2017-05-04 13:03:18 -070079// We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
80// into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
81static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
82
Tao Baoac9d94d2016-11-03 11:37:15 -070083bool modified_flash = false;
Tao Baoa8d72bc2016-12-25 18:46:50 -080084std::string stage;
Tao Baoac9d94d2016-11-03 11:37:15 -070085const char* reason = nullptr;
Tao Baoac9d94d2016-11-03 11:37:15 -070086
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080087/*
88 * The recovery tool communicates with the main system through /cache files.
89 * /cache/recovery/command - INPUT - command line for tool, one arg per line
90 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080091 *
92 * The arguments which may be supplied in the recovery.command file:
Doug Zongkerd4208f92010-09-20 12:16:13 -070093 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080094 * --wipe_data - erase user data (and cache), then reboot
Tao Baof9f17342018-04-27 10:44:04 -070095 * --prompt_and_wipe_data - prompt the user that data is corrupt, with their consent erase user
96 * data (and cache), then reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080097 * --wipe_cache - wipe cache (but not user data), then reboot
Tao Baof9f17342018-04-27 10:44:04 -070098 * --show_text - show the recovery text menu, used by some bootloader (e.g. http://b/36872519).
Oscar Montemayor05231562009-11-30 08:40:57 -080099 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700100 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800101 *
102 * After completing, we remove /cache/recovery/command and reboot.
103 * Arguments may also be supplied in the bootloader control block (BCB).
104 * These important scenarios must be safely restartable at any point:
105 *
106 * FACTORY RESET
107 * 1. user selects "factory reset"
108 * 2. main system writes "--wipe_data" to /cache/recovery/command
109 * 3. main system reboots into recovery
110 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
111 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700112 * 5. erase_volume() reformats /data
113 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800114 * 7. finish_recovery() erases BCB
115 * -- after this, rebooting will restart the main system --
116 * 8. main() calls reboot() to boot main system
117 *
118 * OTA INSTALL
119 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700120 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800121 * 3. main system reboots into recovery
122 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
123 * -- after this, rebooting will attempt to reinstall the update --
124 * 5. install_package() attempts to install the update
125 * NOTE: the package install must itself be restartable from any point
126 * 6. finish_recovery() erases BCB
127 * -- after this, rebooting will (try to) restart the main system --
128 * 7. ** if install failed **
129 * 7a. prompt_and_wait() shows an error icon and waits for the user
Tao Baoc0336392016-12-13 22:29:49 -0800130 * 7b. the user reboots (pulling the battery, etc) into the main system
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800131 */
132
Elliott Hughesf14af802015-02-10 14:46:14 -0800133bool is_ro_debuggable() {
Elliott Hughescb220402016-09-23 15:30:55 -0700134 return android::base::GetBoolProperty("ro.debuggable", false);
Elliott Hughesf14af802015-02-10 14:46:14 -0800135}
136
Tao Baoec579032017-07-21 12:13:15 -0700137// Clear the recovery command and prepare to boot a (hopefully working) system,
Tianjie Xuc14d95d2016-03-24 11:50:34 -0700138// copy our log file to cache as well (for the system to read). This function is
139// idempotent: call it as many times as you like.
Tao Bao551d2c32018-05-09 20:53:13 -0700140static void finish_recovery() {
141 std::string locale = ui->GetLocale();
Tao Baoec579032017-07-21 12:13:15 -0700142 // Save the locale to cache, so if recovery is next started up without a '--locale' argument
143 // (e.g., directly from the bootloader) it will use the last-known locale.
144 if (!locale.empty() && has_cache) {
145 LOG(INFO) << "Saving locale \"" << locale << "\"";
146 if (ensure_path_mounted(LOCALE_FILE) != 0) {
147 LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
148 } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
149 PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
Doug Zongker4f33e552012-08-23 13:16:12 -0700150 }
Tao Baoec579032017-07-21 12:13:15 -0700151 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700152
Jerry Zhangcadf4ed2018-05-02 16:56:00 -0700153 copy_logs(modified_flash, has_cache);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800154
Tao Baoec579032017-07-21 12:13:15 -0700155 // Reset to normal system boot so recovery won't cycle indefinitely.
156 std::string err;
157 if (!clear_bootloader_message(&err)) {
158 LOG(ERROR) << "Failed to clear BCB message: " << err;
159 }
160
161 // Remove the command file, so recovery won't repeat indefinitely.
162 if (has_cache) {
163 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
164 LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
Yabin Cui8b309f62016-06-24 18:22:02 -0700165 }
Tao Baoec579032017-07-21 12:13:15 -0700166 ensure_path_unmounted(CACHE_ROOT);
167 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800168
Tao Baoec579032017-07-21 12:13:15 -0700169 sync(); // For good measure.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800170}
171
Tao Bao3f5a3822016-12-13 11:14:37 -0800172struct saved_log_file {
173 std::string name;
174 struct stat sb;
175 std::string data;
176};
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700177
Elliott Hughes945548e2015-06-05 17:59:56 -0700178static bool erase_volume(const char* volume) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800179 bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
180 bool is_data = (strcmp(volume, DATA_ROOT) == 0);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700181
Tao Bao3f5a3822016-12-13 11:14:37 -0800182 ui->SetBackground(RecoveryUI::ERASING);
183 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700184
Tao Bao3f5a3822016-12-13 11:14:37 -0800185 std::vector<saved_log_file> log_files;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700186
Tao Bao3f5a3822016-12-13 11:14:37 -0800187 if (is_cache) {
188 // If we're reformatting /cache, we load any past logs
189 // (i.e. "/cache/recovery/last_*") and the current log
190 // ("/cache/recovery/log") into memory, so we can restore them after
191 // the reformat.
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700192
Tao Bao3f5a3822016-12-13 11:14:37 -0800193 ensure_path_mounted(volume);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700194
Tao Bao3f5a3822016-12-13 11:14:37 -0800195 struct dirent* de;
196 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(CACHE_LOG_DIR), closedir);
197 if (d) {
198 while ((de = readdir(d.get())) != nullptr) {
199 if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
200 std::string path = android::base::StringPrintf("%s/%s", CACHE_LOG_DIR, de->d_name);
201
202 struct stat sb;
203 if (stat(path.c_str(), &sb) == 0) {
204 // truncate files to 512kb
205 if (sb.st_size > (1 << 19)) {
206 sb.st_size = 1 << 19;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700207 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800208
209 std::string data(sb.st_size, '\0');
Tianjie Xude6735e2017-07-10 15:13:33 -0700210 FILE* f = fopen(path.c_str(), "rbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800211 fread(&data[0], 1, data.size(), f);
212 fclose(f);
213
214 log_files.emplace_back(saved_log_file{ path, sb, data });
215 }
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700216 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800217 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800218 } else {
Tao Bao3f5a3822016-12-13 11:14:37 -0800219 if (errno != ENOENT) {
220 PLOG(ERROR) << "Failed to opendir " << CACHE_LOG_DIR;
221 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800222 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800223 }
Doug Zongkerd0181b82011-10-19 10:51:12 -0700224
Tao Bao3f5a3822016-12-13 11:14:37 -0800225 ui->Print("Formatting %s...\n", volume);
226
227 ensure_path_unmounted(volume);
228
229 int result;
Tao Bao3f5a3822016-12-13 11:14:37 -0800230 if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700231 static constexpr const char* CONVERT_FBE_DIR = "/tmp/convert_fbe";
232 static constexpr const char* CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
233 // Create convert_fbe breadcrumb file to signal init to convert to file based encryption, not
234 // full disk encryption.
Tao Bao3f5a3822016-12-13 11:14:37 -0800235 if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700236 PLOG(ERROR) << "Failed to mkdir " << CONVERT_FBE_DIR;
237 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800238 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700239 FILE* f = fopen(CONVERT_FBE_FILE, "wbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800240 if (!f) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700241 PLOG(ERROR) << "Failed to convert to file encryption";
242 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800243 }
244 fclose(f);
245 result = format_volume(volume, CONVERT_FBE_DIR);
246 remove(CONVERT_FBE_FILE);
247 rmdir(CONVERT_FBE_DIR);
248 } else {
249 result = format_volume(volume);
250 }
251
252 if (is_cache) {
253 // Re-create the log dir and write back the log entries.
254 if (ensure_path_mounted(CACHE_LOG_DIR) == 0 &&
Tao Baoac3d1ed2017-07-23 00:01:02 -0700255 mkdir_recursively(CACHE_LOG_DIR, 0777, false, sehandle) == 0) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800256 for (const auto& log : log_files) {
257 if (!android::base::WriteStringToFile(log.data, log.name, log.sb.st_mode, log.sb.st_uid,
258 log.sb.st_gid)) {
259 PLOG(ERROR) << "Failed to write to " << log.name;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700260 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800261 }
262 } else {
263 PLOG(ERROR) << "Failed to mount / create " << CACHE_LOG_DIR;
Doug Zongker2c3539e2010-09-29 13:21:30 -0700264 }
265
Tao Bao3f5a3822016-12-13 11:14:37 -0800266 // Any part of the log we'd copied to cache is now gone.
267 // Reset the pointer so we copy from the beginning of the temp
268 // log.
Jerry Zhangcadf4ed2018-05-02 16:56:00 -0700269 reset_tmplog_offset();
270 copy_logs(modified_flash, has_cache);
Tao Bao3f5a3822016-12-13 11:14:37 -0800271 }
272
273 return (result == 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800274}
275
Hridya Valsarajue4ef4532018-08-31 11:57:51 -0700276// Sets the usb config to 'state'
277bool SetUsbConfig(const std::string& state) {
278 android::base::SetProperty("sys.usb.config", state);
279 return android::base::WaitForProperty("sys.usb.state", state);
280}
281
Elliott Hughes30694c92015-03-25 15:16:51 -0700282static bool yes_no(Device* device, const char* question1, const char* question2) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700283 std::vector<std::string> headers{ question1, question2 };
284 std::vector<std::string> items{ " No", " Yes" };
Doug Zongkerddd6a282009-06-09 12:22:33 -0700285
Tao Bao1fe1afe2018-05-01 15:56:05 -0700286 size_t chosen_item = ui->ShowMenu(
Tao Bao3aec6962018-04-20 09:24:58 -0700287 headers, items, 0, true,
288 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
289 return (chosen_item == 1);
Elliott Hughes30694c92015-03-25 15:16:51 -0700290}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800291
Paul Crowley08404b42016-12-19 13:04:23 -0800292static bool ask_to_wipe_data(Device* device) {
Tianjie Xu1a0a30a2018-10-25 15:22:07 -0700293 std::vector<std::string> headers{ "Wipe all user data?", " THIS CAN NOT BE UNDONE!" };
294 std::vector<std::string> items{ " Cancel", " Factory data reset" };
295
296 size_t chosen_item = ui->ShowPromptWipeDataConfirmationMenu(
297 headers, items,
298 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
299
300 return (chosen_item == 1);
Paul Crowley08404b42016-12-19 13:04:23 -0800301}
Doug Zongker1066d2c2009-04-01 13:57:40 -0700302
Paul Crowley08404b42016-12-19 13:04:23 -0800303// Return true on success.
304static bool wipe_data(Device* device) {
Tao Bao682c34b2015-04-07 17:16:35 -0700305 modified_flash = true;
306
Doug Zongker211aebc2011-10-28 15:13:10 -0700307 ui->Print("\n-- Wiping data...\n");
Paul Crowley3b4d5162016-06-08 13:51:41 -0700308 bool success = device->PreWipeData();
309 if (success) {
310 success &= erase_volume(DATA_ROOT);
311 if (has_cache) {
312 success &= erase_volume(CACHE_ROOT);
313 }
314 if (volume_for_mount_point(METADATA_ROOT) != nullptr) {
315 success &= erase_volume(METADATA_ROOT);
316 }
317 }
318 if (success) {
319 success &= device->PostWipeData();
320 }
Elliott Hughes945548e2015-06-05 17:59:56 -0700321 ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
322 return success;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700323}
324
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700325static InstallResult prompt_and_wipe_data(Device* device) {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700326 // Use a single string and let ScreenRecoveryUI handles the wrapping.
Tianjie Xub99e6062018-10-16 15:13:09 -0700327 std::vector<std::string> wipe_data_menu_headers{
Tao Bao2bbc6d62017-08-13 23:48:55 -0700328 "Can't load Android system. Your data may be corrupt. "
329 "If you continue to get this message, you may need to "
330 "perform a factory data reset and erase all user data "
Paul Crowley31ac0c62017-03-23 12:32:40 -0700331 "stored on this device.",
Tao Baofc5499f2017-02-23 19:06:53 -0800332 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700333 // clang-format off
Tianjie Xub99e6062018-10-16 15:13:09 -0700334 std::vector<std::string> wipe_data_menu_items {
Paul Crowley31ac0c62017-03-23 12:32:40 -0700335 "Try again",
336 "Factory data reset",
Tao Baofc5499f2017-02-23 19:06:53 -0800337 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700338 // clang-format on
Tao Baofc5499f2017-02-23 19:06:53 -0800339 for (;;) {
Tianjie Xub99e6062018-10-16 15:13:09 -0700340 size_t chosen_item = ui->ShowPromptWipeDataMenu(
341 wipe_data_menu_headers, wipe_data_menu_items,
Tao Bao3aec6962018-04-20 09:24:58 -0700342 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Jerry Zhangb76af932018-05-22 12:08:35 -0700343 // If ShowMenu() returned RecoveryUI::KeyError::INTERRUPTED, WaitKey() was interrupted.
344 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700345 return INSTALL_KEY_INTERRUPTED;
Jerry Zhangb76af932018-05-22 12:08:35 -0700346 }
Tao Baofc5499f2017-02-23 19:06:53 -0800347 if (chosen_item != 1) {
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700348 return INSTALL_SUCCESS; // Just reboot, no wipe; not a failure, user asked for it
Paul Crowley08404b42016-12-19 13:04:23 -0800349 }
Tianjie Xub99e6062018-10-16 15:13:09 -0700350
Tao Baofc5499f2017-02-23 19:06:53 -0800351 if (ask_to_wipe_data(device)) {
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700352 if (wipe_data(device)) {
353 return INSTALL_SUCCESS;
354 } else {
355 return INSTALL_ERROR;
356 }
Tao Baofc5499f2017-02-23 19:06:53 -0800357 }
358 }
Paul Crowley08404b42016-12-19 13:04:23 -0800359}
360
Tao Baoe39a9bc2015-03-31 12:19:05 -0700361// Return true on success.
362static bool wipe_cache(bool should_confirm, Device* device) {
Tao Bao26112e52016-02-25 12:29:40 -0800363 if (!has_cache) {
364 ui->Print("No /cache partition found.\n");
365 return false;
366 }
367
Elliott Hughes30694c92015-03-25 15:16:51 -0700368 if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
Tao Baoe39a9bc2015-03-31 12:19:05 -0700369 return false;
Elliott Hughes30694c92015-03-25 15:16:51 -0700370 }
371
Tao Bao682c34b2015-04-07 17:16:35 -0700372 modified_flash = true;
373
Elliott Hughes30694c92015-03-25 15:16:51 -0700374 ui->Print("\n-- Wiping cache...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700375 bool success = erase_volume("/cache");
376 ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
377 return success;
Elliott Hughes30694c92015-03-25 15:16:51 -0700378}
379
Tao Bao1b2a98b2017-03-24 10:45:34 -0700380// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
381// BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
Tao Bao862a4c12016-06-02 11:16:50 -0700382static bool secure_wipe_partition(const std::string& partition) {
Tao Bao1b2a98b2017-03-24 10:45:34 -0700383 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
384 if (fd == -1) {
385 PLOG(ERROR) << "Failed to open \"" << partition << "\"";
386 return false;
387 }
388
389 uint64_t range[2] = { 0, 0 };
390 if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
391 PLOG(ERROR) << "Failed to get partition size";
392 return false;
393 }
394 LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
395
396 LOG(INFO) << " Trying BLKSECDISCARD...";
397 if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
398 PLOG(WARNING) << " Failed";
399
400 // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
401 unsigned int zeroes;
402 if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
403 LOG(INFO) << " Trying BLKDISCARD...";
404 if (ioctl(fd, BLKDISCARD, &range) == -1) {
405 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700406 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700407 }
408 } else {
409 LOG(INFO) << " Trying BLKZEROOUT...";
410 if (ioctl(fd, BLKZEROOUT, &range) == -1) {
411 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700412 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700413 }
Tao Bao862a4c12016-06-02 11:16:50 -0700414 }
Tao Bao1b2a98b2017-03-24 10:45:34 -0700415 }
Tao Bao862a4c12016-06-02 11:16:50 -0700416
Tao Bao1b2a98b2017-03-24 10:45:34 -0700417 LOG(INFO) << " Done";
418 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700419}
420
xunchang55e3d222019-03-11 11:28:41 -0700421static std::unique_ptr<Package> ReadWipePackage(size_t wipe_package_size) {
xunchange0d991c2019-03-05 14:50:51 -0800422 if (wipe_package_size == 0) {
423 LOG(ERROR) << "wipe_package_size is zero";
xunchang55e3d222019-03-11 11:28:41 -0700424 return nullptr;
xunchange0d991c2019-03-05 14:50:51 -0800425 }
426
427 std::string wipe_package;
428 std::string err_str;
429 if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
430 PLOG(ERROR) << "Failed to read wipe package" << err_str;
xunchang55e3d222019-03-11 11:28:41 -0700431 return nullptr;
xunchange0d991c2019-03-05 14:50:51 -0800432 }
xunchang55e3d222019-03-11 11:28:41 -0700433
434 return Package::CreateMemoryPackage(
435 std::vector<uint8_t>(wipe_package.begin(), wipe_package.end()), nullptr);
xunchange0d991c2019-03-05 14:50:51 -0800436}
437
438// Checks if the wipe package matches expectation. If the check passes, reads the list of
439// partitions to wipe from the package. Checks include
Yabin Cuifd99a312016-06-09 14:09:39 -0700440// 1. verify the package.
441// 2. check metadata (ota-type, pre-device and serial number if having one).
xunchang55e3d222019-03-11 11:28:41 -0700442static bool CheckWipePackage(Package* wipe_package) {
443 if (!verify_package(wipe_package)) {
xunchange0d991c2019-03-05 14:50:51 -0800444 LOG(ERROR) << "Failed to verify package";
445 return false;
446 }
Yabin Cuifd99a312016-06-09 14:09:39 -0700447
xunchang55e3d222019-03-11 11:28:41 -0700448 ZipArchiveHandle zip = wipe_package->GetZipArchiveHandle();
449 if (!zip) {
450 LOG(ERROR) << "Failed to get ZipArchiveHandle";
xunchange0d991c2019-03-05 14:50:51 -0800451 return false;
452 }
453
454 std::map<std::string, std::string> metadata;
455 if (!ReadMetadataFromPackage(zip, &metadata)) {
456 LOG(ERROR) << "Failed to parse metadata in the zip file";
457 return false;
458 }
459
xunchang55e3d222019-03-11 11:28:41 -0700460 return CheckPackageMetadata(metadata, OtaType::BRICK) == 0;
xunchange0d991c2019-03-05 14:50:51 -0800461}
462
xunchang55e3d222019-03-11 11:28:41 -0700463std::vector<std::string> GetWipePartitionList(Package* wipe_package) {
464 ZipArchiveHandle zip = wipe_package->GetZipArchiveHandle();
465 if (!zip) {
466 LOG(ERROR) << "Failed to get ZipArchiveHandle";
xunchange0d991c2019-03-05 14:50:51 -0800467 return {};
468 }
469
470 static constexpr const char* RECOVERY_WIPE_ENTRY_NAME = "recovery.wipe";
471
472 std::string partition_list_content;
473 ZipString path(RECOVERY_WIPE_ENTRY_NAME);
474 ZipEntry entry;
475 if (FindEntry(zip, path, &entry) == 0) {
476 uint32_t length = entry.uncompressed_length;
477 partition_list_content = std::string(length, '\0');
478 if (auto err = ExtractToMemory(
479 zip, &entry, reinterpret_cast<uint8_t*>(partition_list_content.data()), length);
480 err != 0) {
481 LOG(ERROR) << "Failed to extract " << RECOVERY_WIPE_ENTRY_NAME << ": "
482 << ErrorCodeString(err);
xunchange0d991c2019-03-05 14:50:51 -0800483 return {};
Yabin Cuifd99a312016-06-09 14:09:39 -0700484 }
xunchange0d991c2019-03-05 14:50:51 -0800485 } else {
486 LOG(INFO) << "Failed to find " << RECOVERY_WIPE_ENTRY_NAME
487 << ", falling back to use the partition list on device.";
Tianjie Xu93b5bf22018-10-25 10:39:01 -0700488
xunchange0d991c2019-03-05 14:50:51 -0800489 static constexpr const char* RECOVERY_WIPE_ON_DEVICE = "/etc/recovery.wipe";
490 if (!android::base::ReadFileToString(RECOVERY_WIPE_ON_DEVICE, &partition_list_content)) {
491 PLOG(ERROR) << "failed to read \"" << RECOVERY_WIPE_ON_DEVICE << "\"";
xunchange0d991c2019-03-05 14:50:51 -0800492 return {};
Yabin Cuifd99a312016-06-09 14:09:39 -0700493 }
xunchange0d991c2019-03-05 14:50:51 -0800494 }
Tianjie Xu93b5bf22018-10-25 10:39:01 -0700495
xunchange0d991c2019-03-05 14:50:51 -0800496 std::vector<std::string> result;
497 std::vector<std::string> lines = android::base::Split(partition_list_content, "\n");
498 for (const std::string& line : lines) {
499 std::string partition = android::base::Trim(line);
500 // Ignore '#' comment or empty lines.
501 if (android::base::StartsWith(partition, "#") || partition.empty()) {
502 continue;
503 }
504 result.push_back(line);
505 }
Yabin Cuifd99a312016-06-09 14:09:39 -0700506
xunchange0d991c2019-03-05 14:50:51 -0800507 return result;
Yabin Cuifd99a312016-06-09 14:09:39 -0700508}
509
Tao Baoaac9d9f2018-04-29 23:38:59 -0700510// Wipes the current A/B device, with a secure wipe of all the partitions in RECOVERY_WIPE.
Yabin Cuifd99a312016-06-09 14:09:39 -0700511static bool wipe_ab_device(size_t wipe_package_size) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700512 ui->SetBackground(RecoveryUI::ERASING);
513 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Tao Bao862a4c12016-06-02 11:16:50 -0700514
xunchang55e3d222019-03-11 11:28:41 -0700515 auto wipe_package = ReadWipePackage(wipe_package_size);
516 if (!wipe_package) {
517 LOG(ERROR) << "Failed to open wipe package";
xunchange0d991c2019-03-05 14:50:51 -0800518 return false;
519 }
520
xunchang55e3d222019-03-11 11:28:41 -0700521 if (!CheckWipePackage(wipe_package.get())) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700522 LOG(ERROR) << "Failed to verify wipe package";
523 return false;
524 }
xunchange0d991c2019-03-05 14:50:51 -0800525
xunchang55e3d222019-03-11 11:28:41 -0700526 auto partition_list = GetWipePartitionList(wipe_package.get());
xunchange0d991c2019-03-05 14:50:51 -0800527 if (partition_list.empty()) {
528 LOG(ERROR) << "Empty wipe ab partition list";
Tao Baoaac9d9f2018-04-29 23:38:59 -0700529 return false;
530 }
531
xunchange0d991c2019-03-05 14:50:51 -0800532 for (const auto& partition : partition_list) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700533 // Proceed anyway even if it fails to wipe some partition.
534 secure_wipe_partition(partition);
535 }
536 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700537}
538
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700539static void choose_recovery_file(Device* device) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800540 std::vector<std::string> entries;
541 if (has_cache) {
542 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
543 auto add_to_entries = [&](const char* filename) {
544 std::string log_file(filename);
545 if (i > 0) {
546 log_file += "." + std::to_string(i);
Tao Baobef39712015-05-04 18:50:27 -0700547 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800548
Yifan Hongd81b8e32018-12-17 14:29:06 -0800549 if (ensure_path_mounted(log_file) == 0 && access(log_file.c_str(), R_OK) == 0) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800550 entries.push_back(std::move(log_file));
551 }
552 };
553
554 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
555 add_to_entries(LAST_LOG_FILE);
556
557 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
558 add_to_entries(LAST_KMSG_FILE);
559 }
560 } else {
561 // If cache partition is not found, view /tmp/recovery.log instead.
Tao Bao641fa972018-04-25 18:59:40 -0700562 if (access(Paths::Get().temporary_log_file().c_str(), R_OK) == -1) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800563 return;
Tianjie Xua54f75e2016-08-17 12:02:46 -0700564 } else {
Tao Bao641fa972018-04-25 18:59:40 -0700565 entries.push_back(Paths::Get().temporary_log_file());
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700566 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800567 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700568
Tao Bao08fc6be2017-03-07 00:56:27 -0800569 entries.push_back("Back");
Elliott Hughesc0491632015-05-06 12:40:05 -0700570
Tao Bao1fe1afe2018-05-01 15:56:05 -0700571 std::vector<std::string> headers{ "Select file to view" };
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700572
Tao Bao1fe1afe2018-05-01 15:56:05 -0700573 size_t chosen_item = 0;
Tao Bao08fc6be2017-03-07 00:56:27 -0800574 while (true) {
Tao Bao3aec6962018-04-20 09:24:58 -0700575 chosen_item = ui->ShowMenu(
Tao Bao1fe1afe2018-05-01 15:56:05 -0700576 headers, entries, chosen_item, true,
Tao Bao3aec6962018-04-20 09:24:58 -0700577 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Jerry Zhangb76af932018-05-22 12:08:35 -0700578
579 // Handle WaitKey() interrupt.
580 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
581 break;
582 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800583 if (entries[chosen_item] == "Back") break;
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700584
Tao Bao1d156b92018-05-02 12:43:18 -0700585 ui->ShowFile(entries[chosen_item]);
Tao Bao08fc6be2017-03-07 00:56:27 -0800586 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700587}
588
Tao Baodb7e8982017-03-06 23:53:16 -0800589static void run_graphics_test() {
590 // Switch to graphics screen.
591 ui->ShowText(false);
Elliott Hughes498cda62016-04-14 16:49:04 -0700592
Tao Baodb7e8982017-03-06 23:53:16 -0800593 ui->SetProgressType(RecoveryUI::INDETERMINATE);
594 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
595 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700596
Tao Baodb7e8982017-03-06 23:53:16 -0800597 ui->SetBackground(RecoveryUI::ERROR);
598 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700599
Tao Baodb7e8982017-03-06 23:53:16 -0800600 ui->SetBackground(RecoveryUI::NO_COMMAND);
601 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700602
Tao Baodb7e8982017-03-06 23:53:16 -0800603 ui->SetBackground(RecoveryUI::ERASING);
604 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700605
Tao Baodb7e8982017-03-06 23:53:16 -0800606 // Calling SetBackground() after SetStage() to trigger a redraw.
607 ui->SetStage(1, 3);
608 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
609 sleep(1);
610 ui->SetStage(2, 3);
611 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
612 sleep(1);
613 ui->SetStage(3, 3);
614 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
615 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700616
Tao Baodb7e8982017-03-06 23:53:16 -0800617 ui->SetStage(-1, -1);
618 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Elliott Hughes498cda62016-04-14 16:49:04 -0700619
Tao Baodb7e8982017-03-06 23:53:16 -0800620 ui->SetProgressType(RecoveryUI::DETERMINATE);
621 ui->ShowProgress(1.0, 10.0);
622 float fraction = 0.0;
623 for (size_t i = 0; i < 100; ++i) {
624 fraction += .01;
625 ui->SetProgress(fraction);
626 usleep(100000);
627 }
628
629 ui->ShowText(true);
Elliott Hughes498cda62016-04-14 16:49:04 -0700630}
631
Tao Bao50dd5322017-03-07 14:57:04 -0800632// Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
633// which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
634static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
635 for (;;) {
Tao Bao551d2c32018-05-09 20:53:13 -0700636 finish_recovery();
Tao Bao50dd5322017-03-07 14:57:04 -0800637 switch (status) {
638 case INSTALL_SUCCESS:
639 case INSTALL_NONE:
640 ui->SetBackground(RecoveryUI::NO_COMMAND);
641 break;
Doug Zongker6c8553d2012-09-24 10:40:47 -0700642
Tao Bao50dd5322017-03-07 14:57:04 -0800643 case INSTALL_ERROR:
644 case INSTALL_CORRUPT:
645 ui->SetBackground(RecoveryUI::ERROR);
646 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800647 }
Tao Bao50dd5322017-03-07 14:57:04 -0800648 ui->SetProgressType(RecoveryUI::EMPTY);
649
Tao Bao1fe1afe2018-05-01 15:56:05 -0700650 size_t chosen_item = ui->ShowMenu(
651 {}, device->GetMenuItems(), 0, false,
Tao Bao3aec6962018-04-20 09:24:58 -0700652 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Jerry Zhangb76af932018-05-22 12:08:35 -0700653 // Handle Interrupt key
654 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
655 return Device::KEY_INTERRUPTED;
656 }
Tao Bao50dd5322017-03-07 14:57:04 -0800657 // Device-specific code may take some action here. It may return one of the core actions
658 // handled in the switch statement below.
Jerry Zhangb76af932018-05-22 12:08:35 -0700659 Device::BuiltinAction chosen_action =
660 (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::TIMED_OUT))
661 ? Device::REBOOT
662 : device->InvokeMenuItem(chosen_item);
Tao Bao50dd5322017-03-07 14:57:04 -0800663
664 bool should_wipe_cache = false;
665 switch (chosen_action) {
666 case Device::NO_ACTION:
667 break;
668
669 case Device::REBOOT:
670 case Device::SHUTDOWN:
671 case Device::REBOOT_BOOTLOADER:
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700672 case Device::ENTER_FASTBOOT:
673 case Device::ENTER_RECOVERY:
Tao Bao50dd5322017-03-07 14:57:04 -0800674 return chosen_action;
675
676 case Device::WIPE_DATA:
677 if (ui->IsTextVisible()) {
678 if (ask_to_wipe_data(device)) {
679 wipe_data(device);
680 }
681 } else {
682 wipe_data(device);
683 return Device::NO_ACTION;
684 }
685 break;
686
687 case Device::WIPE_CACHE:
688 wipe_cache(ui->IsTextVisible(), device);
689 if (!ui->IsTextVisible()) return Device::NO_ACTION;
690 break;
691
692 case Device::APPLY_ADB_SIDELOAD:
xunchang3cc23d52019-03-18 15:03:33 -0700693 case Device::APPLY_SDCARD: {
694 modified_flash = true;
695 bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD);
696 if (adb) {
697 status = apply_from_adb(&should_wipe_cache);
698 } else {
699 status = ApplyFromSdcard(device, &should_wipe_cache, ui);
700 }
Tao Bao50dd5322017-03-07 14:57:04 -0800701
xunchang3cc23d52019-03-18 15:03:33 -0700702 if (status == INSTALL_SUCCESS && should_wipe_cache) {
703 if (!wipe_cache(false, device)) {
704 status = INSTALL_ERROR;
Tao Bao50dd5322017-03-07 14:57:04 -0800705 }
706 }
xunchang3cc23d52019-03-18 15:03:33 -0700707
708 if (status != INSTALL_SUCCESS) {
709 ui->SetBackground(RecoveryUI::ERROR);
710 ui->Print("Installation aborted.\n");
711 copy_logs(modified_flash, has_cache);
712 } else if (!ui->IsTextVisible()) {
713 return Device::NO_ACTION; // reboot if logs aren't visible
714 } else {
715 ui->Print("\nInstall from %s complete.\n", adb ? "ADB" : "SD card");
716 }
Tao Bao50dd5322017-03-07 14:57:04 -0800717 break;
xunchang3cc23d52019-03-18 15:03:33 -0700718 }
Tao Bao50dd5322017-03-07 14:57:04 -0800719
720 case Device::VIEW_RECOVERY_LOGS:
721 choose_recovery_file(device);
722 break;
723
724 case Device::RUN_GRAPHICS_TEST:
725 run_graphics_test();
726 break;
727
Tianjie Xu29d55752017-09-20 17:53:46 -0700728 case Device::RUN_LOCALE_TEST: {
729 ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
Tao Bao39c49182018-05-07 22:50:33 -0700730 screen_ui->CheckBackgroundTextImages();
Tianjie Xu29d55752017-09-20 17:53:46 -0700731 break;
732 }
Tao Bao50dd5322017-03-07 14:57:04 -0800733 case Device::MOUNT_SYSTEM:
Jiyong Park8b7af4c2018-06-01 11:58:54 +0900734 // the system partition is mounted at /mnt/system
Yifan Hongd81b8e32018-12-17 14:29:06 -0800735 if (ensure_path_mounted_at(get_system_root(), "/mnt/system") != -1) {
Yifan Hong49327802018-11-26 14:59:09 -0800736 ui->Print("Mounted /system.\n");
Tao Bao50dd5322017-03-07 14:57:04 -0800737 }
738 break;
Jerry Zhangb76af932018-05-22 12:08:35 -0700739
740 case Device::KEY_INTERRUPTED:
741 return Device::KEY_INTERRUPTED;
Tao Bao50dd5322017-03-07 14:57:04 -0800742 }
743 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800744}
745
Tao Bao99f0d9e2016-10-13 12:46:38 -0700746static void print_property(const char* key, const char* name, void* /* cookie */) {
747 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800748}
749
Tao Baoac9d94d2016-11-03 11:37:15 -0700750void ui_print(const char* format, ...) {
751 std::string buffer;
Doug Zongker7c3ae452013-05-14 11:03:02 -0700752 va_list ap;
753 va_start(ap, format);
Tao Baoac9d94d2016-11-03 11:37:15 -0700754 android::base::StringAppendV(&buffer, format, ap);
Doug Zongker7c3ae452013-05-14 11:03:02 -0700755 va_end(ap);
756
Tao Baoac9d94d2016-11-03 11:37:15 -0700757 if (ui != nullptr) {
758 ui->Print("%s", buffer.c_str());
Doug Zongker7c3ae452013-05-14 11:03:02 -0700759 } else {
Tao Baoac9d94d2016-11-03 11:37:15 -0700760 fputs(buffer.c_str(), stdout);
Doug Zongker7c3ae452013-05-14 11:03:02 -0700761 }
762}
763
Tao Bao6d90a9d2018-04-26 10:40:36 -0700764static bool is_battery_ok(int* required_battery_level) {
Yifan Honge8e4c402017-11-08 14:56:03 -0800765 using android::hardware::health::V1_0::BatteryStatus;
Yifan Hong056538c2018-07-11 17:04:12 -0700766 using android::hardware::health::V2_0::get_health_service;
767 using android::hardware::health::V2_0::IHealth;
Yifan Honge8e4c402017-11-08 14:56:03 -0800768 using android::hardware::health::V2_0::Result;
769 using android::hardware::health::V2_0::toString;
Yabin Cui99281df2016-02-17 12:21:52 -0800770
Yifan Hong056538c2018-07-11 17:04:12 -0700771 android::sp<IHealth> health = get_health_service();
Yifan Honge8e4c402017-11-08 14:56:03 -0800772
Tao Bao6d90a9d2018-04-26 10:40:36 -0700773 static constexpr int BATTERY_READ_TIMEOUT_IN_SEC = 10;
Yifan Honge8e4c402017-11-08 14:56:03 -0800774 int wait_second = 0;
775 while (true) {
776 auto charge_status = BatteryStatus::UNKNOWN;
Yifan Hong056538c2018-07-11 17:04:12 -0700777
778 if (health == nullptr) {
779 LOG(WARNING) << "no health implementation is found, assuming defaults";
780 } else {
781 health
782 ->getChargeStatus([&charge_status](auto res, auto out_status) {
783 if (res == Result::SUCCESS) {
784 charge_status = out_status;
785 }
786 })
787 .isOk(); // should not have transport error
788 }
Yifan Honge8e4c402017-11-08 14:56:03 -0800789
790 // Treat unknown status as charged.
791 bool charged = (charge_status != BatteryStatus::DISCHARGING &&
792 charge_status != BatteryStatus::NOT_CHARGING);
793
794 Result res = Result::UNKNOWN;
795 int32_t capacity = INT32_MIN;
Yifan Hong056538c2018-07-11 17:04:12 -0700796 if (health != nullptr) {
797 health
798 ->getCapacity([&res, &capacity](auto out_res, auto out_capacity) {
799 res = out_res;
800 capacity = out_capacity;
801 })
802 .isOk(); // should not have transport error
803 }
Yifan Honge8e4c402017-11-08 14:56:03 -0800804
Yifan Hong056538c2018-07-11 17:04:12 -0700805 LOG(INFO) << "charge_status " << toString(charge_status) << ", charged " << charged
806 << ", status " << toString(res) << ", capacity " << capacity;
Yifan Honge8e4c402017-11-08 14:56:03 -0800807 // At startup, the battery drivers in devices like N5X/N6P take some time to load
808 // the battery profile. Before the load finishes, it reports value 50 as a fake
809 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
810 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
811 if (res == Result::SUCCESS && capacity == 50) {
812 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
813 sleep(1);
814 wait_second++;
815 continue;
816 }
817 }
818 // If we can't read battery percentage, it may be a device without battery. In this
819 // situation, use 100 as a fake battery percentage.
820 if (res != Result::SUCCESS) {
821 capacity = 100;
822 }
Tao Bao6d90a9d2018-04-26 10:40:36 -0700823
824 // GmsCore enters recovery mode to install package when having enough battery percentage.
825 // Normally, the threshold is 40% without charger and 20% with charger. So we should check
826 // battery with a slightly lower limitation.
827 static constexpr int BATTERY_OK_PERCENTAGE = 20;
828 static constexpr int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
829 *required_battery_level = charged ? BATTERY_WITH_CHARGER_OK_PERCENTAGE : BATTERY_OK_PERCENTAGE;
830 return capacity >= *required_battery_level;
831 }
Yabin Cui99281df2016-02-17 12:21:52 -0800832}
833
Tianjie Xu99b73be2017-11-28 17:23:06 -0800834// Set the retry count to |retry_count| in BCB.
Tianjie Xu72449c92017-05-16 18:07:31 -0700835static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
836 std::vector<std::string> options;
837 for (const auto& arg : args) {
838 if (!android::base::StartsWith(arg, "--retry_count")) {
839 options.push_back(arg);
Tianjie Xu3c62b672016-02-05 18:25:58 -0800840 }
Tianjie Xu72449c92017-05-16 18:07:31 -0700841 }
Tianjie Xu3c62b672016-02-05 18:25:58 -0800842
Tianjie Xu99b73be2017-11-28 17:23:06 -0800843 // Update the retry counter in BCB.
844 options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
Tianjie Xu72449c92017-05-16 18:07:31 -0700845 std::string err;
846 if (!update_bootloader_message(options, &err)) {
847 LOG(ERROR) << err;
848 }
Tianjie Xu3c62b672016-02-05 18:25:58 -0800849}
850
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700851static bool bootreason_in_blacklist() {
Tao Baoefc35592017-01-08 22:45:47 -0800852 std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
853 if (!bootreason.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700854 // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
855 static const std::vector<std::string> kBootreasonBlacklist{
856 "kernel_panic",
857 "Panic",
858 };
859 for (const auto& str : kBootreasonBlacklist) {
860 if (android::base::EqualsIgnoreCase(str, bootreason)) return true;
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700861 }
Tao Baoefc35592017-01-08 22:45:47 -0800862 }
863 return false;
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700864}
865
Tao Bao641fa972018-04-25 18:59:40 -0700866static void log_failure_code(ErrorCode code, const std::string& update_package) {
867 std::vector<std::string> log_buffer = {
868 update_package,
869 "0", // install result
870 "error: " + std::to_string(code),
871 };
872 std::string log_content = android::base::Join(log_buffer, "\n");
873 const std::string& install_file = Paths::Get().temporary_install_file();
874 if (!android::base::WriteStringToFile(log_content, install_file)) {
875 PLOG(ERROR) << "Failed to write " << install_file;
876 }
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700877
Tao Bao641fa972018-04-25 18:59:40 -0700878 // Also write the info into last_log.
879 LOG(INFO) << log_content;
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700880}
881
Jerry Zhang6a648042018-05-04 11:24:10 -0700882Device::BuiltinAction start_recovery(Device* device, const std::vector<std::string>& args) {
Tao Baof9f17342018-04-27 10:44:04 -0700883 static constexpr struct option OPTIONS[] = {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700884 { "fastboot", no_argument, nullptr, 0 },
David Andersonedee8362018-05-16 13:43:22 -0700885 { "fsck_unshare_blocks", no_argument, nullptr, 0 },
Tao Baof9f17342018-04-27 10:44:04 -0700886 { "just_exit", no_argument, nullptr, 'x' },
887 { "locale", required_argument, nullptr, 0 },
888 { "prompt_and_wipe_data", no_argument, nullptr, 0 },
889 { "reason", required_argument, nullptr, 0 },
890 { "retry_count", required_argument, nullptr, 0 },
891 { "security", no_argument, nullptr, 0 },
892 { "show_text", no_argument, nullptr, 't' },
893 { "shutdown_after", no_argument, nullptr, 0 },
894 { "sideload", no_argument, nullptr, 0 },
895 { "sideload_auto_reboot", no_argument, nullptr, 0 },
896 { "update_package", required_argument, nullptr, 0 },
897 { "wipe_ab", no_argument, nullptr, 0 },
898 { "wipe_cache", no_argument, nullptr, 0 },
899 { "wipe_data", no_argument, nullptr, 0 },
900 { "wipe_package_size", required_argument, nullptr, 0 },
901 { nullptr, 0, nullptr, 0 },
902 };
903
Tianjie Xu99b73be2017-11-28 17:23:06 -0800904 const char* update_package = nullptr;
905 bool should_wipe_data = false;
906 bool should_prompt_and_wipe_data = false;
907 bool should_wipe_cache = false;
908 bool should_wipe_ab = false;
909 size_t wipe_package_size = 0;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800910 bool sideload = false;
911 bool sideload_auto_reboot = false;
912 bool just_exit = false;
913 bool shutdown_after = false;
David Andersonedee8362018-05-16 13:43:22 -0700914 bool fsck_unshare_blocks = false;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800915 int retry_count = 0;
916 bool security_update = false;
Jerry Zhang2dea53e2018-05-02 17:15:03 -0700917 std::string locale;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800918
Tao Bao1700cc42018-07-16 22:09:59 -0700919 auto args_to_parse = StringVectorToNullTerminatedArray(args);
920
Tianjie Xu99b73be2017-11-28 17:23:06 -0800921 int arg;
922 int option_index;
Tao Bao1700cc42018-07-16 22:09:59 -0700923 // Parse everything before the last element (which must be a nullptr). getopt_long(3) expects a
924 // null-terminated char* array, but without counting null as an arg (i.e. argv[argc] should be
925 // nullptr).
926 while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
Tianjie Xu99b73be2017-11-28 17:23:06 -0800927 &option_index)) != -1) {
928 switch (arg) {
Tianjie Xu99b73be2017-11-28 17:23:06 -0800929 case 't':
Jerry Zhang6a648042018-05-04 11:24:10 -0700930 // Handled in recovery_main.cpp
Tianjie Xu99b73be2017-11-28 17:23:06 -0800931 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800932 case 'x':
933 just_exit = true;
934 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800935 case 0: {
936 std::string option = OPTIONS[option_index].name;
David Andersonedee8362018-05-16 13:43:22 -0700937 if (option == "fsck_unshare_blocks") {
938 fsck_unshare_blocks = true;
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700939 } else if (option == "locale" || option == "fastboot") {
Jerry Zhang6a648042018-05-04 11:24:10 -0700940 // Handled in recovery_main.cpp
Tianjie Xu99b73be2017-11-28 17:23:06 -0800941 } else if (option == "prompt_and_wipe_data") {
942 should_prompt_and_wipe_data = true;
Tao Baof9f17342018-04-27 10:44:04 -0700943 } else if (option == "reason") {
944 reason = optarg;
945 } else if (option == "retry_count") {
946 android::base::ParseInt(optarg, &retry_count, 0);
947 } else if (option == "security") {
948 security_update = true;
949 } else if (option == "sideload") {
950 sideload = true;
951 } else if (option == "sideload_auto_reboot") {
952 sideload = true;
953 sideload_auto_reboot = true;
954 } else if (option == "shutdown_after") {
955 shutdown_after = true;
956 } else if (option == "update_package") {
957 update_package = optarg;
958 } else if (option == "wipe_ab") {
959 should_wipe_ab = true;
960 } else if (option == "wipe_cache") {
961 should_wipe_cache = true;
962 } else if (option == "wipe_data") {
963 should_wipe_data = true;
964 } else if (option == "wipe_package_size") {
965 android::base::ParseUint(optarg, &wipe_package_size);
Tianjie Xu99b73be2017-11-28 17:23:06 -0800966 }
967 break;
968 }
969 case '?':
970 LOG(ERROR) << "Invalid command argument";
971 continue;
Doug Zongker9270a202012-01-09 15:16:13 -0800972 }
Tianjie Xu99b73be2017-11-28 17:23:06 -0800973 }
Jerry Zhang49fd5d22018-05-17 12:54:41 -0700974 optind = 1;
Doug Zongker9270a202012-01-09 15:16:13 -0800975
Tianjie Xu99b73be2017-11-28 17:23:06 -0800976 printf("stage is [%s]\n", stage.c_str());
977 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -0700978
Tianjie Xu99b73be2017-11-28 17:23:06 -0800979 // Set background string to "installing security update" for security update,
980 // otherwise set it to "installing system update".
981 ui->SetSystemUpdateText(security_update);
982
983 int st_cur, st_max;
984 if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
985 ui->SetStage(st_cur, st_max);
986 }
987
Jerry Zhang0e577ee2018-05-07 11:21:10 -0700988 std::vector<std::string> title_lines =
989 android::base::Split(android::base::GetProperty("ro.bootimage.build.fingerprint", ""), ":");
990 title_lines.insert(std::begin(title_lines), "Android Recovery");
991 ui->SetTitle(title_lines);
992
Jerry Zhangb76af932018-05-22 12:08:35 -0700993 ui->ResetKeyInterruptStatus();
Tianjie Xu99b73be2017-11-28 17:23:06 -0800994 device->StartRecovery();
995
996 printf("Command:");
997 for (const auto& arg : args) {
998 printf(" \"%s\"", arg.c_str());
999 }
1000 printf("\n\n");
1001
1002 property_list(print_property, nullptr);
1003 printf("\n");
1004
1005 ui->Print("Supported API: %d\n", kRecoveryApiVersion);
1006
1007 int status = INSTALL_SUCCESS;
1008
1009 if (update_package != nullptr) {
1010 // It's not entirely true that we will modify the flash. But we want
1011 // to log the update attempt since update_package is non-NULL.
1012 modified_flash = true;
1013
Tao Bao6d90a9d2018-04-26 10:40:36 -07001014 int required_battery_level;
1015 if (retry_count == 0 && !is_battery_ok(&required_battery_level)) {
1016 ui->Print("battery capacity is not enough for installing package: %d%% needed\n",
1017 required_battery_level);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001018 // Log the error code to last_install when installation skips due to
1019 // low battery.
1020 log_failure_code(kLowBattery, update_package);
1021 status = INSTALL_SKIPPED;
Tianjie Xua6f49bd2018-03-26 14:32:11 -07001022 } else if (retry_count == 0 && bootreason_in_blacklist()) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001023 // Skip update-on-reboot when bootreason is kernel_panic or similar
1024 ui->Print("bootreason is in the blacklist; skip OTA installation\n");
1025 log_failure_code(kBootreasonInBlacklist, update_package);
1026 status = INSTALL_SKIPPED;
Dmitri Plotnikov8706a982017-04-18 08:28:26 -07001027 } else {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001028 // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
1029 // identify the interrupted update due to unexpected reboots.
1030 if (retry_count == 0) {
1031 set_retry_bootloader_message(retry_count + 1, args);
Tao Bao7022f332017-07-25 09:52:36 -07001032 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001033
Tao Bao641fa972018-04-25 18:59:40 -07001034 status = install_package(update_package, &should_wipe_cache, true, retry_count);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001035 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1036 wipe_cache(false, device);
1037 }
1038 if (status != INSTALL_SUCCESS) {
1039 ui->Print("Installation aborted.\n");
Tao Baoaac9d9f2018-04-29 23:38:59 -07001040
1041 // When I/O error or bspatch/imgpatch error happens, reboot and retry installation
1042 // RETRY_LIMIT times before we abandon this OTA update.
1043 static constexpr int RETRY_LIMIT = 4;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001044 if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
Jerry Zhangcadf4ed2018-05-02 16:56:00 -07001045 copy_logs(modified_flash, has_cache);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001046 retry_count += 1;
1047 set_retry_bootloader_message(retry_count, args);
1048 // Print retry count on screen.
1049 ui->Print("Retry attempt %d\n", retry_count);
1050
1051 // Reboot and retry the update
1052 if (!reboot("reboot,recovery")) {
1053 ui->Print("Reboot failed\n");
1054 } else {
1055 while (true) {
1056 pause();
1057 }
1058 }
Tianjie Xud9d16292017-04-20 18:08:21 -07001059 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001060 // If this is an eng or userdebug build, then automatically
1061 // turn the text display on if the script fails so the error
1062 // message is visible.
1063 if (is_ro_debuggable()) {
1064 ui->ShowText(true);
Tao Baoc679f932015-03-30 09:43:49 -07001065 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001066 }
Doug Zongker8674a722010-09-15 11:08:23 -07001067 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001068 } else if (should_wipe_data) {
1069 if (!wipe_data(device)) {
1070 status = INSTALL_ERROR;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001071 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001072 } else if (should_prompt_and_wipe_data) {
Tao Baoa5bbcb92018-09-17 14:32:47 -07001073 // Trigger the logging to capture the cause, even if user chooses to not wipe data.
1074 modified_flash = true;
1075
Tianjie Xu99b73be2017-11-28 17:23:06 -08001076 ui->ShowText(true);
1077 ui->SetBackground(RecoveryUI::ERROR);
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -07001078 status = prompt_and_wipe_data(device);
1079 if (status != INSTALL_KEY_INTERRUPTED) {
1080 ui->ShowText(false);
Tao Bao75238632015-05-27 14:46:17 -07001081 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001082 } else if (should_wipe_cache) {
1083 if (!wipe_cache(false, device)) {
1084 status = INSTALL_ERROR;
1085 }
1086 } else if (should_wipe_ab) {
1087 if (!wipe_ab_device(wipe_package_size)) {
1088 status = INSTALL_ERROR;
1089 }
1090 } else if (sideload) {
1091 // 'adb reboot sideload' acts the same as user presses key combinations
1092 // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
1093 // display will NOT be turned on by default. And it will reboot after
1094 // sideload finishes even if there are errors. Unless one turns on the
1095 // text display during the installation. This is to enable automated
1096 // testing.
1097 if (!sideload_auto_reboot) {
1098 ui->ShowText(true);
1099 }
Tao Bao641fa972018-04-25 18:59:40 -07001100 status = apply_from_adb(&should_wipe_cache);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001101 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1102 if (!wipe_cache(false, device)) {
1103 status = INSTALL_ERROR;
1104 }
1105 }
1106 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1107 if (sideload_auto_reboot) {
1108 ui->Print("Rebooting automatically.\n");
1109 }
David Andersonedee8362018-05-16 13:43:22 -07001110 } else if (fsck_unshare_blocks) {
1111 if (!do_fsck_unshare_blocks()) {
1112 status = INSTALL_ERROR;
1113 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001114 } else if (!just_exit) {
1115 // If this is an eng or userdebug build, automatically turn on the text display if no command
1116 // is specified. Note that this should be called before setting the background to avoid
1117 // flickering the background image.
1118 if (is_ro_debuggable()) {
1119 ui->ShowText(true);
1120 }
1121 status = INSTALL_NONE; // No command specified
1122 ui->SetBackground(RecoveryUI::NO_COMMAND);
1123 }
1124
1125 if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
1126 ui->SetBackground(RecoveryUI::ERROR);
1127 if (!ui->IsTextVisible()) {
1128 sleep(5);
1129 }
1130 }
1131
1132 Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
1133 // 1. If the recovery menu is visible, prompt and wait for commands.
1134 // 2. If the state is INSTALL_NONE, wait for commands. (i.e. In user build, manually reboot into
1135 // recovery to sideload a package.)
1136 // 3. sideload_auto_reboot is an option only available in user-debug build, reboot the device
1137 // without waiting.
1138 // 4. In all other cases, reboot the device. Therefore, normal users will observe the device
1139 // reboot after it shows the "error" screen for 5s.
1140 if ((status == INSTALL_NONE && !sideload_auto_reboot) || ui->IsTextVisible()) {
1141 Device::BuiltinAction temp = prompt_and_wait(device, status);
1142 if (temp != Device::NO_ACTION) {
1143 after = temp;
1144 }
1145 }
1146
1147 // Save logs and clean up before rebooting or shutting down.
Tao Bao551d2c32018-05-09 20:53:13 -07001148 finish_recovery();
Tianjie Xu99b73be2017-11-28 17:23:06 -08001149
Jerry Zhang6a648042018-05-04 11:24:10 -07001150 return after;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001151}