blob: 9a9890de0b459448ce8c5bfa5da41ded0da62334 [file] [log] [blame]
Tao Bao6d99d4b2018-04-25 16:47:04 -07001/*
2 * Copyright (C) 2018 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 Bao42c45e22018-07-31 09:37:12 -070017#include <dlfcn.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070018#include <errno.h>
19#include <fcntl.h>
20#include <getopt.h>
21#include <inttypes.h>
22#include <limits.h>
23#include <linux/fs.h>
24#include <stdarg.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070025#include <stdio.h>
26#include <stdlib.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070027#include <string.h>
28#include <sys/stat.h>
29#include <sys/types.h>
30#include <time.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070031#include <unistd.h>
32
Jerry Zhangf5e319a2018-05-04 11:24:10 -070033#include <string>
34#include <vector>
Tao Bao6d99d4b2018-04-25 16:47:04 -070035
Jerry Zhangf5e319a2018-05-04 11:24:10 -070036#include <android-base/file.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070037#include <android-base/logging.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070038#include <android-base/properties.h>
39#include <android-base/strings.h>
40#include <bootloader_message/bootloader_message.h>
41#include <cutils/android_reboot.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070042#include <private/android_logger.h> /* private pmsg functions */
Jerry Zhangf5e319a2018-05-04 11:24:10 -070043#include <selinux/android.h>
44#include <selinux/label.h>
45#include <selinux/selinux.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070046
47#include "common.h"
Jerry Zhangf5e319a2018-05-04 11:24:10 -070048#include "device.h"
Jerry Zhang152933a2018-05-02 16:56:00 -070049#include "logging.h"
Tao Bao6d99d4b2018-04-25 16:47:04 -070050#include "minadbd/minadbd.h"
51#include "otautil/paths.h"
Jerry Zhangf5e319a2018-05-04 11:24:10 -070052#include "otautil/sysutil.h"
53#include "recovery.h"
54#include "roots.h"
55#include "stub_ui.h"
Tao Bao6d99d4b2018-04-25 16:47:04 -070056#include "ui.h"
57
Jerry Zhangf5e319a2018-05-04 11:24:10 -070058static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
59static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
60
61static constexpr const char* CACHE_ROOT = "/cache";
62
63bool has_cache = false;
64
65RecoveryUI* ui = nullptr;
66struct selabel_handle* sehandle;
67
Tao Bao6d99d4b2018-04-25 16:47:04 -070068static void UiLogger(android::base::LogId /* id */, android::base::LogSeverity severity,
69 const char* /* tag */, const char* /* file */, unsigned int /* line */,
70 const char* message) {
71 static constexpr char log_characters[] = "VDIWEF";
72 if (severity >= android::base::ERROR && ui != nullptr) {
73 ui->Print("E:%s\n", message);
74 } else {
75 fprintf(stdout, "%c:%s\n", log_characters[severity], message);
76 }
77}
78
Jerry Zhangf5e319a2018-05-04 11:24:10 -070079// command line args come from, in decreasing precedence:
80// - the actual command line
81// - the bootloader control block (one per line, after "recovery")
82// - the contents of COMMAND_FILE (one per line)
83static std::vector<std::string> get_args(const int argc, char** const argv) {
84 CHECK_GT(argc, 0);
85
86 bootloader_message boot = {};
87 std::string err;
88 if (!read_bootloader_message(&boot, &err)) {
89 LOG(ERROR) << err;
90 // If fails, leave a zeroed bootloader_message.
91 boot = {};
92 }
93 stage = std::string(boot.stage);
94
95 if (boot.command[0] != 0) {
96 std::string boot_command = std::string(boot.command, sizeof(boot.command));
97 LOG(INFO) << "Boot command: " << boot_command;
98 }
99
100 if (boot.status[0] != 0) {
101 std::string boot_status = std::string(boot.status, sizeof(boot.status));
102 LOG(INFO) << "Boot status: " << boot_status;
103 }
104
105 std::vector<std::string> args(argv, argv + argc);
106
107 // --- if arguments weren't supplied, look in the bootloader control block
108 if (args.size() == 1) {
109 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
110 std::string boot_recovery(boot.recovery);
111 std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
112 if (!tokens.empty() && tokens[0] == "recovery") {
113 for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
114 // Skip empty and '\0'-filled tokens.
115 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
116 }
117 LOG(INFO) << "Got " << args.size() << " arguments from boot message";
118 } else if (boot.recovery[0] != 0) {
119 LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
120 }
121 }
122
123 // --- if that doesn't work, try the command file (if we have /cache).
124 if (args.size() == 1 && has_cache) {
125 std::string content;
126 if (ensure_path_mounted(COMMAND_FILE) == 0 &&
127 android::base::ReadFileToString(COMMAND_FILE, &content)) {
128 std::vector<std::string> tokens = android::base::Split(content, "\n");
129 // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
130 // COMMAND_FILE doesn't use filename as the first argument).
131 for (auto it = tokens.begin(); it != tokens.end(); it++) {
132 // Skip empty and '\0'-filled tokens.
133 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
134 }
135 LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
136 }
137 }
138
139 // Write the arguments (excluding the filename in args[0]) back into the
140 // bootloader control block. So the device will always boot into recovery to
141 // finish the pending work, until finish_recovery() is called.
142 std::vector<std::string> options(args.cbegin() + 1, args.cend());
143 if (!update_bootloader_message(options, &err)) {
144 LOG(ERROR) << "Failed to set BCB message: " << err;
145 }
146
147 return args;
148}
149
150static std::string load_locale_from_cache() {
151 if (ensure_path_mounted(LOCALE_FILE) != 0) {
152 LOG(ERROR) << "Can't mount " << LOCALE_FILE;
153 return "";
154 }
155
156 std::string content;
157 if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
158 PLOG(ERROR) << "Can't read " << LOCALE_FILE;
159 return "";
160 }
161
162 return android::base::Trim(content);
163}
164
Tao Bao6d99d4b2018-04-25 16:47:04 -0700165static void redirect_stdio(const char* filename) {
166 int pipefd[2];
167 if (pipe(pipefd) == -1) {
168 PLOG(ERROR) << "pipe failed";
169
170 // Fall back to traditional logging mode without timestamps. If these fail, there's not really
171 // anywhere to complain...
172 freopen(filename, "a", stdout);
173 setbuf(stdout, nullptr);
174 freopen(filename, "a", stderr);
175 setbuf(stderr, nullptr);
176
177 return;
178 }
179
180 pid_t pid = fork();
181 if (pid == -1) {
182 PLOG(ERROR) << "fork failed";
183
184 // Fall back to traditional logging mode without timestamps. If these fail, there's not really
185 // anywhere to complain...
186 freopen(filename, "a", stdout);
187 setbuf(stdout, nullptr);
188 freopen(filename, "a", stderr);
189 setbuf(stderr, nullptr);
190
191 return;
192 }
193
194 if (pid == 0) {
195 /// Close the unused write end.
196 close(pipefd[1]);
197
198 auto start = std::chrono::steady_clock::now();
199
200 // Child logger to actually write to the log file.
201 FILE* log_fp = fopen(filename, "ae");
202 if (log_fp == nullptr) {
203 PLOG(ERROR) << "fopen \"" << filename << "\" failed";
204 close(pipefd[0]);
205 _exit(EXIT_FAILURE);
206 }
207
208 FILE* pipe_fp = fdopen(pipefd[0], "r");
209 if (pipe_fp == nullptr) {
210 PLOG(ERROR) << "fdopen failed";
211 check_and_fclose(log_fp, filename);
212 close(pipefd[0]);
213 _exit(EXIT_FAILURE);
214 }
215
216 char* line = nullptr;
217 size_t len = 0;
218 while (getline(&line, &len, pipe_fp) != -1) {
219 auto now = std::chrono::steady_clock::now();
220 double duration =
221 std::chrono::duration_cast<std::chrono::duration<double>>(now - start).count();
222 if (line[0] == '\n') {
223 fprintf(log_fp, "[%12.6lf]\n", duration);
224 } else {
225 fprintf(log_fp, "[%12.6lf] %s", duration, line);
226 }
227 fflush(log_fp);
228 }
229
230 PLOG(ERROR) << "getline failed";
231
232 free(line);
233 check_and_fclose(log_fp, filename);
234 close(pipefd[0]);
235 _exit(EXIT_FAILURE);
236 } else {
237 // Redirect stdout/stderr to the logger process. Close the unused read end.
238 close(pipefd[0]);
239
240 setbuf(stdout, nullptr);
241 setbuf(stderr, nullptr);
242
243 if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
244 PLOG(ERROR) << "dup2 stdout failed";
245 }
246 if (dup2(pipefd[1], STDERR_FILENO) == -1) {
247 PLOG(ERROR) << "dup2 stderr failed";
248 }
249
250 close(pipefd[1]);
251 }
252}
253
254int main(int argc, char** argv) {
255 // We don't have logcat yet under recovery; so we'll print error on screen and log to stdout
256 // (which is redirected to recovery.log) as we used to do.
257 android::base::InitLogging(argv, &UiLogger);
258
259 // Take last pmsg contents and rewrite it to the current pmsg session.
260 static constexpr const char filter[] = "recovery/";
261 // Do we need to rotate?
262 bool do_rotate = false;
263
264 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logbasename, &do_rotate);
265 // Take action to refresh pmsg contents
266 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logrotate, &do_rotate);
267
268 // If this binary is started with the single argument "--adbd", instead of being the normal
269 // recovery binary, it turns into kind of a stripped-down version of adbd that only supports the
270 // 'sideload' command. Note this must be a real argument, not anything in the command file or
271 // bootloader control block; the only way recovery should be run with this argument is when it
272 // starts a copy of itself from the apply_from_adb() function.
273 if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
274 minadbd_main();
275 return 0;
276 }
277
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700278 time_t start = time(nullptr);
279
Tao Bao6d99d4b2018-04-25 16:47:04 -0700280 // redirect_stdio should be called only in non-sideload mode. Otherwise we may have two logger
281 // instances with different timestamps.
282 redirect_stdio(Paths::Get().temporary_log_file().c_str());
283
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700284 printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
285
286 load_volume_table();
287 has_cache = volume_for_mount_point(CACHE_ROOT) != nullptr;
288
289 std::vector<std::string> args = get_args(argc, argv);
Tao Bao1700cc42018-07-16 22:09:59 -0700290 auto args_to_parse = StringVectorToNullTerminatedArray(args);
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700291
292 static constexpr struct option OPTIONS[] = {
293 { "locale", required_argument, nullptr, 0 },
294 { "show_text", no_argument, nullptr, 't' },
295 { nullptr, 0, nullptr, 0 },
296 };
297
298 bool show_text = false;
299 std::string locale;
300
301 int arg;
302 int option_index;
Tao Bao1700cc42018-07-16 22:09:59 -0700303 while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700304 &option_index)) != -1) {
305 switch (arg) {
306 case 't':
307 show_text = true;
308 break;
309 case 0: {
310 std::string option = OPTIONS[option_index].name;
311 if (option == "locale") {
312 locale = optarg;
313 }
314 break;
315 }
316 }
317 }
Jerry Zhang49fd5d22018-05-17 12:54:41 -0700318 optind = 1;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700319
320 if (locale.empty()) {
321 if (has_cache) {
322 locale = load_locale_from_cache();
323 }
324
325 if (locale.empty()) {
326 static constexpr const char* DEFAULT_LOCALE = "en-US";
327 locale = DEFAULT_LOCALE;
328 }
329 }
330
331 printf("locale is [%s]\n", locale.c_str());
332
Tao Bao42c45e22018-07-31 09:37:12 -0700333 static constexpr const char* kDefaultLibRecoveryUIExt = "librecovery_ui_ext.so";
334 // Intentionally not calling dlclose(3) to avoid potential gotchas (e.g. `make_device` may have
335 // handed out pointers to code or static [or thread-local] data and doesn't collect them all back
336 // in on dlclose).
337 void* librecovery_ui_ext = dlopen(kDefaultLibRecoveryUIExt, RTLD_NOW);
338
339 using MakeDeviceType = decltype(&make_device);
340 MakeDeviceType make_device_func = nullptr;
341 if (librecovery_ui_ext == nullptr) {
342 printf("Failed to dlopen %s: %s\n", kDefaultLibRecoveryUIExt, dlerror());
343 } else {
344 reinterpret_cast<void*&>(make_device_func) = dlsym(librecovery_ui_ext, "make_device");
345 if (make_device_func == nullptr) {
346 printf("Failed to dlsym make_device: %s\n", dlerror());
347 }
348 }
349
350 Device* device;
351 if (make_device_func == nullptr) {
352 printf("Falling back to the default make_device() instead\n");
353 device = make_device();
354 } else {
355 printf("Loading make_device from %s\n", kDefaultLibRecoveryUIExt);
356 device = (*make_device_func)();
357 }
358
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700359 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
360 printf("Quiescent recovery mode.\n");
361 device->ResetUI(new StubRecoveryUI());
362 } else {
363 if (!device->GetUI()->Init(locale)) {
364 printf("Failed to initialize UI; using stub UI instead.\n");
365 device->ResetUI(new StubRecoveryUI());
366 }
367 }
368 ui = device->GetUI();
369
370 if (!has_cache) {
371 device->RemoveMenuItemForAction(Device::WIPE_CACHE);
372 }
373
374 ui->SetBackground(RecoveryUI::NONE);
375 if (show_text) ui->ShowText(true);
376
377 sehandle = selinux_android_file_context_handle();
378 selinux_android_set_sehandle(sehandle);
379 if (!sehandle) {
380 ui->Print("Warning: No file_contexts\n");
381 }
382
383 Device::BuiltinAction after = start_recovery(device, args);
384
385 switch (after) {
386 case Device::SHUTDOWN:
387 ui->Print("Shutting down...\n");
388 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,");
389 break;
390
391 case Device::REBOOT_BOOTLOADER:
392 ui->Print("Rebooting to bootloader...\n");
393 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
394 break;
395
396 default:
397 ui->Print("Rebooting...\n");
398 reboot("reboot,");
399 break;
400 }
401 while (true) {
402 pause();
403 }
404 // Should be unreachable.
405 return EXIT_SUCCESS;
Tao Bao6d99d4b2018-04-25 16:47:04 -0700406}