blob: 6aceb2d61ff08f642bd66d0e2ada1493c308b413 [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"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080067#include "minui/minui.h"
Tao Bao17054c02018-05-03 22:41:23 -070068#include "otautil/dirutil.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070069#include "otautil/error_code.h"
Tao Bao641fa972018-04-25 18:59:40 -070070#include "otautil/paths.h"
Tao Bao2c526392018-05-03 23:01:13 -070071#include "otautil/sysutil.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080072#include "roots.h"
Doug Zongker211aebc2011-10-28 15:13:10 -070073#include "screen_ui.h"
Sen Jiangd5304492016-12-09 16:20:49 -080074#include "stub_ui.h"
Tianjie Xue113e4d2016-10-21 17:46:13 -070075#include "ui.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080076
Tao Baoaac9d9f2018-04-29 23:38:59 -070077static constexpr const char* CACHE_LOG_DIR = "/cache/recovery";
78static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
Tao Baoaac9d9f2018-04-29 23:38:59 -070079static constexpr const char* LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
80static constexpr const char* LAST_LOG_FILE = "/cache/recovery/last_log";
81static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
Tianjie Xu06e57ac2016-07-11 14:04:08 -070082
Tao Baoaac9d9f2018-04-29 23:38:59 -070083static constexpr const char* CACHE_ROOT = "/cache";
84static constexpr const char* DATA_ROOT = "/data";
85static constexpr const char* METADATA_ROOT = "/metadata";
86static constexpr const char* SDCARD_ROOT = "/sdcard";
Nick Kralevicha9ad0322014-10-22 18:38:48 -070087
Tao Baobd0ddcd2017-05-04 13:03:18 -070088// We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
89// into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
90static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
91
Dan Albert8584fcf2016-10-27 03:08:08 +000092static bool has_cache = false;
Tao Baoc0319b62016-10-13 15:17:04 -070093
Tao Baoac9d94d2016-11-03 11:37:15 -070094RecoveryUI* ui = nullptr;
95bool modified_flash = false;
Tao Baoa8d72bc2016-12-25 18:46:50 -080096std::string stage;
Tao Baoac9d94d2016-11-03 11:37:15 -070097const char* reason = nullptr;
98struct selabel_handle* sehandle;
99
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800100/*
101 * The recovery tool communicates with the main system through /cache files.
102 * /cache/recovery/command - INPUT - command line for tool, one arg per line
103 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800104 *
105 * The arguments which may be supplied in the recovery.command file:
Doug Zongkerd4208f92010-09-20 12:16:13 -0700106 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800107 * --wipe_data - erase user data (and cache), then reboot
Tao Baof9f17342018-04-27 10:44:04 -0700108 * --prompt_and_wipe_data - prompt the user that data is corrupt, with their consent erase user
109 * data (and cache), then reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800110 * --wipe_cache - wipe cache (but not user data), then reboot
Tao Baof9f17342018-04-27 10:44:04 -0700111 * --show_text - show the recovery text menu, used by some bootloader (e.g. http://b/36872519).
Oscar Montemayor05231562009-11-30 08:40:57 -0800112 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700113 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800114 *
115 * After completing, we remove /cache/recovery/command and reboot.
116 * Arguments may also be supplied in the bootloader control block (BCB).
117 * These important scenarios must be safely restartable at any point:
118 *
119 * FACTORY RESET
120 * 1. user selects "factory reset"
121 * 2. main system writes "--wipe_data" to /cache/recovery/command
122 * 3. main system reboots into recovery
123 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
124 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700125 * 5. erase_volume() reformats /data
126 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800127 * 7. finish_recovery() erases BCB
128 * -- after this, rebooting will restart the main system --
129 * 8. main() calls reboot() to boot main system
130 *
131 * OTA INSTALL
132 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700133 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800134 * 3. main system reboots into recovery
135 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
136 * -- after this, rebooting will attempt to reinstall the update --
137 * 5. install_package() attempts to install the update
138 * NOTE: the package install must itself be restartable from any point
139 * 6. finish_recovery() erases BCB
140 * -- after this, rebooting will (try to) restart the main system --
141 * 7. ** if install failed **
142 * 7a. prompt_and_wait() shows an error icon and waits for the user
Tao Baoc0336392016-12-13 22:29:49 -0800143 * 7b. the user reboots (pulling the battery, etc) into the main system
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800144 */
145
Elliott Hughesf14af802015-02-10 14:46:14 -0800146bool is_ro_debuggable() {
Elliott Hughescb220402016-09-23 15:30:55 -0700147 return android::base::GetBoolProperty("ro.debuggable", false);
Elliott Hughesf14af802015-02-10 14:46:14 -0800148}
149
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800150// command line args come from, in decreasing precedence:
151// - the actual command line
152// - the bootloader control block (one per line, after "recovery")
153// - the contents of COMMAND_FILE (one per line)
Tao Baof0ed1592016-12-02 11:32:19 -0800154static std::vector<std::string> get_args(const int argc, char** const argv) {
155 CHECK_GT(argc, 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800156
Tao Baof0ed1592016-12-02 11:32:19 -0800157 bootloader_message boot = {};
158 std::string err;
159 if (!read_bootloader_message(&boot, &err)) {
160 LOG(ERROR) << err;
161 // If fails, leave a zeroed bootloader_message.
162 boot = {};
163 }
Tao Baoa8d72bc2016-12-25 18:46:50 -0800164 stage = std::string(boot.stage);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800165
Tao Baof0ed1592016-12-02 11:32:19 -0800166 if (boot.command[0] != 0) {
167 std::string boot_command = std::string(boot.command, sizeof(boot.command));
168 LOG(INFO) << "Boot command: " << boot_command;
169 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800170
Tao Baof0ed1592016-12-02 11:32:19 -0800171 if (boot.status[0] != 0) {
172 std::string boot_status = std::string(boot.status, sizeof(boot.status));
173 LOG(INFO) << "Boot status: " << boot_status;
174 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800175
Tao Baof0ed1592016-12-02 11:32:19 -0800176 std::vector<std::string> args(argv, argv + argc);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800177
Tao Baof0ed1592016-12-02 11:32:19 -0800178 // --- if arguments weren't supplied, look in the bootloader control block
Tao Bao570af9d2017-01-09 10:29:59 -0800179 if (args.size() == 1) {
Tao Baof0ed1592016-12-02 11:32:19 -0800180 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
181 std::string boot_recovery(boot.recovery);
182 std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
183 if (!tokens.empty() && tokens[0] == "recovery") {
184 for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
185 // Skip empty and '\0'-filled tokens.
186 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
187 }
188 LOG(INFO) << "Got " << args.size() << " arguments from boot message";
189 } else if (boot.recovery[0] != 0) {
190 LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
191 }
192 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800193
Tao Baof0ed1592016-12-02 11:32:19 -0800194 // --- if that doesn't work, try the command file (if we have /cache).
Tao Bao570af9d2017-01-09 10:29:59 -0800195 if (args.size() == 1 && has_cache) {
Tao Baof0ed1592016-12-02 11:32:19 -0800196 std::string content;
Tao Bao7d34fa12016-12-08 18:10:48 -0800197 if (ensure_path_mounted(COMMAND_FILE) == 0 &&
198 android::base::ReadFileToString(COMMAND_FILE, &content)) {
Tao Baof0ed1592016-12-02 11:32:19 -0800199 std::vector<std::string> tokens = android::base::Split(content, "\n");
Tao Bao7d34fa12016-12-08 18:10:48 -0800200 // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
201 // COMMAND_FILE doesn't use filename as the first argument).
202 for (auto it = tokens.begin(); it != tokens.end(); it++) {
Tao Baof0ed1592016-12-02 11:32:19 -0800203 // Skip empty and '\0'-filled tokens.
204 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
205 }
206 LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800207 }
Tao Baof0ed1592016-12-02 11:32:19 -0800208 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800209
Tao Baof0ed1592016-12-02 11:32:19 -0800210 // Write the arguments (excluding the filename in args[0]) back into the
211 // bootloader control block. So the device will always boot into recovery to
212 // finish the pending work, until finish_recovery() is called.
213 std::vector<std::string> options(args.cbegin() + 1, args.cend());
Tao Bao2292db82016-12-13 21:53:31 -0800214 if (!update_bootloader_message(options, &err)) {
215 LOG(ERROR) << "Failed to set BCB message: " << err;
Tao Baof0ed1592016-12-02 11:32:19 -0800216 }
217
218 return args;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800219}
220
Tao Bao2292db82016-12-13 21:53:31 -0800221// Set the BCB to reboot back into recovery (it won't resume the install from
222// sdcard though).
223static void set_sdcard_update_bootloader_message() {
224 std::vector<std::string> options;
225 std::string err;
226 if (!update_bootloader_message(options, &err)) {
227 LOG(ERROR) << "Failed to set BCB message: " << err;
228 }
Doug Zongker34c98df2009-08-18 12:05:45 -0700229}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800230
Tao Baoec579032017-07-21 12:13:15 -0700231// Clear the recovery command and prepare to boot a (hopefully working) system,
Tianjie Xuc14d95d2016-03-24 11:50:34 -0700232// copy our log file to cache as well (for the system to read). This function is
233// idempotent: call it as many times as you like.
Jerry Zhang2dea53e2018-05-02 17:15:03 -0700234static void finish_recovery(Device* device) {
235 std::string locale = device->GetUI()->GetLocale();
Tao Baoec579032017-07-21 12:13:15 -0700236 // Save the locale to cache, so if recovery is next started up without a '--locale' argument
237 // (e.g., directly from the bootloader) it will use the last-known locale.
238 if (!locale.empty() && has_cache) {
239 LOG(INFO) << "Saving locale \"" << locale << "\"";
240 if (ensure_path_mounted(LOCALE_FILE) != 0) {
241 LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
242 } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
243 PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
Doug Zongker4f33e552012-08-23 13:16:12 -0700244 }
Tao Baoec579032017-07-21 12:13:15 -0700245 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700246
Jerry Zhang152933a2018-05-02 16:56:00 -0700247 copy_logs(modified_flash, has_cache);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800248
Tao Baoec579032017-07-21 12:13:15 -0700249 // Reset to normal system boot so recovery won't cycle indefinitely.
250 std::string err;
251 if (!clear_bootloader_message(&err)) {
252 LOG(ERROR) << "Failed to clear BCB message: " << err;
253 }
254
255 // Remove the command file, so recovery won't repeat indefinitely.
256 if (has_cache) {
257 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
258 LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
Yabin Cui8b309f62016-06-24 18:22:02 -0700259 }
Tao Baoec579032017-07-21 12:13:15 -0700260 ensure_path_unmounted(CACHE_ROOT);
261 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800262
Tao Baoec579032017-07-21 12:13:15 -0700263 sync(); // For good measure.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800264}
265
Tao Bao3f5a3822016-12-13 11:14:37 -0800266struct saved_log_file {
267 std::string name;
268 struct stat sb;
269 std::string data;
270};
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700271
Elliott Hughes945548e2015-06-05 17:59:56 -0700272static bool erase_volume(const char* volume) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800273 bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
274 bool is_data = (strcmp(volume, DATA_ROOT) == 0);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700275
Tao Bao3f5a3822016-12-13 11:14:37 -0800276 ui->SetBackground(RecoveryUI::ERASING);
277 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700278
Tao Bao3f5a3822016-12-13 11:14:37 -0800279 std::vector<saved_log_file> log_files;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700280
Tao Bao3f5a3822016-12-13 11:14:37 -0800281 if (is_cache) {
282 // If we're reformatting /cache, we load any past logs
283 // (i.e. "/cache/recovery/last_*") and the current log
284 // ("/cache/recovery/log") into memory, so we can restore them after
285 // the reformat.
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700286
Tao Bao3f5a3822016-12-13 11:14:37 -0800287 ensure_path_mounted(volume);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700288
Tao Bao3f5a3822016-12-13 11:14:37 -0800289 struct dirent* de;
290 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(CACHE_LOG_DIR), closedir);
291 if (d) {
292 while ((de = readdir(d.get())) != nullptr) {
293 if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
294 std::string path = android::base::StringPrintf("%s/%s", CACHE_LOG_DIR, de->d_name);
295
296 struct stat sb;
297 if (stat(path.c_str(), &sb) == 0) {
298 // truncate files to 512kb
299 if (sb.st_size > (1 << 19)) {
300 sb.st_size = 1 << 19;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700301 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800302
303 std::string data(sb.st_size, '\0');
Tianjie Xude6735e2017-07-10 15:13:33 -0700304 FILE* f = fopen(path.c_str(), "rbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800305 fread(&data[0], 1, data.size(), f);
306 fclose(f);
307
308 log_files.emplace_back(saved_log_file{ path, sb, data });
309 }
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700310 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800311 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800312 } else {
Tao Bao3f5a3822016-12-13 11:14:37 -0800313 if (errno != ENOENT) {
314 PLOG(ERROR) << "Failed to opendir " << CACHE_LOG_DIR;
315 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800316 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800317 }
Doug Zongkerd0181b82011-10-19 10:51:12 -0700318
Tao Bao3f5a3822016-12-13 11:14:37 -0800319 ui->Print("Formatting %s...\n", volume);
320
321 ensure_path_unmounted(volume);
322
323 int result;
Tao Bao3f5a3822016-12-13 11:14:37 -0800324 if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700325 static constexpr const char* CONVERT_FBE_DIR = "/tmp/convert_fbe";
326 static constexpr const char* CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
327 // Create convert_fbe breadcrumb file to signal init to convert to file based encryption, not
328 // full disk encryption.
Tao Bao3f5a3822016-12-13 11:14:37 -0800329 if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700330 PLOG(ERROR) << "Failed to mkdir " << CONVERT_FBE_DIR;
331 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800332 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700333 FILE* f = fopen(CONVERT_FBE_FILE, "wbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800334 if (!f) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700335 PLOG(ERROR) << "Failed to convert to file encryption";
336 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800337 }
338 fclose(f);
339 result = format_volume(volume, CONVERT_FBE_DIR);
340 remove(CONVERT_FBE_FILE);
341 rmdir(CONVERT_FBE_DIR);
342 } else {
343 result = format_volume(volume);
344 }
345
346 if (is_cache) {
347 // Re-create the log dir and write back the log entries.
348 if (ensure_path_mounted(CACHE_LOG_DIR) == 0 &&
Tao Baoac3d1ed2017-07-23 00:01:02 -0700349 mkdir_recursively(CACHE_LOG_DIR, 0777, false, sehandle) == 0) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800350 for (const auto& log : log_files) {
351 if (!android::base::WriteStringToFile(log.data, log.name, log.sb.st_mode, log.sb.st_uid,
352 log.sb.st_gid)) {
353 PLOG(ERROR) << "Failed to write to " << log.name;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700354 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800355 }
356 } else {
357 PLOG(ERROR) << "Failed to mount / create " << CACHE_LOG_DIR;
Doug Zongker2c3539e2010-09-29 13:21:30 -0700358 }
359
Tao Bao3f5a3822016-12-13 11:14:37 -0800360 // Any part of the log we'd copied to cache is now gone.
361 // Reset the pointer so we copy from the beginning of the temp
362 // log.
Jerry Zhang152933a2018-05-02 16:56:00 -0700363 reset_tmplog_offset();
364 copy_logs(modified_flash, has_cache);
Tao Bao3f5a3822016-12-13 11:14:37 -0800365 }
366
367 return (result == 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800368}
369
Tao Baoc4a18ef2017-02-10 00:13:30 -0800370// Returns the selected filename, or an empty string.
371static std::string browse_directory(const std::string& path, Device* device) {
372 ensure_path_mounted(path.c_str());
Doug Zongker8674a722010-09-15 11:08:23 -0700373
Tao Baoc4a18ef2017-02-10 00:13:30 -0800374 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path.c_str()), closedir);
375 if (!d) {
376 PLOG(ERROR) << "error opening " << path;
377 return "";
378 }
Doug Zongkerc18eeb82010-09-21 16:49:26 -0700379
Tao Baoc4a18ef2017-02-10 00:13:30 -0800380 std::vector<std::string> dirs;
Tao Bao1fe1afe2018-05-01 15:56:05 -0700381 std::vector<std::string> entries{ "../" }; // "../" is always the first entry.
Tao Baoc4a18ef2017-02-10 00:13:30 -0800382
383 dirent* de;
384 while ((de = readdir(d.get())) != nullptr) {
385 std::string name(de->d_name);
386
387 if (de->d_type == DT_DIR) {
388 // Skip "." and ".." entries.
389 if (name == "." || name == "..") continue;
390 dirs.push_back(name + "/");
391 } else if (de->d_type == DT_REG && android::base::EndsWithIgnoreCase(name, ".zip")) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700392 entries.push_back(name);
Tao Baoc4a18ef2017-02-10 00:13:30 -0800393 }
394 }
395
396 std::sort(dirs.begin(), dirs.end());
Tao Bao1fe1afe2018-05-01 15:56:05 -0700397 std::sort(entries.begin(), entries.end());
Tao Baoc4a18ef2017-02-10 00:13:30 -0800398
Tao Bao1fe1afe2018-05-01 15:56:05 -0700399 // Append dirs to the entries list.
400 entries.insert(entries.end(), dirs.begin(), dirs.end());
Tao Baoc4a18ef2017-02-10 00:13:30 -0800401
Tao Bao1fe1afe2018-05-01 15:56:05 -0700402 std::vector<std::string> headers{ "Choose a package to install:", path };
Tao Baoc4a18ef2017-02-10 00:13:30 -0800403
Tao Bao1fe1afe2018-05-01 15:56:05 -0700404 size_t chosen_item = 0;
Tao Baoc4a18ef2017-02-10 00:13:30 -0800405 while (true) {
Tao Bao3aec6962018-04-20 09:24:58 -0700406 chosen_item = ui->ShowMenu(
407 headers, entries, chosen_item, true,
408 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Baoc4a18ef2017-02-10 00:13:30 -0800409
Tao Bao1fe1afe2018-05-01 15:56:05 -0700410 const std::string& item = entries[chosen_item];
Tao Baoc4a18ef2017-02-10 00:13:30 -0800411 if (chosen_item == 0) {
412 // Go up but continue browsing (if the caller is browse_directory).
413 return "";
Doug Zongker8674a722010-09-15 11:08:23 -0700414 }
415
Tao Baoc4a18ef2017-02-10 00:13:30 -0800416 std::string new_path = path + "/" + item;
417 if (new_path.back() == '/') {
418 // Recurse down into a subdirectory.
419 new_path.pop_back();
420 std::string result = browse_directory(new_path, device);
421 if (!result.empty()) return result;
422 } else {
423 // Selected a zip file: return the path to the caller.
424 return new_path;
Doug Zongker8674a722010-09-15 11:08:23 -0700425 }
Tao Baoc4a18ef2017-02-10 00:13:30 -0800426 }
Doug Zongker8674a722010-09-15 11:08:23 -0700427
Tao Baoc4a18ef2017-02-10 00:13:30 -0800428 // Unreachable.
Doug Zongker8674a722010-09-15 11:08:23 -0700429}
430
Elliott Hughes30694c92015-03-25 15:16:51 -0700431static bool yes_no(Device* device, const char* question1, const char* question2) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700432 std::vector<std::string> headers{ question1, question2 };
433 std::vector<std::string> items{ " No", " Yes" };
Doug Zongkerddd6a282009-06-09 12:22:33 -0700434
Tao Bao1fe1afe2018-05-01 15:56:05 -0700435 size_t chosen_item = ui->ShowMenu(
Tao Bao3aec6962018-04-20 09:24:58 -0700436 headers, items, 0, true,
437 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
438 return (chosen_item == 1);
Elliott Hughes30694c92015-03-25 15:16:51 -0700439}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800440
Paul Crowley08404b42016-12-19 13:04:23 -0800441static bool ask_to_wipe_data(Device* device) {
Tao Bao3aec6962018-04-20 09:24:58 -0700442 return yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!");
Paul Crowley08404b42016-12-19 13:04:23 -0800443}
Doug Zongker1066d2c2009-04-01 13:57:40 -0700444
Paul Crowley08404b42016-12-19 13:04:23 -0800445// Return true on success.
446static bool wipe_data(Device* device) {
Tao Bao682c34b2015-04-07 17:16:35 -0700447 modified_flash = true;
448
Doug Zongker211aebc2011-10-28 15:13:10 -0700449 ui->Print("\n-- Wiping data...\n");
Paul Crowley3b4d5162016-06-08 13:51:41 -0700450 bool success = device->PreWipeData();
451 if (success) {
452 success &= erase_volume(DATA_ROOT);
453 if (has_cache) {
454 success &= erase_volume(CACHE_ROOT);
455 }
456 if (volume_for_mount_point(METADATA_ROOT) != nullptr) {
457 success &= erase_volume(METADATA_ROOT);
458 }
459 }
460 if (success) {
461 success &= device->PostWipeData();
462 }
Elliott Hughes945548e2015-06-05 17:59:56 -0700463 ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
464 return success;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700465}
466
Paul Crowley08404b42016-12-19 13:04:23 -0800467static bool prompt_and_wipe_data(Device* device) {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700468 // Use a single string and let ScreenRecoveryUI handles the wrapping.
Tao Bao1fe1afe2018-05-01 15:56:05 -0700469 std::vector<std::string> headers{
Tao Bao2bbc6d62017-08-13 23:48:55 -0700470 "Can't load Android system. Your data may be corrupt. "
471 "If you continue to get this message, you may need to "
472 "perform a factory data reset and erase all user data "
Paul Crowley31ac0c62017-03-23 12:32:40 -0700473 "stored on this device.",
Tao Baofc5499f2017-02-23 19:06:53 -0800474 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700475 // clang-format off
476 std::vector<std::string> items {
Paul Crowley31ac0c62017-03-23 12:32:40 -0700477 "Try again",
478 "Factory data reset",
Tao Baofc5499f2017-02-23 19:06:53 -0800479 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700480 // clang-format on
Tao Baofc5499f2017-02-23 19:06:53 -0800481 for (;;) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700482 size_t chosen_item = ui->ShowMenu(
Tao Bao3aec6962018-04-20 09:24:58 -0700483 headers, items, 0, true,
484 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Baofc5499f2017-02-23 19:06:53 -0800485 if (chosen_item != 1) {
486 return true; // Just reboot, no wipe; not a failure, user asked for it
Paul Crowley08404b42016-12-19 13:04:23 -0800487 }
Tao Baofc5499f2017-02-23 19:06:53 -0800488 if (ask_to_wipe_data(device)) {
489 return wipe_data(device);
490 }
491 }
Paul Crowley08404b42016-12-19 13:04:23 -0800492}
493
Tao Baoe39a9bc2015-03-31 12:19:05 -0700494// Return true on success.
495static bool wipe_cache(bool should_confirm, Device* device) {
Tao Bao26112e52016-02-25 12:29:40 -0800496 if (!has_cache) {
497 ui->Print("No /cache partition found.\n");
498 return false;
499 }
500
Elliott Hughes30694c92015-03-25 15:16:51 -0700501 if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
Tao Baoe39a9bc2015-03-31 12:19:05 -0700502 return false;
Elliott Hughes30694c92015-03-25 15:16:51 -0700503 }
504
Tao Bao682c34b2015-04-07 17:16:35 -0700505 modified_flash = true;
506
Elliott Hughes30694c92015-03-25 15:16:51 -0700507 ui->Print("\n-- Wiping cache...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700508 bool success = erase_volume("/cache");
509 ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
510 return success;
Elliott Hughes30694c92015-03-25 15:16:51 -0700511}
512
Tao Bao1b2a98b2017-03-24 10:45:34 -0700513// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
514// BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
Tao Bao862a4c12016-06-02 11:16:50 -0700515static bool secure_wipe_partition(const std::string& partition) {
Tao Bao1b2a98b2017-03-24 10:45:34 -0700516 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
517 if (fd == -1) {
518 PLOG(ERROR) << "Failed to open \"" << partition << "\"";
519 return false;
520 }
521
522 uint64_t range[2] = { 0, 0 };
523 if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
524 PLOG(ERROR) << "Failed to get partition size";
525 return false;
526 }
527 LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
528
529 LOG(INFO) << " Trying BLKSECDISCARD...";
530 if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
531 PLOG(WARNING) << " Failed";
532
533 // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
534 unsigned int zeroes;
535 if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
536 LOG(INFO) << " Trying BLKDISCARD...";
537 if (ioctl(fd, BLKDISCARD, &range) == -1) {
538 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700539 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700540 }
541 } else {
542 LOG(INFO) << " Trying BLKZEROOUT...";
543 if (ioctl(fd, BLKZEROOUT, &range) == -1) {
544 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700545 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700546 }
Tao Bao862a4c12016-06-02 11:16:50 -0700547 }
Tao Bao1b2a98b2017-03-24 10:45:34 -0700548 }
Tao Bao862a4c12016-06-02 11:16:50 -0700549
Tao Bao1b2a98b2017-03-24 10:45:34 -0700550 LOG(INFO) << " Done";
551 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700552}
553
Yabin Cuifd99a312016-06-09 14:09:39 -0700554// Check if the wipe package matches expectation:
555// 1. verify the package.
556// 2. check metadata (ota-type, pre-device and serial number if having one).
557static bool check_wipe_package(size_t wipe_package_size) {
558 if (wipe_package_size == 0) {
559 LOG(ERROR) << "wipe_package_size is zero";
560 return false;
561 }
562 std::string wipe_package;
563 std::string err_str;
564 if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
565 PLOG(ERROR) << "Failed to read wipe package";
566 return false;
567 }
568 if (!verify_package(reinterpret_cast<const unsigned char*>(wipe_package.data()),
569 wipe_package.size())) {
570 LOG(ERROR) << "Failed to verify package";
571 return false;
572 }
573
574 // Extract metadata
575 ZipArchiveHandle zip;
Tao Baoefc35592017-01-08 22:45:47 -0800576 int err = OpenArchiveFromMemory(static_cast<void*>(&wipe_package[0]), wipe_package.size(),
577 "wipe_package", &zip);
Yabin Cuifd99a312016-06-09 14:09:39 -0700578 if (err != 0) {
579 LOG(ERROR) << "Can't open wipe package : " << ErrorCodeString(err);
580 return false;
581 }
582 std::string metadata;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700583 if (!read_metadata_from_package(zip, &metadata)) {
Yabin Cuifd99a312016-06-09 14:09:39 -0700584 CloseArchive(zip);
585 return false;
586 }
587 CloseArchive(zip);
588
589 // Check metadata
590 std::vector<std::string> lines = android::base::Split(metadata, "\n");
591 bool ota_type_matched = false;
592 bool device_type_matched = false;
593 bool has_serial_number = false;
594 bool serial_number_matched = false;
595 for (const auto& line : lines) {
596 if (line == "ota-type=BRICK") {
597 ota_type_matched = true;
598 } else if (android::base::StartsWith(line, "pre-device=")) {
599 std::string device_type = line.substr(strlen("pre-device="));
Tao Baoefc35592017-01-08 22:45:47 -0800600 std::string real_device_type = android::base::GetProperty("ro.build.product", "");
Yabin Cuifd99a312016-06-09 14:09:39 -0700601 device_type_matched = (device_type == real_device_type);
602 } else if (android::base::StartsWith(line, "serialno=")) {
603 std::string serial_no = line.substr(strlen("serialno="));
Tao Baoefc35592017-01-08 22:45:47 -0800604 std::string real_serial_no = android::base::GetProperty("ro.serialno", "");
Yabin Cuifd99a312016-06-09 14:09:39 -0700605 has_serial_number = true;
606 serial_number_matched = (serial_no == real_serial_no);
607 }
608 }
609 return ota_type_matched && device_type_matched && (!has_serial_number || serial_number_matched);
610}
611
Tao Baoaac9d9f2018-04-29 23:38:59 -0700612// Wipes the current A/B device, with a secure wipe of all the partitions in RECOVERY_WIPE.
Yabin Cuifd99a312016-06-09 14:09:39 -0700613static bool wipe_ab_device(size_t wipe_package_size) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700614 ui->SetBackground(RecoveryUI::ERASING);
615 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Tao Bao862a4c12016-06-02 11:16:50 -0700616
Tao Baoaac9d9f2018-04-29 23:38:59 -0700617 if (!check_wipe_package(wipe_package_size)) {
618 LOG(ERROR) << "Failed to verify wipe package";
619 return false;
620 }
621 static constexpr const char* RECOVERY_WIPE = "/etc/recovery.wipe";
622 std::string partition_list;
623 if (!android::base::ReadFileToString(RECOVERY_WIPE, &partition_list)) {
624 LOG(ERROR) << "failed to read \"" << RECOVERY_WIPE << "\"";
625 return false;
626 }
627
628 std::vector<std::string> lines = android::base::Split(partition_list, "\n");
629 for (const std::string& line : lines) {
630 std::string partition = android::base::Trim(line);
631 // Ignore '#' comment or empty lines.
632 if (android::base::StartsWith(partition, "#") || partition.empty()) {
633 continue;
Tao Bao862a4c12016-06-02 11:16:50 -0700634 }
635
Tao Baoaac9d9f2018-04-29 23:38:59 -0700636 // Proceed anyway even if it fails to wipe some partition.
637 secure_wipe_partition(partition);
638 }
639 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700640}
641
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700642static void choose_recovery_file(Device* device) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800643 std::vector<std::string> entries;
644 if (has_cache) {
645 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
646 auto add_to_entries = [&](const char* filename) {
647 std::string log_file(filename);
648 if (i > 0) {
649 log_file += "." + std::to_string(i);
Tao Baobef39712015-05-04 18:50:27 -0700650 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800651
652 if (ensure_path_mounted(log_file.c_str()) == 0 && access(log_file.c_str(), R_OK) == 0) {
653 entries.push_back(std::move(log_file));
654 }
655 };
656
657 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
658 add_to_entries(LAST_LOG_FILE);
659
660 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
661 add_to_entries(LAST_KMSG_FILE);
662 }
663 } else {
664 // If cache partition is not found, view /tmp/recovery.log instead.
Tao Bao641fa972018-04-25 18:59:40 -0700665 if (access(Paths::Get().temporary_log_file().c_str(), R_OK) == -1) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800666 return;
Tianjie Xua54f75e2016-08-17 12:02:46 -0700667 } else {
Tao Bao641fa972018-04-25 18:59:40 -0700668 entries.push_back(Paths::Get().temporary_log_file());
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700669 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800670 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700671
Tao Bao08fc6be2017-03-07 00:56:27 -0800672 entries.push_back("Back");
Elliott Hughesc0491632015-05-06 12:40:05 -0700673
Tao Bao1fe1afe2018-05-01 15:56:05 -0700674 std::vector<std::string> headers{ "Select file to view" };
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700675
Tao Bao1fe1afe2018-05-01 15:56:05 -0700676 size_t chosen_item = 0;
Tao Bao08fc6be2017-03-07 00:56:27 -0800677 while (true) {
Tao Bao3aec6962018-04-20 09:24:58 -0700678 chosen_item = ui->ShowMenu(
Tao Bao1fe1afe2018-05-01 15:56:05 -0700679 headers, entries, chosen_item, true,
Tao Bao3aec6962018-04-20 09:24:58 -0700680 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Bao08fc6be2017-03-07 00:56:27 -0800681 if (entries[chosen_item] == "Back") break;
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700682
Tao Bao1d156b92018-05-02 12:43:18 -0700683 ui->ShowFile(entries[chosen_item]);
Tao Bao08fc6be2017-03-07 00:56:27 -0800684 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700685}
686
Tao Baodb7e8982017-03-06 23:53:16 -0800687static void run_graphics_test() {
688 // Switch to graphics screen.
689 ui->ShowText(false);
Elliott Hughes498cda62016-04-14 16:49:04 -0700690
Tao Baodb7e8982017-03-06 23:53:16 -0800691 ui->SetProgressType(RecoveryUI::INDETERMINATE);
692 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
693 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700694
Tao Baodb7e8982017-03-06 23:53:16 -0800695 ui->SetBackground(RecoveryUI::ERROR);
696 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700697
Tao Baodb7e8982017-03-06 23:53:16 -0800698 ui->SetBackground(RecoveryUI::NO_COMMAND);
699 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700700
Tao Baodb7e8982017-03-06 23:53:16 -0800701 ui->SetBackground(RecoveryUI::ERASING);
702 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700703
Tao Baodb7e8982017-03-06 23:53:16 -0800704 // Calling SetBackground() after SetStage() to trigger a redraw.
705 ui->SetStage(1, 3);
706 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
707 sleep(1);
708 ui->SetStage(2, 3);
709 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
710 sleep(1);
711 ui->SetStage(3, 3);
712 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
713 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700714
Tao Baodb7e8982017-03-06 23:53:16 -0800715 ui->SetStage(-1, -1);
716 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Elliott Hughes498cda62016-04-14 16:49:04 -0700717
Tao Baodb7e8982017-03-06 23:53:16 -0800718 ui->SetProgressType(RecoveryUI::DETERMINATE);
719 ui->ShowProgress(1.0, 10.0);
720 float fraction = 0.0;
721 for (size_t i = 0; i < 100; ++i) {
722 fraction += .01;
723 ui->SetProgress(fraction);
724 usleep(100000);
725 }
726
727 ui->ShowText(true);
Elliott Hughes498cda62016-04-14 16:49:04 -0700728}
729
Tao Baocdcf28f2016-01-13 15:05:20 -0800730// How long (in seconds) we wait for the fuse-provided package file to
731// appear, before timing out.
732#define SDCARD_INSTALL_TIMEOUT 10
733
Tao Bao145d8612015-03-25 15:51:15 -0700734static int apply_from_sdcard(Device* device, bool* wipe_cache) {
Tao Bao682c34b2015-04-07 17:16:35 -0700735 modified_flash = true;
736
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000737 if (ensure_path_mounted(SDCARD_ROOT) != 0) {
738 ui->Print("\n-- Couldn't mount %s.\n", SDCARD_ROOT);
739 return INSTALL_ERROR;
740 }
741
Tao Baoc4a18ef2017-02-10 00:13:30 -0800742 std::string path = browse_directory(SDCARD_ROOT, device);
743 if (path.empty()) {
Elliott Hughes018ed312015-04-08 16:51:36 -0700744 ui->Print("\n-- No package file selected.\n");
caozhiyuanb4effb92015-06-10 16:46:38 +0800745 ensure_path_unmounted(SDCARD_ROOT);
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000746 return INSTALL_ERROR;
747 }
748
Tao Baoc4a18ef2017-02-10 00:13:30 -0800749 ui->Print("\n-- Install %s ...\n", path.c_str());
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000750 set_sdcard_update_bootloader_message();
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000751
Tao Baocdcf28f2016-01-13 15:05:20 -0800752 // We used to use fuse in a thread as opposed to a process. Since accessing
753 // through fuse involves going from kernel to userspace to kernel, it leads
754 // to deadlock when a page fault occurs. (Bug: 26313124)
755 pid_t child;
756 if ((child = fork()) == 0) {
Tao Baoc4a18ef2017-02-10 00:13:30 -0800757 bool status = start_sdcard_fuse(path.c_str());
Tao Baocdcf28f2016-01-13 15:05:20 -0800758
759 _exit(status ? EXIT_SUCCESS : EXIT_FAILURE);
760 }
761
762 // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the fuse in child
763 // process is ready.
764 int result = INSTALL_ERROR;
765 int status;
766 bool waited = false;
767 for (int i = 0; i < SDCARD_INSTALL_TIMEOUT; ++i) {
768 if (waitpid(child, &status, WNOHANG) == -1) {
769 result = INSTALL_ERROR;
770 waited = true;
771 break;
772 }
773
774 struct stat sb;
775 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &sb) == -1) {
776 if (errno == ENOENT && i < SDCARD_INSTALL_TIMEOUT-1) {
777 sleep(1);
778 continue;
779 } else {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700780 LOG(ERROR) << "Timed out waiting for the fuse-provided package.";
Tao Baocdcf28f2016-01-13 15:05:20 -0800781 result = INSTALL_ERROR;
782 kill(child, SIGKILL);
783 break;
784 }
785 }
786
Tao Bao641fa972018-04-25 18:59:40 -0700787 result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache, false, 0 /*retry_count*/);
Tao Baocdcf28f2016-01-13 15:05:20 -0800788 break;
789 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000790
Tao Baocdcf28f2016-01-13 15:05:20 -0800791 if (!waited) {
792 // Calling stat() on this magic filename signals the fuse
793 // filesystem to shut down.
794 struct stat sb;
795 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &sb);
796
797 waitpid(child, &status, 0);
798 }
799
800 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700801 LOG(ERROR) << "Error exit from the fuse process: " << WEXITSTATUS(status);
Tao Baocdcf28f2016-01-13 15:05:20 -0800802 }
803
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000804 ensure_path_unmounted(SDCARD_ROOT);
Tao Baocdcf28f2016-01-13 15:05:20 -0800805 return result;
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000806}
807
Tao Bao50dd5322017-03-07 14:57:04 -0800808// Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
809// which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
810static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
811 for (;;) {
Jerry Zhang2dea53e2018-05-02 17:15:03 -0700812 finish_recovery(device);
Tao Bao50dd5322017-03-07 14:57:04 -0800813 switch (status) {
814 case INSTALL_SUCCESS:
815 case INSTALL_NONE:
816 ui->SetBackground(RecoveryUI::NO_COMMAND);
817 break;
Doug Zongker6c8553d2012-09-24 10:40:47 -0700818
Tao Bao50dd5322017-03-07 14:57:04 -0800819 case INSTALL_ERROR:
820 case INSTALL_CORRUPT:
821 ui->SetBackground(RecoveryUI::ERROR);
822 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800823 }
Tao Bao50dd5322017-03-07 14:57:04 -0800824 ui->SetProgressType(RecoveryUI::EMPTY);
825
Tao Bao1fe1afe2018-05-01 15:56:05 -0700826 size_t chosen_item = ui->ShowMenu(
827 {}, device->GetMenuItems(), 0, false,
Tao Bao3aec6962018-04-20 09:24:58 -0700828 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Bao50dd5322017-03-07 14:57:04 -0800829
830 // Device-specific code may take some action here. It may return one of the core actions
831 // handled in the switch statement below.
Tao Bao1fe1afe2018-05-01 15:56:05 -0700832 Device::BuiltinAction chosen_action = (chosen_item == static_cast<size_t>(-1))
833 ? Device::REBOOT
834 : device->InvokeMenuItem(chosen_item);
Tao Bao50dd5322017-03-07 14:57:04 -0800835
836 bool should_wipe_cache = false;
837 switch (chosen_action) {
838 case Device::NO_ACTION:
839 break;
840
841 case Device::REBOOT:
842 case Device::SHUTDOWN:
843 case Device::REBOOT_BOOTLOADER:
844 return chosen_action;
845
846 case Device::WIPE_DATA:
847 if (ui->IsTextVisible()) {
848 if (ask_to_wipe_data(device)) {
849 wipe_data(device);
850 }
851 } else {
852 wipe_data(device);
853 return Device::NO_ACTION;
854 }
855 break;
856
857 case Device::WIPE_CACHE:
858 wipe_cache(ui->IsTextVisible(), device);
859 if (!ui->IsTextVisible()) return Device::NO_ACTION;
860 break;
861
862 case Device::APPLY_ADB_SIDELOAD:
863 case Device::APPLY_SDCARD:
864 {
865 bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD);
866 if (adb) {
Tao Bao641fa972018-04-25 18:59:40 -0700867 status = apply_from_adb(&should_wipe_cache);
Tao Bao50dd5322017-03-07 14:57:04 -0800868 } else {
869 status = apply_from_sdcard(device, &should_wipe_cache);
870 }
871
872 if (status == INSTALL_SUCCESS && should_wipe_cache) {
873 if (!wipe_cache(false, device)) {
874 status = INSTALL_ERROR;
875 }
876 }
877
878 if (status != INSTALL_SUCCESS) {
879 ui->SetBackground(RecoveryUI::ERROR);
880 ui->Print("Installation aborted.\n");
Jerry Zhang152933a2018-05-02 16:56:00 -0700881 copy_logs(modified_flash, has_cache);
Tao Bao50dd5322017-03-07 14:57:04 -0800882 } else if (!ui->IsTextVisible()) {
883 return Device::NO_ACTION; // reboot if logs aren't visible
884 } else {
885 ui->Print("\nInstall from %s complete.\n", adb ? "ADB" : "SD card");
886 }
887 }
888 break;
889
890 case Device::VIEW_RECOVERY_LOGS:
891 choose_recovery_file(device);
892 break;
893
894 case Device::RUN_GRAPHICS_TEST:
895 run_graphics_test();
896 break;
897
Tianjie Xu29d55752017-09-20 17:53:46 -0700898 case Device::RUN_LOCALE_TEST: {
899 ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
Tao Bao39c49182018-05-07 22:50:33 -0700900 screen_ui->CheckBackgroundTextImages();
Tianjie Xu29d55752017-09-20 17:53:46 -0700901 break;
902 }
Tao Bao50dd5322017-03-07 14:57:04 -0800903 case Device::MOUNT_SYSTEM:
904 // For a system image built with the root directory (i.e. system_root_image == "true"), we
905 // mount it to /system_root, and symlink /system to /system_root/system to make adb shell
906 // work (the symlink is created through the build system). (Bug: 22855115)
907 if (android::base::GetBoolProperty("ro.build.system_root_image", false)) {
908 if (ensure_path_mounted_at("/", "/system_root") != -1) {
909 ui->Print("Mounted /system.\n");
910 }
911 } else {
912 if (ensure_path_mounted("/system") != -1) {
913 ui->Print("Mounted /system.\n");
914 }
915 }
916 break;
917 }
918 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800919}
920
Tao Bao99f0d9e2016-10-13 12:46:38 -0700921static void print_property(const char* key, const char* name, void* /* cookie */) {
922 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800923}
924
Tao Baoac9d94d2016-11-03 11:37:15 -0700925static std::string load_locale_from_cache() {
926 if (ensure_path_mounted(LOCALE_FILE) != 0) {
927 LOG(ERROR) << "Can't mount " << LOCALE_FILE;
928 return "";
Doug Zongker02ec6b82012-08-22 17:26:40 -0700929 }
Tao Baoac9d94d2016-11-03 11:37:15 -0700930
931 std::string content;
932 if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
933 PLOG(ERROR) << "Can't read " << LOCALE_FILE;
934 return "";
935 }
936
937 return android::base::Trim(content);
Doug Zongker02ec6b82012-08-22 17:26:40 -0700938}
939
Tao Baoac9d94d2016-11-03 11:37:15 -0700940void ui_print(const char* format, ...) {
941 std::string buffer;
Doug Zongker7c3ae452013-05-14 11:03:02 -0700942 va_list ap;
943 va_start(ap, format);
Tao Baoac9d94d2016-11-03 11:37:15 -0700944 android::base::StringAppendV(&buffer, format, ap);
Doug Zongker7c3ae452013-05-14 11:03:02 -0700945 va_end(ap);
946
Tao Baoac9d94d2016-11-03 11:37:15 -0700947 if (ui != nullptr) {
948 ui->Print("%s", buffer.c_str());
Doug Zongker7c3ae452013-05-14 11:03:02 -0700949 } else {
Tao Baoac9d94d2016-11-03 11:37:15 -0700950 fputs(buffer.c_str(), stdout);
Doug Zongker7c3ae452013-05-14 11:03:02 -0700951 }
952}
953
Tao Baof2ea6d72018-04-26 10:40:36 -0700954static bool is_battery_ok(int* required_battery_level) {
955 struct healthd_config healthd_config = {
956 .batteryStatusPath = android::String8(android::String8::kEmptyString),
957 .batteryHealthPath = android::String8(android::String8::kEmptyString),
958 .batteryPresentPath = android::String8(android::String8::kEmptyString),
959 .batteryCapacityPath = android::String8(android::String8::kEmptyString),
960 .batteryVoltagePath = android::String8(android::String8::kEmptyString),
961 .batteryTemperaturePath = android::String8(android::String8::kEmptyString),
962 .batteryTechnologyPath = android::String8(android::String8::kEmptyString),
963 .batteryCurrentNowPath = android::String8(android::String8::kEmptyString),
964 .batteryCurrentAvgPath = android::String8(android::String8::kEmptyString),
965 .batteryChargeCounterPath = android::String8(android::String8::kEmptyString),
966 .batteryFullChargePath = android::String8(android::String8::kEmptyString),
967 .batteryCycleCountPath = android::String8(android::String8::kEmptyString),
968 .energyCounter = nullptr,
969 .boot_min_cap = 0,
970 .screen_on = nullptr
971 };
972 healthd_board_init(&healthd_config);
Yabin Cui99281df2016-02-17 12:21:52 -0800973
Tao Baof2ea6d72018-04-26 10:40:36 -0700974 android::BatteryMonitor monitor;
975 monitor.init(&healthd_config);
Yabin Cui99281df2016-02-17 12:21:52 -0800976
Tao Baof2ea6d72018-04-26 10:40:36 -0700977 static constexpr int BATTERY_READ_TIMEOUT_IN_SEC = 10;
978 int wait_second = 0;
979 while (true) {
980 int charge_status = monitor.getChargeStatus();
981 // Treat unknown status as charged.
982 bool charged = (charge_status != android::BATTERY_STATUS_DISCHARGING &&
983 charge_status != android::BATTERY_STATUS_NOT_CHARGING);
984 android::BatteryProperty capacity;
985 android::status_t status = monitor.getProperty(android::BATTERY_PROP_CAPACITY, &capacity);
986 ui_print("charge_status %d, charged %d, status %d, capacity %" PRId64 "\n", charge_status,
987 charged, status, capacity.valueInt64);
988 // At startup, the battery drivers in devices like N5X/N6P take some time to load
989 // the battery profile. Before the load finishes, it reports value 50 as a fake
990 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
991 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
992 if (status == 0 && capacity.valueInt64 == 50) {
993 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
994 sleep(1);
995 wait_second++;
996 continue;
997 }
Yabin Cui99281df2016-02-17 12:21:52 -0800998 }
Tao Baof2ea6d72018-04-26 10:40:36 -0700999 // If we can't read battery percentage, it may be a device without battery. In this situation,
1000 // use 100 as a fake battery percentage.
1001 if (status != 0) {
1002 capacity.valueInt64 = 100;
1003 }
1004
1005 // GmsCore enters recovery mode to install package when having enough battery percentage.
1006 // Normally, the threshold is 40% without charger and 20% with charger. So we should check
1007 // battery with a slightly lower limitation.
1008 static constexpr int BATTERY_OK_PERCENTAGE = 20;
1009 static constexpr int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
1010 *required_battery_level = charged ? BATTERY_WITH_CHARGER_OK_PERCENTAGE : BATTERY_OK_PERCENTAGE;
1011 return capacity.valueInt64 >= *required_battery_level;
1012 }
Yabin Cui99281df2016-02-17 12:21:52 -08001013}
1014
Tianjie Xu99b73be2017-11-28 17:23:06 -08001015// Set the retry count to |retry_count| in BCB.
Tianjie Xu72449c92017-05-16 18:07:31 -07001016static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
1017 std::vector<std::string> options;
1018 for (const auto& arg : args) {
1019 if (!android::base::StartsWith(arg, "--retry_count")) {
1020 options.push_back(arg);
Tianjie Xu3c62b672016-02-05 18:25:58 -08001021 }
Tianjie Xu72449c92017-05-16 18:07:31 -07001022 }
Tianjie Xu3c62b672016-02-05 18:25:58 -08001023
Tianjie Xu99b73be2017-11-28 17:23:06 -08001024 // Update the retry counter in BCB.
1025 options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
Tianjie Xu72449c92017-05-16 18:07:31 -07001026 std::string err;
1027 if (!update_bootloader_message(options, &err)) {
1028 LOG(ERROR) << err;
1029 }
Tianjie Xu3c62b672016-02-05 18:25:58 -08001030}
1031
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001032static bool bootreason_in_blacklist() {
Tao Baoefc35592017-01-08 22:45:47 -08001033 std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
1034 if (!bootreason.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -07001035 // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
1036 static const std::vector<std::string> kBootreasonBlacklist{
1037 "kernel_panic",
1038 "Panic",
1039 };
1040 for (const auto& str : kBootreasonBlacklist) {
1041 if (android::base::EqualsIgnoreCase(str, bootreason)) return true;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001042 }
Tao Baoefc35592017-01-08 22:45:47 -08001043 }
1044 return false;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001045}
1046
Tao Bao641fa972018-04-25 18:59:40 -07001047static void log_failure_code(ErrorCode code, const std::string& update_package) {
1048 std::vector<std::string> log_buffer = {
1049 update_package,
1050 "0", // install result
1051 "error: " + std::to_string(code),
1052 };
1053 std::string log_content = android::base::Join(log_buffer, "\n");
1054 const std::string& install_file = Paths::Get().temporary_install_file();
1055 if (!android::base::WriteStringToFile(log_content, install_file)) {
1056 PLOG(ERROR) << "Failed to write " << install_file;
1057 }
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001058
Tao Bao641fa972018-04-25 18:59:40 -07001059 // Also write the info into last_log.
1060 LOG(INFO) << log_content;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001061}
1062
Tao Bao6d99d4b2018-04-25 16:47:04 -07001063int start_recovery(int argc, char** argv) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001064 time_t start = time(nullptr);
1065
Tianjie Xu99b73be2017-11-28 17:23:06 -08001066 printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
1067
1068 load_volume_table();
1069 has_cache = volume_for_mount_point(CACHE_ROOT) != nullptr;
1070
1071 std::vector<std::string> args = get_args(argc, argv);
1072 std::vector<char*> args_to_parse(args.size());
1073 std::transform(args.cbegin(), args.cend(), args_to_parse.begin(),
1074 [](const std::string& arg) { return const_cast<char*>(arg.c_str()); });
1075
Tao Baof9f17342018-04-27 10:44:04 -07001076 static constexpr struct option OPTIONS[] = {
1077 { "just_exit", no_argument, nullptr, 'x' },
1078 { "locale", required_argument, nullptr, 0 },
1079 { "prompt_and_wipe_data", no_argument, nullptr, 0 },
1080 { "reason", required_argument, nullptr, 0 },
1081 { "retry_count", required_argument, nullptr, 0 },
1082 { "security", no_argument, nullptr, 0 },
1083 { "show_text", no_argument, nullptr, 't' },
1084 { "shutdown_after", no_argument, nullptr, 0 },
1085 { "sideload", no_argument, nullptr, 0 },
1086 { "sideload_auto_reboot", no_argument, nullptr, 0 },
1087 { "update_package", required_argument, nullptr, 0 },
1088 { "wipe_ab", no_argument, nullptr, 0 },
1089 { "wipe_cache", no_argument, nullptr, 0 },
1090 { "wipe_data", no_argument, nullptr, 0 },
1091 { "wipe_package_size", required_argument, nullptr, 0 },
1092 { nullptr, 0, nullptr, 0 },
1093 };
1094
Tianjie Xu99b73be2017-11-28 17:23:06 -08001095 const char* update_package = nullptr;
1096 bool should_wipe_data = false;
1097 bool should_prompt_and_wipe_data = false;
1098 bool should_wipe_cache = false;
1099 bool should_wipe_ab = false;
1100 size_t wipe_package_size = 0;
1101 bool show_text = false;
1102 bool sideload = false;
1103 bool sideload_auto_reboot = false;
1104 bool just_exit = false;
1105 bool shutdown_after = false;
1106 int retry_count = 0;
1107 bool security_update = false;
Jerry Zhang2dea53e2018-05-02 17:15:03 -07001108 std::string locale;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001109
1110 int arg;
1111 int option_index;
1112 while ((arg = getopt_long(args_to_parse.size(), args_to_parse.data(), "", OPTIONS,
1113 &option_index)) != -1) {
1114 switch (arg) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001115 case 't':
1116 show_text = true;
1117 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001118 case 'x':
1119 just_exit = true;
1120 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001121 case 0: {
1122 std::string option = OPTIONS[option_index].name;
Tao Baof9f17342018-04-27 10:44:04 -07001123 if (option == "locale") {
1124 locale = optarg;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001125 } else if (option == "prompt_and_wipe_data") {
1126 should_prompt_and_wipe_data = true;
Tao Baof9f17342018-04-27 10:44:04 -07001127 } else if (option == "reason") {
1128 reason = optarg;
1129 } else if (option == "retry_count") {
1130 android::base::ParseInt(optarg, &retry_count, 0);
1131 } else if (option == "security") {
1132 security_update = true;
1133 } else if (option == "sideload") {
1134 sideload = true;
1135 } else if (option == "sideload_auto_reboot") {
1136 sideload = true;
1137 sideload_auto_reboot = true;
1138 } else if (option == "shutdown_after") {
1139 shutdown_after = true;
1140 } else if (option == "update_package") {
1141 update_package = optarg;
1142 } else if (option == "wipe_ab") {
1143 should_wipe_ab = true;
1144 } else if (option == "wipe_cache") {
1145 should_wipe_cache = true;
1146 } else if (option == "wipe_data") {
1147 should_wipe_data = true;
1148 } else if (option == "wipe_package_size") {
1149 android::base::ParseUint(optarg, &wipe_package_size);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001150 }
1151 break;
1152 }
1153 case '?':
1154 LOG(ERROR) << "Invalid command argument";
1155 continue;
Doug Zongker9270a202012-01-09 15:16:13 -08001156 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001157 }
Doug Zongker9270a202012-01-09 15:16:13 -08001158
Tianjie Xu99b73be2017-11-28 17:23:06 -08001159 if (locale.empty()) {
1160 if (has_cache) {
1161 locale = load_locale_from_cache();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001162 }
1163
Tao Baoac9d94d2016-11-03 11:37:15 -07001164 if (locale.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -07001165 static constexpr const char* DEFAULT_LOCALE = "en-US";
Tianjie Xu99b73be2017-11-28 17:23:06 -08001166 locale = DEFAULT_LOCALE;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001167 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001168 }
Tao Baoac9d94d2016-11-03 11:37:15 -07001169
Tianjie Xu99b73be2017-11-28 17:23:06 -08001170 printf("locale is [%s]\n", locale.c_str());
1171 printf("stage is [%s]\n", stage.c_str());
1172 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001173
Tianjie Xu99b73be2017-11-28 17:23:06 -08001174 Device* device = make_device();
1175 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
1176 printf("Quiescent recovery mode.\n");
1177 ui = new StubRecoveryUI();
1178 } else {
1179 ui = device->GetUI();
1180
1181 if (!ui->Init(locale)) {
1182 printf("Failed to initialize UI, use stub UI instead.\n");
1183 ui = new StubRecoveryUI();
1184 }
1185 }
Jerry Zhang2dea53e2018-05-02 17:15:03 -07001186 device->SetUI(ui);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001187
1188 // Set background string to "installing security update" for security update,
1189 // otherwise set it to "installing system update".
1190 ui->SetSystemUpdateText(security_update);
1191
1192 int st_cur, st_max;
1193 if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
1194 ui->SetStage(st_cur, st_max);
1195 }
1196
1197 ui->SetBackground(RecoveryUI::NONE);
1198 if (show_text) ui->ShowText(true);
1199
1200 sehandle = selinux_android_file_context_handle();
1201 selinux_android_set_sehandle(sehandle);
1202 if (!sehandle) {
1203 ui->Print("Warning: No file_contexts\n");
1204 }
1205
1206 device->StartRecovery();
1207
1208 printf("Command:");
1209 for (const auto& arg : args) {
1210 printf(" \"%s\"", arg.c_str());
1211 }
1212 printf("\n\n");
1213
1214 property_list(print_property, nullptr);
1215 printf("\n");
1216
1217 ui->Print("Supported API: %d\n", kRecoveryApiVersion);
1218
1219 int status = INSTALL_SUCCESS;
1220
1221 if (update_package != nullptr) {
1222 // It's not entirely true that we will modify the flash. But we want
1223 // to log the update attempt since update_package is non-NULL.
1224 modified_flash = true;
1225
Tao Baof2ea6d72018-04-26 10:40:36 -07001226 int required_battery_level;
1227 if (retry_count == 0 && !is_battery_ok(&required_battery_level)) {
1228 ui->Print("battery capacity is not enough for installing package: %d%% needed\n",
1229 required_battery_level);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001230 // Log the error code to last_install when installation skips due to
1231 // low battery.
1232 log_failure_code(kLowBattery, update_package);
1233 status = INSTALL_SKIPPED;
Tianjie Xua6f49bd2018-03-26 14:32:11 -07001234 } else if (retry_count == 0 && bootreason_in_blacklist()) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001235 // Skip update-on-reboot when bootreason is kernel_panic or similar
1236 ui->Print("bootreason is in the blacklist; skip OTA installation\n");
1237 log_failure_code(kBootreasonInBlacklist, update_package);
1238 status = INSTALL_SKIPPED;
Dmitri Plotnikov8706a982017-04-18 08:28:26 -07001239 } else {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001240 // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
1241 // identify the interrupted update due to unexpected reboots.
1242 if (retry_count == 0) {
1243 set_retry_bootloader_message(retry_count + 1, args);
Tao Bao7022f332017-07-25 09:52:36 -07001244 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001245
Tao Bao641fa972018-04-25 18:59:40 -07001246 status = install_package(update_package, &should_wipe_cache, true, retry_count);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001247 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1248 wipe_cache(false, device);
1249 }
1250 if (status != INSTALL_SUCCESS) {
1251 ui->Print("Installation aborted.\n");
Tao Baoaac9d9f2018-04-29 23:38:59 -07001252
1253 // When I/O error or bspatch/imgpatch error happens, reboot and retry installation
1254 // RETRY_LIMIT times before we abandon this OTA update.
1255 static constexpr int RETRY_LIMIT = 4;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001256 if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
Jerry Zhang152933a2018-05-02 16:56:00 -07001257 copy_logs(modified_flash, has_cache);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001258 retry_count += 1;
1259 set_retry_bootloader_message(retry_count, args);
1260 // Print retry count on screen.
1261 ui->Print("Retry attempt %d\n", retry_count);
1262
1263 // Reboot and retry the update
1264 if (!reboot("reboot,recovery")) {
1265 ui->Print("Reboot failed\n");
1266 } else {
1267 while (true) {
1268 pause();
1269 }
1270 }
Tianjie Xud9d16292017-04-20 18:08:21 -07001271 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001272 // If this is an eng or userdebug build, then automatically
1273 // turn the text display on if the script fails so the error
1274 // message is visible.
1275 if (is_ro_debuggable()) {
1276 ui->ShowText(true);
Tao Baoc679f932015-03-30 09:43:49 -07001277 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001278 }
Doug Zongker8674a722010-09-15 11:08:23 -07001279 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001280 } else if (should_wipe_data) {
1281 if (!wipe_data(device)) {
1282 status = INSTALL_ERROR;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001283 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001284 } else if (should_prompt_and_wipe_data) {
1285 ui->ShowText(true);
1286 ui->SetBackground(RecoveryUI::ERROR);
1287 if (!prompt_and_wipe_data(device)) {
1288 status = INSTALL_ERROR;
Tao Bao75238632015-05-27 14:46:17 -07001289 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001290 ui->ShowText(false);
1291 } else if (should_wipe_cache) {
1292 if (!wipe_cache(false, device)) {
1293 status = INSTALL_ERROR;
1294 }
1295 } else if (should_wipe_ab) {
1296 if (!wipe_ab_device(wipe_package_size)) {
1297 status = INSTALL_ERROR;
1298 }
1299 } else if (sideload) {
1300 // 'adb reboot sideload' acts the same as user presses key combinations
1301 // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
1302 // display will NOT be turned on by default. And it will reboot after
1303 // sideload finishes even if there are errors. Unless one turns on the
1304 // text display during the installation. This is to enable automated
1305 // testing.
1306 if (!sideload_auto_reboot) {
1307 ui->ShowText(true);
1308 }
Tao Bao641fa972018-04-25 18:59:40 -07001309 status = apply_from_adb(&should_wipe_cache);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001310 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1311 if (!wipe_cache(false, device)) {
1312 status = INSTALL_ERROR;
1313 }
1314 }
1315 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1316 if (sideload_auto_reboot) {
1317 ui->Print("Rebooting automatically.\n");
1318 }
1319 } else if (!just_exit) {
1320 // If this is an eng or userdebug build, automatically turn on the text display if no command
1321 // is specified. Note that this should be called before setting the background to avoid
1322 // flickering the background image.
1323 if (is_ro_debuggable()) {
1324 ui->ShowText(true);
1325 }
1326 status = INSTALL_NONE; // No command specified
1327 ui->SetBackground(RecoveryUI::NO_COMMAND);
1328 }
1329
1330 if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
1331 ui->SetBackground(RecoveryUI::ERROR);
1332 if (!ui->IsTextVisible()) {
1333 sleep(5);
1334 }
1335 }
1336
1337 Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
1338 // 1. If the recovery menu is visible, prompt and wait for commands.
1339 // 2. If the state is INSTALL_NONE, wait for commands. (i.e. In user build, manually reboot into
1340 // recovery to sideload a package.)
1341 // 3. sideload_auto_reboot is an option only available in user-debug build, reboot the device
1342 // without waiting.
1343 // 4. In all other cases, reboot the device. Therefore, normal users will observe the device
1344 // reboot after it shows the "error" screen for 5s.
1345 if ((status == INSTALL_NONE && !sideload_auto_reboot) || ui->IsTextVisible()) {
1346 Device::BuiltinAction temp = prompt_and_wait(device, status);
1347 if (temp != Device::NO_ACTION) {
1348 after = temp;
1349 }
1350 }
1351
1352 // Save logs and clean up before rebooting or shutting down.
Jerry Zhang2dea53e2018-05-02 17:15:03 -07001353 finish_recovery(device);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001354
1355 switch (after) {
1356 case Device::SHUTDOWN:
1357 ui->Print("Shutting down...\n");
1358 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,");
1359 break;
1360
1361 case Device::REBOOT_BOOTLOADER:
1362 ui->Print("Rebooting to bootloader...\n");
1363 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
1364 break;
1365
1366 default:
1367 ui->Print("Rebooting...\n");
1368 reboot("reboot,");
1369 break;
1370 }
1371 while (true) {
1372 pause();
1373 }
1374 // Should be unreachable.
1375 return EXIT_SUCCESS;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001376}