blob: e427998a8c0da4661cd178562944426c13eb1b86 [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
Tao Bao6d99d4b2018-04-25 16:47:04 -070017#include "private/recovery.h"
18
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080019#include <ctype.h>
Doug Zongker7c3ae452013-05-14 11:03:02 -070020#include <dirent.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080021#include <errno.h>
22#include <fcntl.h>
23#include <getopt.h>
Tao Bao862a4c12016-06-02 11:16:50 -070024#include <inttypes.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080025#include <limits.h>
Tao Bao862a4c12016-06-02 11:16:50 -070026#include <linux/fs.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080027#include <linux/input.h>
Doug Zongker7c3ae452013-05-14 11:03:02 -070028#include <stdarg.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080029#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
Doug Zongker23ceeea2010-07-08 17:27:55 -070032#include <sys/stat.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080033#include <sys/types.h>
Tao Baocdcf28f2016-01-13 15:05:20 -080034#include <sys/wait.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080035#include <time.h>
36#include <unistd.h>
37
Tao Baoc4a18ef2017-02-10 00:13:30 -080038#include <algorithm>
Tao Bao3aec6962018-04-20 09:24:58 -070039#include <functional>
Tao Baoc4a18ef2017-02-10 00:13:30 -080040#include <memory>
Tao Bao862a4c12016-06-02 11:16:50 -070041#include <string>
42#include <vector>
Tao Bao04ca4262015-09-10 15:32:24 -070043
Elliott Hughes4b166f02015-12-04 15:30:20 -080044#include <android-base/file.h>
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -070045#include <android-base/logging.h>
Tianjie Xu3c62b672016-02-05 18:25:58 -080046#include <android-base/parseint.h>
Elliott Hughescb220402016-09-23 15:30:55 -070047#include <android-base/properties.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080048#include <android-base/stringprintf.h>
Tao Bao862a4c12016-06-02 11:16:50 -070049#include <android-base/strings.h>
50#include <android-base/unique_fd.h>
Yabin Cui8b309f62016-06-24 18:22:02 -070051#include <bootloader_message/bootloader_message.h>
Tao Bao75238632015-05-27 14:46:17 -070052#include <cutils/android_reboot.h>
Elliott Hughescb220402016-09-23 15:30:55 -070053#include <cutils/properties.h> /* for property_list */
Elliott Hughes4bbd5bf2016-04-01 18:24:39 -070054#include <healthd/BatteryMonitor.h>
Jeff Vander Stoepe35926e2017-06-14 15:30:39 -070055#include <selinux/android.h>
Elliott Hughes4bbd5bf2016-04-01 18:24:39 -070056#include <selinux/label.h>
57#include <selinux/selinux.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070058#include <ziparchive/zip_archive.h>
Yabin Cui99281df2016-02-17 12:21:52 -080059
Tao Bao75238632015-05-27 14:46:17 -070060#include "adb_install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080061#include "common.h"
Tao Bao75238632015-05-27 14:46:17 -070062#include "device.h"
63#include "fuse_sdcard_provider.h"
64#include "fuse_sideload.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080065#include "install.h"
Jerry Zhang152933a2018-05-02 16:56:00 -070066#include "logging.h"
Tao Bao17054c02018-05-03 22:41:23 -070067#include "otautil/dirutil.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070068#include "otautil/error_code.h"
Tao Bao641fa972018-04-25 18:59:40 -070069#include "otautil/paths.h"
Tao Bao2c526392018-05-03 23:01:13 -070070#include "otautil/sysutil.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080071#include "roots.h"
Doug Zongker211aebc2011-10-28 15:13:10 -070072#include "screen_ui.h"
Sen Jiangd5304492016-12-09 16:20:49 -080073#include "stub_ui.h"
Tianjie Xue113e4d2016-10-21 17:46:13 -070074#include "ui.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080075
Tao Baoaac9d9f2018-04-29 23:38:59 -070076static constexpr const char* CACHE_LOG_DIR = "/cache/recovery";
77static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
Tao Baoaac9d9f2018-04-29 23:38:59 -070078static constexpr const char* LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
79static constexpr const char* LAST_LOG_FILE = "/cache/recovery/last_log";
80static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
Tianjie Xu06e57ac2016-07-11 14:04:08 -070081
Tao Baoaac9d9f2018-04-29 23:38:59 -070082static constexpr const char* CACHE_ROOT = "/cache";
83static constexpr const char* DATA_ROOT = "/data";
84static constexpr const char* METADATA_ROOT = "/metadata";
85static constexpr const char* SDCARD_ROOT = "/sdcard";
Nick Kralevicha9ad0322014-10-22 18:38:48 -070086
Tao Baobd0ddcd2017-05-04 13:03:18 -070087// We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
88// into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
89static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
90
Dan Albert8584fcf2016-10-27 03:08:08 +000091static bool has_cache = false;
Tao Baoc0319b62016-10-13 15:17:04 -070092
Tao Baoac9d94d2016-11-03 11:37:15 -070093RecoveryUI* ui = nullptr;
94bool modified_flash = false;
Tao Baoa8d72bc2016-12-25 18:46:50 -080095std::string stage;
Tao Baoac9d94d2016-11-03 11:37:15 -070096const char* reason = nullptr;
97struct selabel_handle* sehandle;
98
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080099/*
100 * The recovery tool communicates with the main system through /cache files.
101 * /cache/recovery/command - INPUT - command line for tool, one arg per line
102 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800103 *
104 * The arguments which may be supplied in the recovery.command file:
Doug Zongkerd4208f92010-09-20 12:16:13 -0700105 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800106 * --wipe_data - erase user data (and cache), then reboot
Tao Baof9f17342018-04-27 10:44:04 -0700107 * --prompt_and_wipe_data - prompt the user that data is corrupt, with their consent erase user
108 * data (and cache), then reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800109 * --wipe_cache - wipe cache (but not user data), then reboot
Tao Baof9f17342018-04-27 10:44:04 -0700110 * --show_text - show the recovery text menu, used by some bootloader (e.g. http://b/36872519).
Oscar Montemayor05231562009-11-30 08:40:57 -0800111 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700112 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800113 *
114 * After completing, we remove /cache/recovery/command and reboot.
115 * Arguments may also be supplied in the bootloader control block (BCB).
116 * These important scenarios must be safely restartable at any point:
117 *
118 * FACTORY RESET
119 * 1. user selects "factory reset"
120 * 2. main system writes "--wipe_data" to /cache/recovery/command
121 * 3. main system reboots into recovery
122 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
123 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700124 * 5. erase_volume() reformats /data
125 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800126 * 7. finish_recovery() erases BCB
127 * -- after this, rebooting will restart the main system --
128 * 8. main() calls reboot() to boot main system
129 *
130 * OTA INSTALL
131 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700132 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800133 * 3. main system reboots into recovery
134 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
135 * -- after this, rebooting will attempt to reinstall the update --
136 * 5. install_package() attempts to install the update
137 * NOTE: the package install must itself be restartable from any point
138 * 6. finish_recovery() erases BCB
139 * -- after this, rebooting will (try to) restart the main system --
140 * 7. ** if install failed **
141 * 7a. prompt_and_wait() shows an error icon and waits for the user
Tao Baoc0336392016-12-13 22:29:49 -0800142 * 7b. the user reboots (pulling the battery, etc) into the main system
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800143 */
144
Elliott Hughesf14af802015-02-10 14:46:14 -0800145bool is_ro_debuggable() {
Elliott Hughescb220402016-09-23 15:30:55 -0700146 return android::base::GetBoolProperty("ro.debuggable", false);
Elliott Hughesf14af802015-02-10 14:46:14 -0800147}
148
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800149// command line args come from, in decreasing precedence:
150// - the actual command line
151// - the bootloader control block (one per line, after "recovery")
152// - the contents of COMMAND_FILE (one per line)
Tao Baof0ed1592016-12-02 11:32:19 -0800153static std::vector<std::string> get_args(const int argc, char** const argv) {
154 CHECK_GT(argc, 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800155
Tao Baof0ed1592016-12-02 11:32:19 -0800156 bootloader_message boot = {};
157 std::string err;
158 if (!read_bootloader_message(&boot, &err)) {
159 LOG(ERROR) << err;
160 // If fails, leave a zeroed bootloader_message.
161 boot = {};
162 }
Tao Baoa8d72bc2016-12-25 18:46:50 -0800163 stage = std::string(boot.stage);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800164
Tao Baof0ed1592016-12-02 11:32:19 -0800165 if (boot.command[0] != 0) {
166 std::string boot_command = std::string(boot.command, sizeof(boot.command));
167 LOG(INFO) << "Boot command: " << boot_command;
168 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800169
Tao Baof0ed1592016-12-02 11:32:19 -0800170 if (boot.status[0] != 0) {
171 std::string boot_status = std::string(boot.status, sizeof(boot.status));
172 LOG(INFO) << "Boot status: " << boot_status;
173 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800174
Tao Baof0ed1592016-12-02 11:32:19 -0800175 std::vector<std::string> args(argv, argv + argc);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800176
Tao Baof0ed1592016-12-02 11:32:19 -0800177 // --- if arguments weren't supplied, look in the bootloader control block
Tao Bao570af9d2017-01-09 10:29:59 -0800178 if (args.size() == 1) {
Tao Baof0ed1592016-12-02 11:32:19 -0800179 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
180 std::string boot_recovery(boot.recovery);
181 std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
182 if (!tokens.empty() && tokens[0] == "recovery") {
183 for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
184 // Skip empty and '\0'-filled tokens.
185 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
186 }
187 LOG(INFO) << "Got " << args.size() << " arguments from boot message";
188 } else if (boot.recovery[0] != 0) {
189 LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
190 }
191 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800192
Tao Baof0ed1592016-12-02 11:32:19 -0800193 // --- if that doesn't work, try the command file (if we have /cache).
Tao Bao570af9d2017-01-09 10:29:59 -0800194 if (args.size() == 1 && has_cache) {
Tao Baof0ed1592016-12-02 11:32:19 -0800195 std::string content;
Tao Bao7d34fa12016-12-08 18:10:48 -0800196 if (ensure_path_mounted(COMMAND_FILE) == 0 &&
197 android::base::ReadFileToString(COMMAND_FILE, &content)) {
Tao Baof0ed1592016-12-02 11:32:19 -0800198 std::vector<std::string> tokens = android::base::Split(content, "\n");
Tao Bao7d34fa12016-12-08 18:10:48 -0800199 // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
200 // COMMAND_FILE doesn't use filename as the first argument).
201 for (auto it = tokens.begin(); it != tokens.end(); it++) {
Tao Baof0ed1592016-12-02 11:32:19 -0800202 // Skip empty and '\0'-filled tokens.
203 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
204 }
205 LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800206 }
Tao Baof0ed1592016-12-02 11:32:19 -0800207 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800208
Tao Baof0ed1592016-12-02 11:32:19 -0800209 // Write the arguments (excluding the filename in args[0]) back into the
210 // bootloader control block. So the device will always boot into recovery to
211 // finish the pending work, until finish_recovery() is called.
212 std::vector<std::string> options(args.cbegin() + 1, args.cend());
Tao Bao2292db82016-12-13 21:53:31 -0800213 if (!update_bootloader_message(options, &err)) {
214 LOG(ERROR) << "Failed to set BCB message: " << err;
Tao Baof0ed1592016-12-02 11:32:19 -0800215 }
216
217 return args;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800218}
219
Tao Bao2292db82016-12-13 21:53:31 -0800220// Set the BCB to reboot back into recovery (it won't resume the install from
221// sdcard though).
222static void set_sdcard_update_bootloader_message() {
223 std::vector<std::string> options;
224 std::string err;
225 if (!update_bootloader_message(options, &err)) {
226 LOG(ERROR) << "Failed to set BCB message: " << err;
227 }
Doug Zongker34c98df2009-08-18 12:05:45 -0700228}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800229
Tao Baoec579032017-07-21 12:13:15 -0700230// Clear the recovery command and prepare to boot a (hopefully working) system,
Tianjie Xuc14d95d2016-03-24 11:50:34 -0700231// copy our log file to cache as well (for the system to read). This function is
232// idempotent: call it as many times as you like.
Tao Bao551d2c32018-05-09 20:53:13 -0700233static void finish_recovery() {
234 std::string locale = ui->GetLocale();
Tao Baoec579032017-07-21 12:13:15 -0700235 // Save the locale to cache, so if recovery is next started up without a '--locale' argument
236 // (e.g., directly from the bootloader) it will use the last-known locale.
237 if (!locale.empty() && has_cache) {
238 LOG(INFO) << "Saving locale \"" << locale << "\"";
239 if (ensure_path_mounted(LOCALE_FILE) != 0) {
240 LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
241 } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
242 PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
Doug Zongker4f33e552012-08-23 13:16:12 -0700243 }
Tao Baoec579032017-07-21 12:13:15 -0700244 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700245
Jerry Zhang152933a2018-05-02 16:56:00 -0700246 copy_logs(modified_flash, has_cache);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800247
Tao Baoec579032017-07-21 12:13:15 -0700248 // Reset to normal system boot so recovery won't cycle indefinitely.
249 std::string err;
250 if (!clear_bootloader_message(&err)) {
251 LOG(ERROR) << "Failed to clear BCB message: " << err;
252 }
253
254 // Remove the command file, so recovery won't repeat indefinitely.
255 if (has_cache) {
256 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
257 LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
Yabin Cui8b309f62016-06-24 18:22:02 -0700258 }
Tao Baoec579032017-07-21 12:13:15 -0700259 ensure_path_unmounted(CACHE_ROOT);
260 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800261
Tao Baoec579032017-07-21 12:13:15 -0700262 sync(); // For good measure.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800263}
264
Tao Bao3f5a3822016-12-13 11:14:37 -0800265struct saved_log_file {
266 std::string name;
267 struct stat sb;
268 std::string data;
269};
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700270
Elliott Hughes945548e2015-06-05 17:59:56 -0700271static bool erase_volume(const char* volume) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800272 bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
273 bool is_data = (strcmp(volume, DATA_ROOT) == 0);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700274
Tao Bao3f5a3822016-12-13 11:14:37 -0800275 ui->SetBackground(RecoveryUI::ERASING);
276 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700277
Tao Bao3f5a3822016-12-13 11:14:37 -0800278 std::vector<saved_log_file> log_files;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700279
Tao Bao3f5a3822016-12-13 11:14:37 -0800280 if (is_cache) {
281 // If we're reformatting /cache, we load any past logs
282 // (i.e. "/cache/recovery/last_*") and the current log
283 // ("/cache/recovery/log") into memory, so we can restore them after
284 // the reformat.
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700285
Tao Bao3f5a3822016-12-13 11:14:37 -0800286 ensure_path_mounted(volume);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700287
Tao Bao3f5a3822016-12-13 11:14:37 -0800288 struct dirent* de;
289 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(CACHE_LOG_DIR), closedir);
290 if (d) {
291 while ((de = readdir(d.get())) != nullptr) {
292 if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
293 std::string path = android::base::StringPrintf("%s/%s", CACHE_LOG_DIR, de->d_name);
294
295 struct stat sb;
296 if (stat(path.c_str(), &sb) == 0) {
297 // truncate files to 512kb
298 if (sb.st_size > (1 << 19)) {
299 sb.st_size = 1 << 19;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700300 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800301
302 std::string data(sb.st_size, '\0');
Tianjie Xude6735e2017-07-10 15:13:33 -0700303 FILE* f = fopen(path.c_str(), "rbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800304 fread(&data[0], 1, data.size(), f);
305 fclose(f);
306
307 log_files.emplace_back(saved_log_file{ path, sb, data });
308 }
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700309 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800310 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800311 } else {
Tao Bao3f5a3822016-12-13 11:14:37 -0800312 if (errno != ENOENT) {
313 PLOG(ERROR) << "Failed to opendir " << CACHE_LOG_DIR;
314 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800315 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800316 }
Doug Zongkerd0181b82011-10-19 10:51:12 -0700317
Tao Bao3f5a3822016-12-13 11:14:37 -0800318 ui->Print("Formatting %s...\n", volume);
319
320 ensure_path_unmounted(volume);
321
322 int result;
Tao Bao3f5a3822016-12-13 11:14:37 -0800323 if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700324 static constexpr const char* CONVERT_FBE_DIR = "/tmp/convert_fbe";
325 static constexpr const char* CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
326 // Create convert_fbe breadcrumb file to signal init to convert to file based encryption, not
327 // full disk encryption.
Tao Bao3f5a3822016-12-13 11:14:37 -0800328 if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700329 PLOG(ERROR) << "Failed to mkdir " << CONVERT_FBE_DIR;
330 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800331 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700332 FILE* f = fopen(CONVERT_FBE_FILE, "wbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800333 if (!f) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700334 PLOG(ERROR) << "Failed to convert to file encryption";
335 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800336 }
337 fclose(f);
338 result = format_volume(volume, CONVERT_FBE_DIR);
339 remove(CONVERT_FBE_FILE);
340 rmdir(CONVERT_FBE_DIR);
341 } else {
342 result = format_volume(volume);
343 }
344
345 if (is_cache) {
346 // Re-create the log dir and write back the log entries.
347 if (ensure_path_mounted(CACHE_LOG_DIR) == 0 &&
Tao Baoac3d1ed2017-07-23 00:01:02 -0700348 mkdir_recursively(CACHE_LOG_DIR, 0777, false, sehandle) == 0) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800349 for (const auto& log : log_files) {
350 if (!android::base::WriteStringToFile(log.data, log.name, log.sb.st_mode, log.sb.st_uid,
351 log.sb.st_gid)) {
352 PLOG(ERROR) << "Failed to write to " << log.name;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700353 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800354 }
355 } else {
356 PLOG(ERROR) << "Failed to mount / create " << CACHE_LOG_DIR;
Doug Zongker2c3539e2010-09-29 13:21:30 -0700357 }
358
Tao Bao3f5a3822016-12-13 11:14:37 -0800359 // Any part of the log we'd copied to cache is now gone.
360 // Reset the pointer so we copy from the beginning of the temp
361 // log.
Jerry Zhang152933a2018-05-02 16:56:00 -0700362 reset_tmplog_offset();
363 copy_logs(modified_flash, has_cache);
Tao Bao3f5a3822016-12-13 11:14:37 -0800364 }
365
366 return (result == 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800367}
368
Tao Baoc4a18ef2017-02-10 00:13:30 -0800369// Returns the selected filename, or an empty string.
370static std::string browse_directory(const std::string& path, Device* device) {
371 ensure_path_mounted(path.c_str());
Doug Zongker8674a722010-09-15 11:08:23 -0700372
Tao Baoc4a18ef2017-02-10 00:13:30 -0800373 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path.c_str()), closedir);
374 if (!d) {
375 PLOG(ERROR) << "error opening " << path;
376 return "";
377 }
Doug Zongkerc18eeb82010-09-21 16:49:26 -0700378
Tao Baoc4a18ef2017-02-10 00:13:30 -0800379 std::vector<std::string> dirs;
Tao Bao1fe1afe2018-05-01 15:56:05 -0700380 std::vector<std::string> entries{ "../" }; // "../" is always the first entry.
Tao Baoc4a18ef2017-02-10 00:13:30 -0800381
382 dirent* de;
383 while ((de = readdir(d.get())) != nullptr) {
384 std::string name(de->d_name);
385
386 if (de->d_type == DT_DIR) {
387 // Skip "." and ".." entries.
388 if (name == "." || name == "..") continue;
389 dirs.push_back(name + "/");
390 } else if (de->d_type == DT_REG && android::base::EndsWithIgnoreCase(name, ".zip")) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700391 entries.push_back(name);
Tao Baoc4a18ef2017-02-10 00:13:30 -0800392 }
393 }
394
395 std::sort(dirs.begin(), dirs.end());
Tao Bao1fe1afe2018-05-01 15:56:05 -0700396 std::sort(entries.begin(), entries.end());
Tao Baoc4a18ef2017-02-10 00:13:30 -0800397
Tao Bao1fe1afe2018-05-01 15:56:05 -0700398 // Append dirs to the entries list.
399 entries.insert(entries.end(), dirs.begin(), dirs.end());
Tao Baoc4a18ef2017-02-10 00:13:30 -0800400
Tao Bao1fe1afe2018-05-01 15:56:05 -0700401 std::vector<std::string> headers{ "Choose a package to install:", path };
Tao Baoc4a18ef2017-02-10 00:13:30 -0800402
Tao Bao1fe1afe2018-05-01 15:56:05 -0700403 size_t chosen_item = 0;
Tao Baoc4a18ef2017-02-10 00:13:30 -0800404 while (true) {
Tao Bao3aec6962018-04-20 09:24:58 -0700405 chosen_item = ui->ShowMenu(
406 headers, entries, chosen_item, true,
407 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Baoc4a18ef2017-02-10 00:13:30 -0800408
Tao Bao1fe1afe2018-05-01 15:56:05 -0700409 const std::string& item = entries[chosen_item];
Tao Baoc4a18ef2017-02-10 00:13:30 -0800410 if (chosen_item == 0) {
411 // Go up but continue browsing (if the caller is browse_directory).
412 return "";
Doug Zongker8674a722010-09-15 11:08:23 -0700413 }
414
Tao Baoc4a18ef2017-02-10 00:13:30 -0800415 std::string new_path = path + "/" + item;
416 if (new_path.back() == '/') {
417 // Recurse down into a subdirectory.
418 new_path.pop_back();
419 std::string result = browse_directory(new_path, device);
420 if (!result.empty()) return result;
421 } else {
422 // Selected a zip file: return the path to the caller.
423 return new_path;
Doug Zongker8674a722010-09-15 11:08:23 -0700424 }
Tao Baoc4a18ef2017-02-10 00:13:30 -0800425 }
Doug Zongker8674a722010-09-15 11:08:23 -0700426
Tao Baoc4a18ef2017-02-10 00:13:30 -0800427 // Unreachable.
Doug Zongker8674a722010-09-15 11:08:23 -0700428}
429
Elliott Hughes30694c92015-03-25 15:16:51 -0700430static bool yes_no(Device* device, const char* question1, const char* question2) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700431 std::vector<std::string> headers{ question1, question2 };
432 std::vector<std::string> items{ " No", " Yes" };
Doug Zongkerddd6a282009-06-09 12:22:33 -0700433
Tao Bao1fe1afe2018-05-01 15:56:05 -0700434 size_t chosen_item = ui->ShowMenu(
Tao Bao3aec6962018-04-20 09:24:58 -0700435 headers, items, 0, true,
436 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
437 return (chosen_item == 1);
Elliott Hughes30694c92015-03-25 15:16:51 -0700438}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800439
Paul Crowley08404b42016-12-19 13:04:23 -0800440static bool ask_to_wipe_data(Device* device) {
Tao Bao3aec6962018-04-20 09:24:58 -0700441 return yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!");
Paul Crowley08404b42016-12-19 13:04:23 -0800442}
Doug Zongker1066d2c2009-04-01 13:57:40 -0700443
Paul Crowley08404b42016-12-19 13:04:23 -0800444// Return true on success.
445static bool wipe_data(Device* device) {
Tao Bao682c34b2015-04-07 17:16:35 -0700446 modified_flash = true;
447
Doug Zongker211aebc2011-10-28 15:13:10 -0700448 ui->Print("\n-- Wiping data...\n");
Paul Crowley3b4d5162016-06-08 13:51:41 -0700449 bool success = device->PreWipeData();
450 if (success) {
451 success &= erase_volume(DATA_ROOT);
452 if (has_cache) {
453 success &= erase_volume(CACHE_ROOT);
454 }
455 if (volume_for_mount_point(METADATA_ROOT) != nullptr) {
456 success &= erase_volume(METADATA_ROOT);
457 }
458 }
459 if (success) {
460 success &= device->PostWipeData();
461 }
Elliott Hughes945548e2015-06-05 17:59:56 -0700462 ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
463 return success;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700464}
465
Paul Crowley08404b42016-12-19 13:04:23 -0800466static bool prompt_and_wipe_data(Device* device) {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700467 // Use a single string and let ScreenRecoveryUI handles the wrapping.
Tao Bao1fe1afe2018-05-01 15:56:05 -0700468 std::vector<std::string> headers{
Tao Bao2bbc6d62017-08-13 23:48:55 -0700469 "Can't load Android system. Your data may be corrupt. "
470 "If you continue to get this message, you may need to "
471 "perform a factory data reset and erase all user data "
Paul Crowley31ac0c62017-03-23 12:32:40 -0700472 "stored on this device.",
Tao Baofc5499f2017-02-23 19:06:53 -0800473 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700474 // clang-format off
475 std::vector<std::string> items {
Paul Crowley31ac0c62017-03-23 12:32:40 -0700476 "Try again",
477 "Factory data reset",
Tao Baofc5499f2017-02-23 19:06:53 -0800478 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700479 // clang-format on
Tao Baofc5499f2017-02-23 19:06:53 -0800480 for (;;) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700481 size_t chosen_item = ui->ShowMenu(
Tao Bao3aec6962018-04-20 09:24:58 -0700482 headers, items, 0, true,
483 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Baofc5499f2017-02-23 19:06:53 -0800484 if (chosen_item != 1) {
485 return true; // Just reboot, no wipe; not a failure, user asked for it
Paul Crowley08404b42016-12-19 13:04:23 -0800486 }
Tao Baofc5499f2017-02-23 19:06:53 -0800487 if (ask_to_wipe_data(device)) {
488 return wipe_data(device);
489 }
490 }
Paul Crowley08404b42016-12-19 13:04:23 -0800491}
492
Tao Baoe39a9bc2015-03-31 12:19:05 -0700493// Return true on success.
494static bool wipe_cache(bool should_confirm, Device* device) {
Tao Bao26112e52016-02-25 12:29:40 -0800495 if (!has_cache) {
496 ui->Print("No /cache partition found.\n");
497 return false;
498 }
499
Elliott Hughes30694c92015-03-25 15:16:51 -0700500 if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
Tao Baoe39a9bc2015-03-31 12:19:05 -0700501 return false;
Elliott Hughes30694c92015-03-25 15:16:51 -0700502 }
503
Tao Bao682c34b2015-04-07 17:16:35 -0700504 modified_flash = true;
505
Elliott Hughes30694c92015-03-25 15:16:51 -0700506 ui->Print("\n-- Wiping cache...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700507 bool success = erase_volume("/cache");
508 ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
509 return success;
Elliott Hughes30694c92015-03-25 15:16:51 -0700510}
511
Tao Bao1b2a98b2017-03-24 10:45:34 -0700512// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
513// BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
Tao Bao862a4c12016-06-02 11:16:50 -0700514static bool secure_wipe_partition(const std::string& partition) {
Tao Bao1b2a98b2017-03-24 10:45:34 -0700515 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
516 if (fd == -1) {
517 PLOG(ERROR) << "Failed to open \"" << partition << "\"";
518 return false;
519 }
520
521 uint64_t range[2] = { 0, 0 };
522 if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
523 PLOG(ERROR) << "Failed to get partition size";
524 return false;
525 }
526 LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
527
528 LOG(INFO) << " Trying BLKSECDISCARD...";
529 if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
530 PLOG(WARNING) << " Failed";
531
532 // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
533 unsigned int zeroes;
534 if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
535 LOG(INFO) << " Trying BLKDISCARD...";
536 if (ioctl(fd, BLKDISCARD, &range) == -1) {
537 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700538 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700539 }
540 } else {
541 LOG(INFO) << " Trying BLKZEROOUT...";
542 if (ioctl(fd, BLKZEROOUT, &range) == -1) {
543 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700544 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700545 }
Tao Bao862a4c12016-06-02 11:16:50 -0700546 }
Tao Bao1b2a98b2017-03-24 10:45:34 -0700547 }
Tao Bao862a4c12016-06-02 11:16:50 -0700548
Tao Bao1b2a98b2017-03-24 10:45:34 -0700549 LOG(INFO) << " Done";
550 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700551}
552
Yabin Cuifd99a312016-06-09 14:09:39 -0700553// Check if the wipe package matches expectation:
554// 1. verify the package.
555// 2. check metadata (ota-type, pre-device and serial number if having one).
556static bool check_wipe_package(size_t wipe_package_size) {
557 if (wipe_package_size == 0) {
558 LOG(ERROR) << "wipe_package_size is zero";
559 return false;
560 }
561 std::string wipe_package;
562 std::string err_str;
563 if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
564 PLOG(ERROR) << "Failed to read wipe package";
565 return false;
566 }
567 if (!verify_package(reinterpret_cast<const unsigned char*>(wipe_package.data()),
568 wipe_package.size())) {
569 LOG(ERROR) << "Failed to verify package";
570 return false;
571 }
572
573 // Extract metadata
574 ZipArchiveHandle zip;
Tao Baoefc35592017-01-08 22:45:47 -0800575 int err = OpenArchiveFromMemory(static_cast<void*>(&wipe_package[0]), wipe_package.size(),
576 "wipe_package", &zip);
Yabin Cuifd99a312016-06-09 14:09:39 -0700577 if (err != 0) {
578 LOG(ERROR) << "Can't open wipe package : " << ErrorCodeString(err);
579 return false;
580 }
581 std::string metadata;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700582 if (!read_metadata_from_package(zip, &metadata)) {
Yabin Cuifd99a312016-06-09 14:09:39 -0700583 CloseArchive(zip);
584 return false;
585 }
586 CloseArchive(zip);
587
588 // Check metadata
589 std::vector<std::string> lines = android::base::Split(metadata, "\n");
590 bool ota_type_matched = false;
591 bool device_type_matched = false;
592 bool has_serial_number = false;
593 bool serial_number_matched = false;
594 for (const auto& line : lines) {
595 if (line == "ota-type=BRICK") {
596 ota_type_matched = true;
597 } else if (android::base::StartsWith(line, "pre-device=")) {
598 std::string device_type = line.substr(strlen("pre-device="));
Tao Baoefc35592017-01-08 22:45:47 -0800599 std::string real_device_type = android::base::GetProperty("ro.build.product", "");
Yabin Cuifd99a312016-06-09 14:09:39 -0700600 device_type_matched = (device_type == real_device_type);
601 } else if (android::base::StartsWith(line, "serialno=")) {
602 std::string serial_no = line.substr(strlen("serialno="));
Tao Baoefc35592017-01-08 22:45:47 -0800603 std::string real_serial_no = android::base::GetProperty("ro.serialno", "");
Yabin Cuifd99a312016-06-09 14:09:39 -0700604 has_serial_number = true;
605 serial_number_matched = (serial_no == real_serial_no);
606 }
607 }
608 return ota_type_matched && device_type_matched && (!has_serial_number || serial_number_matched);
609}
610
Tao Baoaac9d9f2018-04-29 23:38:59 -0700611// Wipes the current A/B device, with a secure wipe of all the partitions in RECOVERY_WIPE.
Yabin Cuifd99a312016-06-09 14:09:39 -0700612static bool wipe_ab_device(size_t wipe_package_size) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700613 ui->SetBackground(RecoveryUI::ERASING);
614 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Tao Bao862a4c12016-06-02 11:16:50 -0700615
Tao Baoaac9d9f2018-04-29 23:38:59 -0700616 if (!check_wipe_package(wipe_package_size)) {
617 LOG(ERROR) << "Failed to verify wipe package";
618 return false;
619 }
620 static constexpr const char* RECOVERY_WIPE = "/etc/recovery.wipe";
621 std::string partition_list;
622 if (!android::base::ReadFileToString(RECOVERY_WIPE, &partition_list)) {
623 LOG(ERROR) << "failed to read \"" << RECOVERY_WIPE << "\"";
624 return false;
625 }
626
627 std::vector<std::string> lines = android::base::Split(partition_list, "\n");
628 for (const std::string& line : lines) {
629 std::string partition = android::base::Trim(line);
630 // Ignore '#' comment or empty lines.
631 if (android::base::StartsWith(partition, "#") || partition.empty()) {
632 continue;
Tao Bao862a4c12016-06-02 11:16:50 -0700633 }
634
Tao Baoaac9d9f2018-04-29 23:38:59 -0700635 // Proceed anyway even if it fails to wipe some partition.
636 secure_wipe_partition(partition);
637 }
638 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700639}
640
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700641static void choose_recovery_file(Device* device) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800642 std::vector<std::string> entries;
643 if (has_cache) {
644 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
645 auto add_to_entries = [&](const char* filename) {
646 std::string log_file(filename);
647 if (i > 0) {
648 log_file += "." + std::to_string(i);
Tao Baobef39712015-05-04 18:50:27 -0700649 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800650
651 if (ensure_path_mounted(log_file.c_str()) == 0 && access(log_file.c_str(), R_OK) == 0) {
652 entries.push_back(std::move(log_file));
653 }
654 };
655
656 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
657 add_to_entries(LAST_LOG_FILE);
658
659 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
660 add_to_entries(LAST_KMSG_FILE);
661 }
662 } else {
663 // If cache partition is not found, view /tmp/recovery.log instead.
Tao Bao641fa972018-04-25 18:59:40 -0700664 if (access(Paths::Get().temporary_log_file().c_str(), R_OK) == -1) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800665 return;
Tianjie Xua54f75e2016-08-17 12:02:46 -0700666 } else {
Tao Bao641fa972018-04-25 18:59:40 -0700667 entries.push_back(Paths::Get().temporary_log_file());
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700668 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800669 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700670
Tao Bao08fc6be2017-03-07 00:56:27 -0800671 entries.push_back("Back");
Elliott Hughesc0491632015-05-06 12:40:05 -0700672
Tao Bao1fe1afe2018-05-01 15:56:05 -0700673 std::vector<std::string> headers{ "Select file to view" };
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700674
Tao Bao1fe1afe2018-05-01 15:56:05 -0700675 size_t chosen_item = 0;
Tao Bao08fc6be2017-03-07 00:56:27 -0800676 while (true) {
Tao Bao3aec6962018-04-20 09:24:58 -0700677 chosen_item = ui->ShowMenu(
Tao Bao1fe1afe2018-05-01 15:56:05 -0700678 headers, entries, chosen_item, true,
Tao Bao3aec6962018-04-20 09:24:58 -0700679 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Bao08fc6be2017-03-07 00:56:27 -0800680 if (entries[chosen_item] == "Back") break;
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700681
Tao Bao1d156b92018-05-02 12:43:18 -0700682 ui->ShowFile(entries[chosen_item]);
Tao Bao08fc6be2017-03-07 00:56:27 -0800683 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700684}
685
Tao Baodb7e8982017-03-06 23:53:16 -0800686static void run_graphics_test() {
687 // Switch to graphics screen.
688 ui->ShowText(false);
Elliott Hughes498cda62016-04-14 16:49:04 -0700689
Tao Baodb7e8982017-03-06 23:53:16 -0800690 ui->SetProgressType(RecoveryUI::INDETERMINATE);
691 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
692 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700693
Tao Baodb7e8982017-03-06 23:53:16 -0800694 ui->SetBackground(RecoveryUI::ERROR);
695 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700696
Tao Baodb7e8982017-03-06 23:53:16 -0800697 ui->SetBackground(RecoveryUI::NO_COMMAND);
698 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700699
Tao Baodb7e8982017-03-06 23:53:16 -0800700 ui->SetBackground(RecoveryUI::ERASING);
701 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700702
Tao Baodb7e8982017-03-06 23:53:16 -0800703 // Calling SetBackground() after SetStage() to trigger a redraw.
704 ui->SetStage(1, 3);
705 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
706 sleep(1);
707 ui->SetStage(2, 3);
708 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
709 sleep(1);
710 ui->SetStage(3, 3);
711 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
712 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700713
Tao Baodb7e8982017-03-06 23:53:16 -0800714 ui->SetStage(-1, -1);
715 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Elliott Hughes498cda62016-04-14 16:49:04 -0700716
Tao Baodb7e8982017-03-06 23:53:16 -0800717 ui->SetProgressType(RecoveryUI::DETERMINATE);
718 ui->ShowProgress(1.0, 10.0);
719 float fraction = 0.0;
720 for (size_t i = 0; i < 100; ++i) {
721 fraction += .01;
722 ui->SetProgress(fraction);
723 usleep(100000);
724 }
725
726 ui->ShowText(true);
Elliott Hughes498cda62016-04-14 16:49:04 -0700727}
728
Tao Baocdcf28f2016-01-13 15:05:20 -0800729// How long (in seconds) we wait for the fuse-provided package file to
730// appear, before timing out.
731#define SDCARD_INSTALL_TIMEOUT 10
732
Tao Bao145d8612015-03-25 15:51:15 -0700733static int apply_from_sdcard(Device* device, bool* wipe_cache) {
Tao Bao682c34b2015-04-07 17:16:35 -0700734 modified_flash = true;
735
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000736 if (ensure_path_mounted(SDCARD_ROOT) != 0) {
737 ui->Print("\n-- Couldn't mount %s.\n", SDCARD_ROOT);
738 return INSTALL_ERROR;
739 }
740
Tao Baoc4a18ef2017-02-10 00:13:30 -0800741 std::string path = browse_directory(SDCARD_ROOT, device);
742 if (path.empty()) {
Elliott Hughes018ed312015-04-08 16:51:36 -0700743 ui->Print("\n-- No package file selected.\n");
caozhiyuanb4effb92015-06-10 16:46:38 +0800744 ensure_path_unmounted(SDCARD_ROOT);
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000745 return INSTALL_ERROR;
746 }
747
Tao Baoc4a18ef2017-02-10 00:13:30 -0800748 ui->Print("\n-- Install %s ...\n", path.c_str());
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000749 set_sdcard_update_bootloader_message();
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000750
Tao Baocdcf28f2016-01-13 15:05:20 -0800751 // We used to use fuse in a thread as opposed to a process. Since accessing
752 // through fuse involves going from kernel to userspace to kernel, it leads
753 // to deadlock when a page fault occurs. (Bug: 26313124)
754 pid_t child;
755 if ((child = fork()) == 0) {
Tao Baoc4a18ef2017-02-10 00:13:30 -0800756 bool status = start_sdcard_fuse(path.c_str());
Tao Baocdcf28f2016-01-13 15:05:20 -0800757
758 _exit(status ? EXIT_SUCCESS : EXIT_FAILURE);
759 }
760
761 // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the fuse in child
762 // process is ready.
763 int result = INSTALL_ERROR;
764 int status;
765 bool waited = false;
766 for (int i = 0; i < SDCARD_INSTALL_TIMEOUT; ++i) {
767 if (waitpid(child, &status, WNOHANG) == -1) {
768 result = INSTALL_ERROR;
769 waited = true;
770 break;
771 }
772
773 struct stat sb;
774 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &sb) == -1) {
775 if (errno == ENOENT && i < SDCARD_INSTALL_TIMEOUT-1) {
776 sleep(1);
777 continue;
778 } else {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700779 LOG(ERROR) << "Timed out waiting for the fuse-provided package.";
Tao Baocdcf28f2016-01-13 15:05:20 -0800780 result = INSTALL_ERROR;
781 kill(child, SIGKILL);
782 break;
783 }
784 }
785
Tao Bao641fa972018-04-25 18:59:40 -0700786 result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache, false, 0 /*retry_count*/);
Tao Baocdcf28f2016-01-13 15:05:20 -0800787 break;
788 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000789
Tao Baocdcf28f2016-01-13 15:05:20 -0800790 if (!waited) {
791 // Calling stat() on this magic filename signals the fuse
792 // filesystem to shut down.
793 struct stat sb;
794 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &sb);
795
796 waitpid(child, &status, 0);
797 }
798
799 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700800 LOG(ERROR) << "Error exit from the fuse process: " << WEXITSTATUS(status);
Tao Baocdcf28f2016-01-13 15:05:20 -0800801 }
802
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000803 ensure_path_unmounted(SDCARD_ROOT);
Tao Baocdcf28f2016-01-13 15:05:20 -0800804 return result;
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000805}
806
Tao Bao50dd5322017-03-07 14:57:04 -0800807// Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
808// which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
809static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
810 for (;;) {
Tao Bao551d2c32018-05-09 20:53:13 -0700811 finish_recovery();
Tao Bao50dd5322017-03-07 14:57:04 -0800812 switch (status) {
813 case INSTALL_SUCCESS:
814 case INSTALL_NONE:
815 ui->SetBackground(RecoveryUI::NO_COMMAND);
816 break;
Doug Zongker6c8553d2012-09-24 10:40:47 -0700817
Tao Bao50dd5322017-03-07 14:57:04 -0800818 case INSTALL_ERROR:
819 case INSTALL_CORRUPT:
820 ui->SetBackground(RecoveryUI::ERROR);
821 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800822 }
Tao Bao50dd5322017-03-07 14:57:04 -0800823 ui->SetProgressType(RecoveryUI::EMPTY);
824
Tao Bao1fe1afe2018-05-01 15:56:05 -0700825 size_t chosen_item = ui->ShowMenu(
826 {}, device->GetMenuItems(), 0, false,
Tao Bao3aec6962018-04-20 09:24:58 -0700827 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Bao50dd5322017-03-07 14:57:04 -0800828
829 // Device-specific code may take some action here. It may return one of the core actions
830 // handled in the switch statement below.
Tao Bao1fe1afe2018-05-01 15:56:05 -0700831 Device::BuiltinAction chosen_action = (chosen_item == static_cast<size_t>(-1))
832 ? Device::REBOOT
833 : device->InvokeMenuItem(chosen_item);
Tao Bao50dd5322017-03-07 14:57:04 -0800834
835 bool should_wipe_cache = false;
836 switch (chosen_action) {
837 case Device::NO_ACTION:
838 break;
839
840 case Device::REBOOT:
841 case Device::SHUTDOWN:
842 case Device::REBOOT_BOOTLOADER:
843 return chosen_action;
844
845 case Device::WIPE_DATA:
846 if (ui->IsTextVisible()) {
847 if (ask_to_wipe_data(device)) {
848 wipe_data(device);
849 }
850 } else {
851 wipe_data(device);
852 return Device::NO_ACTION;
853 }
854 break;
855
856 case Device::WIPE_CACHE:
857 wipe_cache(ui->IsTextVisible(), device);
858 if (!ui->IsTextVisible()) return Device::NO_ACTION;
859 break;
860
861 case Device::APPLY_ADB_SIDELOAD:
862 case Device::APPLY_SDCARD:
863 {
864 bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD);
865 if (adb) {
Tao Bao641fa972018-04-25 18:59:40 -0700866 status = apply_from_adb(&should_wipe_cache);
Tao Bao50dd5322017-03-07 14:57:04 -0800867 } else {
868 status = apply_from_sdcard(device, &should_wipe_cache);
869 }
870
871 if (status == INSTALL_SUCCESS && should_wipe_cache) {
872 if (!wipe_cache(false, device)) {
873 status = INSTALL_ERROR;
874 }
875 }
876
877 if (status != INSTALL_SUCCESS) {
878 ui->SetBackground(RecoveryUI::ERROR);
879 ui->Print("Installation aborted.\n");
Jerry Zhang152933a2018-05-02 16:56:00 -0700880 copy_logs(modified_flash, has_cache);
Tao Bao50dd5322017-03-07 14:57:04 -0800881 } else if (!ui->IsTextVisible()) {
882 return Device::NO_ACTION; // reboot if logs aren't visible
883 } else {
884 ui->Print("\nInstall from %s complete.\n", adb ? "ADB" : "SD card");
885 }
886 }
887 break;
888
889 case Device::VIEW_RECOVERY_LOGS:
890 choose_recovery_file(device);
891 break;
892
893 case Device::RUN_GRAPHICS_TEST:
894 run_graphics_test();
895 break;
896
Tianjie Xu29d55752017-09-20 17:53:46 -0700897 case Device::RUN_LOCALE_TEST: {
898 ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
Tao Bao39c49182018-05-07 22:50:33 -0700899 screen_ui->CheckBackgroundTextImages();
Tianjie Xu29d55752017-09-20 17:53:46 -0700900 break;
901 }
Tao Bao50dd5322017-03-07 14:57:04 -0800902 case Device::MOUNT_SYSTEM:
903 // For a system image built with the root directory (i.e. system_root_image == "true"), we
904 // mount it to /system_root, and symlink /system to /system_root/system to make adb shell
905 // work (the symlink is created through the build system). (Bug: 22855115)
906 if (android::base::GetBoolProperty("ro.build.system_root_image", false)) {
907 if (ensure_path_mounted_at("/", "/system_root") != -1) {
908 ui->Print("Mounted /system.\n");
909 }
910 } else {
911 if (ensure_path_mounted("/system") != -1) {
912 ui->Print("Mounted /system.\n");
913 }
914 }
915 break;
916 }
917 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800918}
919
Tao Bao99f0d9e2016-10-13 12:46:38 -0700920static void print_property(const char* key, const char* name, void* /* cookie */) {
921 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800922}
923
Tao Baoac9d94d2016-11-03 11:37:15 -0700924static std::string load_locale_from_cache() {
925 if (ensure_path_mounted(LOCALE_FILE) != 0) {
926 LOG(ERROR) << "Can't mount " << LOCALE_FILE;
927 return "";
Doug Zongker02ec6b82012-08-22 17:26:40 -0700928 }
Tao Baoac9d94d2016-11-03 11:37:15 -0700929
930 std::string content;
931 if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
932 PLOG(ERROR) << "Can't read " << LOCALE_FILE;
933 return "";
934 }
935
936 return android::base::Trim(content);
Doug Zongker02ec6b82012-08-22 17:26:40 -0700937}
938
Tao Baoac9d94d2016-11-03 11:37:15 -0700939void ui_print(const char* format, ...) {
940 std::string buffer;
Doug Zongker7c3ae452013-05-14 11:03:02 -0700941 va_list ap;
942 va_start(ap, format);
Tao Baoac9d94d2016-11-03 11:37:15 -0700943 android::base::StringAppendV(&buffer, format, ap);
Doug Zongker7c3ae452013-05-14 11:03:02 -0700944 va_end(ap);
945
Tao Baoac9d94d2016-11-03 11:37:15 -0700946 if (ui != nullptr) {
947 ui->Print("%s", buffer.c_str());
Doug Zongker7c3ae452013-05-14 11:03:02 -0700948 } else {
Tao Baoac9d94d2016-11-03 11:37:15 -0700949 fputs(buffer.c_str(), stdout);
Doug Zongker7c3ae452013-05-14 11:03:02 -0700950 }
951}
952
Tao Baof2ea6d72018-04-26 10:40:36 -0700953static bool is_battery_ok(int* required_battery_level) {
954 struct healthd_config healthd_config = {
955 .batteryStatusPath = android::String8(android::String8::kEmptyString),
956 .batteryHealthPath = android::String8(android::String8::kEmptyString),
957 .batteryPresentPath = android::String8(android::String8::kEmptyString),
958 .batteryCapacityPath = android::String8(android::String8::kEmptyString),
959 .batteryVoltagePath = android::String8(android::String8::kEmptyString),
960 .batteryTemperaturePath = android::String8(android::String8::kEmptyString),
961 .batteryTechnologyPath = android::String8(android::String8::kEmptyString),
962 .batteryCurrentNowPath = android::String8(android::String8::kEmptyString),
963 .batteryCurrentAvgPath = android::String8(android::String8::kEmptyString),
964 .batteryChargeCounterPath = android::String8(android::String8::kEmptyString),
965 .batteryFullChargePath = android::String8(android::String8::kEmptyString),
966 .batteryCycleCountPath = android::String8(android::String8::kEmptyString),
967 .energyCounter = nullptr,
968 .boot_min_cap = 0,
969 .screen_on = nullptr
970 };
971 healthd_board_init(&healthd_config);
Yabin Cui99281df2016-02-17 12:21:52 -0800972
Tao Baof2ea6d72018-04-26 10:40:36 -0700973 android::BatteryMonitor monitor;
974 monitor.init(&healthd_config);
Yabin Cui99281df2016-02-17 12:21:52 -0800975
Tao Baof2ea6d72018-04-26 10:40:36 -0700976 static constexpr int BATTERY_READ_TIMEOUT_IN_SEC = 10;
977 int wait_second = 0;
978 while (true) {
979 int charge_status = monitor.getChargeStatus();
980 // Treat unknown status as charged.
981 bool charged = (charge_status != android::BATTERY_STATUS_DISCHARGING &&
982 charge_status != android::BATTERY_STATUS_NOT_CHARGING);
983 android::BatteryProperty capacity;
984 android::status_t status = monitor.getProperty(android::BATTERY_PROP_CAPACITY, &capacity);
985 ui_print("charge_status %d, charged %d, status %d, capacity %" PRId64 "\n", charge_status,
986 charged, status, capacity.valueInt64);
987 // At startup, the battery drivers in devices like N5X/N6P take some time to load
988 // the battery profile. Before the load finishes, it reports value 50 as a fake
989 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
990 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
991 if (status == 0 && capacity.valueInt64 == 50) {
992 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
993 sleep(1);
994 wait_second++;
995 continue;
996 }
Yabin Cui99281df2016-02-17 12:21:52 -0800997 }
Tao Baof2ea6d72018-04-26 10:40:36 -0700998 // If we can't read battery percentage, it may be a device without battery. In this situation,
999 // use 100 as a fake battery percentage.
1000 if (status != 0) {
1001 capacity.valueInt64 = 100;
1002 }
1003
1004 // GmsCore enters recovery mode to install package when having enough battery percentage.
1005 // Normally, the threshold is 40% without charger and 20% with charger. So we should check
1006 // battery with a slightly lower limitation.
1007 static constexpr int BATTERY_OK_PERCENTAGE = 20;
1008 static constexpr int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
1009 *required_battery_level = charged ? BATTERY_WITH_CHARGER_OK_PERCENTAGE : BATTERY_OK_PERCENTAGE;
1010 return capacity.valueInt64 >= *required_battery_level;
1011 }
Yabin Cui99281df2016-02-17 12:21:52 -08001012}
1013
Tianjie Xu99b73be2017-11-28 17:23:06 -08001014// Set the retry count to |retry_count| in BCB.
Tianjie Xu72449c92017-05-16 18:07:31 -07001015static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
1016 std::vector<std::string> options;
1017 for (const auto& arg : args) {
1018 if (!android::base::StartsWith(arg, "--retry_count")) {
1019 options.push_back(arg);
Tianjie Xu3c62b672016-02-05 18:25:58 -08001020 }
Tianjie Xu72449c92017-05-16 18:07:31 -07001021 }
Tianjie Xu3c62b672016-02-05 18:25:58 -08001022
Tianjie Xu99b73be2017-11-28 17:23:06 -08001023 // Update the retry counter in BCB.
1024 options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
Tianjie Xu72449c92017-05-16 18:07:31 -07001025 std::string err;
1026 if (!update_bootloader_message(options, &err)) {
1027 LOG(ERROR) << err;
1028 }
Tianjie Xu3c62b672016-02-05 18:25:58 -08001029}
1030
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001031static bool bootreason_in_blacklist() {
Tao Baoefc35592017-01-08 22:45:47 -08001032 std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
1033 if (!bootreason.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -07001034 // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
1035 static const std::vector<std::string> kBootreasonBlacklist{
1036 "kernel_panic",
1037 "Panic",
1038 };
1039 for (const auto& str : kBootreasonBlacklist) {
1040 if (android::base::EqualsIgnoreCase(str, bootreason)) return true;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001041 }
Tao Baoefc35592017-01-08 22:45:47 -08001042 }
1043 return false;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001044}
1045
Tao Bao641fa972018-04-25 18:59:40 -07001046static void log_failure_code(ErrorCode code, const std::string& update_package) {
1047 std::vector<std::string> log_buffer = {
1048 update_package,
1049 "0", // install result
1050 "error: " + std::to_string(code),
1051 };
1052 std::string log_content = android::base::Join(log_buffer, "\n");
1053 const std::string& install_file = Paths::Get().temporary_install_file();
1054 if (!android::base::WriteStringToFile(log_content, install_file)) {
1055 PLOG(ERROR) << "Failed to write " << install_file;
1056 }
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001057
Tao Bao641fa972018-04-25 18:59:40 -07001058 // Also write the info into last_log.
1059 LOG(INFO) << log_content;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001060}
1061
Tao Bao6d99d4b2018-04-25 16:47:04 -07001062int start_recovery(int argc, char** argv) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001063 time_t start = time(nullptr);
1064
Tianjie Xu99b73be2017-11-28 17:23:06 -08001065 printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
1066
1067 load_volume_table();
1068 has_cache = volume_for_mount_point(CACHE_ROOT) != nullptr;
1069
1070 std::vector<std::string> args = get_args(argc, argv);
1071 std::vector<char*> args_to_parse(args.size());
1072 std::transform(args.cbegin(), args.cend(), args_to_parse.begin(),
1073 [](const std::string& arg) { return const_cast<char*>(arg.c_str()); });
1074
Tao Baof9f17342018-04-27 10:44:04 -07001075 static constexpr struct option OPTIONS[] = {
1076 { "just_exit", no_argument, nullptr, 'x' },
1077 { "locale", required_argument, nullptr, 0 },
1078 { "prompt_and_wipe_data", no_argument, nullptr, 0 },
1079 { "reason", required_argument, nullptr, 0 },
1080 { "retry_count", required_argument, nullptr, 0 },
1081 { "security", no_argument, nullptr, 0 },
1082 { "show_text", no_argument, nullptr, 't' },
1083 { "shutdown_after", no_argument, nullptr, 0 },
1084 { "sideload", no_argument, nullptr, 0 },
1085 { "sideload_auto_reboot", no_argument, nullptr, 0 },
1086 { "update_package", required_argument, nullptr, 0 },
1087 { "wipe_ab", no_argument, nullptr, 0 },
1088 { "wipe_cache", no_argument, nullptr, 0 },
1089 { "wipe_data", no_argument, nullptr, 0 },
1090 { "wipe_package_size", required_argument, nullptr, 0 },
1091 { nullptr, 0, nullptr, 0 },
1092 };
1093
Tianjie Xu99b73be2017-11-28 17:23:06 -08001094 const char* update_package = nullptr;
1095 bool should_wipe_data = false;
1096 bool should_prompt_and_wipe_data = false;
1097 bool should_wipe_cache = false;
1098 bool should_wipe_ab = false;
1099 size_t wipe_package_size = 0;
1100 bool show_text = false;
1101 bool sideload = false;
1102 bool sideload_auto_reboot = false;
1103 bool just_exit = false;
1104 bool shutdown_after = false;
1105 int retry_count = 0;
1106 bool security_update = false;
Jerry Zhang2dea53e2018-05-02 17:15:03 -07001107 std::string locale;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001108
1109 int arg;
1110 int option_index;
1111 while ((arg = getopt_long(args_to_parse.size(), args_to_parse.data(), "", OPTIONS,
1112 &option_index)) != -1) {
1113 switch (arg) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001114 case 't':
1115 show_text = true;
1116 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001117 case 'x':
1118 just_exit = true;
1119 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001120 case 0: {
1121 std::string option = OPTIONS[option_index].name;
Tao Baof9f17342018-04-27 10:44:04 -07001122 if (option == "locale") {
1123 locale = optarg;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001124 } else if (option == "prompt_and_wipe_data") {
1125 should_prompt_and_wipe_data = true;
Tao Baof9f17342018-04-27 10:44:04 -07001126 } else if (option == "reason") {
1127 reason = optarg;
1128 } else if (option == "retry_count") {
1129 android::base::ParseInt(optarg, &retry_count, 0);
1130 } else if (option == "security") {
1131 security_update = true;
1132 } else if (option == "sideload") {
1133 sideload = true;
1134 } else if (option == "sideload_auto_reboot") {
1135 sideload = true;
1136 sideload_auto_reboot = true;
1137 } else if (option == "shutdown_after") {
1138 shutdown_after = true;
1139 } else if (option == "update_package") {
1140 update_package = optarg;
1141 } else if (option == "wipe_ab") {
1142 should_wipe_ab = true;
1143 } else if (option == "wipe_cache") {
1144 should_wipe_cache = true;
1145 } else if (option == "wipe_data") {
1146 should_wipe_data = true;
1147 } else if (option == "wipe_package_size") {
1148 android::base::ParseUint(optarg, &wipe_package_size);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001149 }
1150 break;
1151 }
1152 case '?':
1153 LOG(ERROR) << "Invalid command argument";
1154 continue;
Doug Zongker9270a202012-01-09 15:16:13 -08001155 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001156 }
Doug Zongker9270a202012-01-09 15:16:13 -08001157
Tianjie Xu99b73be2017-11-28 17:23:06 -08001158 if (locale.empty()) {
1159 if (has_cache) {
1160 locale = load_locale_from_cache();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001161 }
1162
Tao Baoac9d94d2016-11-03 11:37:15 -07001163 if (locale.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -07001164 static constexpr const char* DEFAULT_LOCALE = "en-US";
Tianjie Xu99b73be2017-11-28 17:23:06 -08001165 locale = DEFAULT_LOCALE;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001166 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001167 }
Tao Baoac9d94d2016-11-03 11:37:15 -07001168
Tianjie Xu99b73be2017-11-28 17:23:06 -08001169 printf("locale is [%s]\n", locale.c_str());
1170 printf("stage is [%s]\n", stage.c_str());
1171 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001172
Tianjie Xu99b73be2017-11-28 17:23:06 -08001173 Device* device = make_device();
1174 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
1175 printf("Quiescent recovery mode.\n");
Tao Bao551d2c32018-05-09 20:53:13 -07001176 device->ResetUI(new StubRecoveryUI());
Tianjie Xu99b73be2017-11-28 17:23:06 -08001177 } else {
Tao Bao551d2c32018-05-09 20:53:13 -07001178 if (!device->GetUI()->Init(locale)) {
1179 printf("Failed to initialize UI; using stub UI instead.\n");
1180 device->ResetUI(new StubRecoveryUI());
Tianjie Xu99b73be2017-11-28 17:23:06 -08001181 }
1182 }
Tao Bao551d2c32018-05-09 20:53:13 -07001183 ui = device->GetUI();
Tianjie Xu99b73be2017-11-28 17:23:06 -08001184
Tao Baoe5d2c252018-05-09 11:05:44 -07001185 if (!has_cache) {
1186 device->RemoveMenuItemForAction(Device::WIPE_CACHE);
1187 }
1188
Tianjie Xu99b73be2017-11-28 17:23:06 -08001189 // Set background string to "installing security update" for security update,
1190 // otherwise set it to "installing system update".
1191 ui->SetSystemUpdateText(security_update);
1192
1193 int st_cur, st_max;
1194 if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
1195 ui->SetStage(st_cur, st_max);
1196 }
1197
1198 ui->SetBackground(RecoveryUI::NONE);
1199 if (show_text) ui->ShowText(true);
1200
1201 sehandle = selinux_android_file_context_handle();
1202 selinux_android_set_sehandle(sehandle);
1203 if (!sehandle) {
1204 ui->Print("Warning: No file_contexts\n");
1205 }
1206
1207 device->StartRecovery();
1208
1209 printf("Command:");
1210 for (const auto& arg : args) {
1211 printf(" \"%s\"", arg.c_str());
1212 }
1213 printf("\n\n");
1214
1215 property_list(print_property, nullptr);
1216 printf("\n");
1217
1218 ui->Print("Supported API: %d\n", kRecoveryApiVersion);
1219
1220 int status = INSTALL_SUCCESS;
1221
1222 if (update_package != nullptr) {
1223 // It's not entirely true that we will modify the flash. But we want
1224 // to log the update attempt since update_package is non-NULL.
1225 modified_flash = true;
1226
Tao Baof2ea6d72018-04-26 10:40:36 -07001227 int required_battery_level;
1228 if (retry_count == 0 && !is_battery_ok(&required_battery_level)) {
1229 ui->Print("battery capacity is not enough for installing package: %d%% needed\n",
1230 required_battery_level);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001231 // Log the error code to last_install when installation skips due to
1232 // low battery.
1233 log_failure_code(kLowBattery, update_package);
1234 status = INSTALL_SKIPPED;
Tianjie Xua6f49bd2018-03-26 14:32:11 -07001235 } else if (retry_count == 0 && bootreason_in_blacklist()) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001236 // Skip update-on-reboot when bootreason is kernel_panic or similar
1237 ui->Print("bootreason is in the blacklist; skip OTA installation\n");
1238 log_failure_code(kBootreasonInBlacklist, update_package);
1239 status = INSTALL_SKIPPED;
Dmitri Plotnikov8706a982017-04-18 08:28:26 -07001240 } else {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001241 // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
1242 // identify the interrupted update due to unexpected reboots.
1243 if (retry_count == 0) {
1244 set_retry_bootloader_message(retry_count + 1, args);
Tao Bao7022f332017-07-25 09:52:36 -07001245 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001246
Tao Bao641fa972018-04-25 18:59:40 -07001247 status = install_package(update_package, &should_wipe_cache, true, retry_count);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001248 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1249 wipe_cache(false, device);
1250 }
1251 if (status != INSTALL_SUCCESS) {
1252 ui->Print("Installation aborted.\n");
Tao Baoaac9d9f2018-04-29 23:38:59 -07001253
1254 // When I/O error or bspatch/imgpatch error happens, reboot and retry installation
1255 // RETRY_LIMIT times before we abandon this OTA update.
1256 static constexpr int RETRY_LIMIT = 4;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001257 if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
Jerry Zhang152933a2018-05-02 16:56:00 -07001258 copy_logs(modified_flash, has_cache);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001259 retry_count += 1;
1260 set_retry_bootloader_message(retry_count, args);
1261 // Print retry count on screen.
1262 ui->Print("Retry attempt %d\n", retry_count);
1263
1264 // Reboot and retry the update
1265 if (!reboot("reboot,recovery")) {
1266 ui->Print("Reboot failed\n");
1267 } else {
1268 while (true) {
1269 pause();
1270 }
1271 }
Tianjie Xud9d16292017-04-20 18:08:21 -07001272 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001273 // If this is an eng or userdebug build, then automatically
1274 // turn the text display on if the script fails so the error
1275 // message is visible.
1276 if (is_ro_debuggable()) {
1277 ui->ShowText(true);
Tao Baoc679f932015-03-30 09:43:49 -07001278 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001279 }
Doug Zongker8674a722010-09-15 11:08:23 -07001280 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001281 } else if (should_wipe_data) {
1282 if (!wipe_data(device)) {
1283 status = INSTALL_ERROR;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001284 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001285 } else if (should_prompt_and_wipe_data) {
1286 ui->ShowText(true);
1287 ui->SetBackground(RecoveryUI::ERROR);
1288 if (!prompt_and_wipe_data(device)) {
1289 status = INSTALL_ERROR;
Tao Bao75238632015-05-27 14:46:17 -07001290 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001291 ui->ShowText(false);
1292 } else if (should_wipe_cache) {
1293 if (!wipe_cache(false, device)) {
1294 status = INSTALL_ERROR;
1295 }
1296 } else if (should_wipe_ab) {
1297 if (!wipe_ab_device(wipe_package_size)) {
1298 status = INSTALL_ERROR;
1299 }
1300 } else if (sideload) {
1301 // 'adb reboot sideload' acts the same as user presses key combinations
1302 // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
1303 // display will NOT be turned on by default. And it will reboot after
1304 // sideload finishes even if there are errors. Unless one turns on the
1305 // text display during the installation. This is to enable automated
1306 // testing.
1307 if (!sideload_auto_reboot) {
1308 ui->ShowText(true);
1309 }
Tao Bao641fa972018-04-25 18:59:40 -07001310 status = apply_from_adb(&should_wipe_cache);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001311 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1312 if (!wipe_cache(false, device)) {
1313 status = INSTALL_ERROR;
1314 }
1315 }
1316 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1317 if (sideload_auto_reboot) {
1318 ui->Print("Rebooting automatically.\n");
1319 }
1320 } else if (!just_exit) {
1321 // If this is an eng or userdebug build, automatically turn on the text display if no command
1322 // is specified. Note that this should be called before setting the background to avoid
1323 // flickering the background image.
1324 if (is_ro_debuggable()) {
1325 ui->ShowText(true);
1326 }
1327 status = INSTALL_NONE; // No command specified
1328 ui->SetBackground(RecoveryUI::NO_COMMAND);
1329 }
1330
1331 if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
1332 ui->SetBackground(RecoveryUI::ERROR);
1333 if (!ui->IsTextVisible()) {
1334 sleep(5);
1335 }
1336 }
1337
1338 Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
1339 // 1. If the recovery menu is visible, prompt and wait for commands.
1340 // 2. If the state is INSTALL_NONE, wait for commands. (i.e. In user build, manually reboot into
1341 // recovery to sideload a package.)
1342 // 3. sideload_auto_reboot is an option only available in user-debug build, reboot the device
1343 // without waiting.
1344 // 4. In all other cases, reboot the device. Therefore, normal users will observe the device
1345 // reboot after it shows the "error" screen for 5s.
1346 if ((status == INSTALL_NONE && !sideload_auto_reboot) || ui->IsTextVisible()) {
1347 Device::BuiltinAction temp = prompt_and_wait(device, status);
1348 if (temp != Device::NO_ACTION) {
1349 after = temp;
1350 }
1351 }
1352
1353 // Save logs and clean up before rebooting or shutting down.
Tao Bao551d2c32018-05-09 20:53:13 -07001354 finish_recovery();
Tianjie Xu99b73be2017-11-28 17:23:06 -08001355
1356 switch (after) {
1357 case Device::SHUTDOWN:
1358 ui->Print("Shutting down...\n");
1359 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,");
1360 break;
1361
1362 case Device::REBOOT_BOOTLOADER:
1363 ui->Print("Rebooting to bootloader...\n");
1364 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
1365 break;
1366
1367 default:
1368 ui->Print("Rebooting...\n");
1369 reboot("reboot,");
1370 break;
1371 }
1372 while (true) {
1373 pause();
1374 }
1375 // Should be unreachable.
1376 return EXIT_SUCCESS;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001377}