一、recovery.cpp 文件分析
recovery 可以理解为一个最小系统,上电开机后,uboot引导kernel,然后加载recovery镜像文件recovery.img(正常启动加载rootfs),之后执行镜像中的init 进程。在init.rc中有如下两行代码:
service recovery /sbin/recovery
seclabel u:r:recovery:s0
由此可知,接下来执行recovery,recovery是由bootable/recovery/recovery.cpp生成,下面就来分析一下recovery.cpp。
int
main(int argc, char **argv) {
time_t start = time(NULL);
redirect_stdio(TEMPORARY_LOG_FILE);
// If this binary is started with the single argument "--adbd", 如果二进制文件使用单个参数"--adbd"启动
// instead of being the normal recovery binary, it turns into kind 而不是正常的recovery启动(不带参数即为正常启动)
// of a stripped-down version of adbd that only supports the 它变成精简版命令时只支持sideload命令。它必须是一个正确可用的参数
// 'sideload' command. Note this must be a real argument, not 不在/cache/recovery/command中,也不受B2B控制
// anything in the command file or bootloader control block; the
// only way recovery should be run with this argument is when it 是apply_from_adb()的副本
// starts a copy of itself from the apply_from_adb() function.
if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
adb_main(0, DEFAULT_ADB_PORT);
return 0;
}
printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
load_volume_table(); //加载并建立分区表
get_args(&argc, &argv); //从传入的参数或/cache/recovery/command文件中得到相应的命令
const char *send_intent = NULL;
const char *update_package = NULL;
bool should_wipe_data = false;
bool should_wipe_cache = false;
bool show_text = false;
bool sideload = false;
bool sideload_auto_reboot = false;
bool just_exit = false;
bool shutdown_after = false;
int arg;
while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) { //while循环解析command或者传入的参数,并把对应的功能设置为true或给相应的变量赋值
switch (arg) {
case 'i': send_intent = optarg; break;
case 'u': update_package = optarg; break;
case 'w': should_wipe_data = true; break;
case 'c': should_wipe_cache = true; break;
case 't': show_text = true; break;
case 's': sideload = true; break;
case 'a': sideload = true; sideload_auto_reboot = true; break;
case 'x': just_exit = true; break;
case 'l': locale = optarg; break;
case 'g': {
if (stage == NULL || *stage == '\0') {
char buffer[20] = "1/";
strncat(buffer, optarg, sizeof(buffer)-3);
stage = strdup(buffer);
}
break;
}
case 'p': shutdown_after = true; break;
case 'r': reason = optarg; break;
case '?':
LOGE("Invalid command argument\n");
continue;
}
}
if (locale == NULL) { //设置语言
load_locale_from_cache();
}
printf("locale is [%s]\n", locale);
printf("stage is [%s]\n", stage);
printf("reason is [%s]\n", reason);
/*初始化UI*/
Device* device = make_device();
ui = device->GetUI();
gCurrentUI = ui;
show_text = true;
ui->SetLocale(locale);
ui->Init();
int st_cur, st_max;
if (stage != NULL && sscanf(stage, "%d/%d", &st_cur, &st_max) == 2) {
ui->SetStage(st_cur, st_max);
}
ui->SetBackground(RecoveryUI::NONE); //设置recovery界面背景
if (show_text) ui->ShowText(true); //设置界面上是否能够显示字符,使能ui->print函数开关
struct selinux_opt seopts[] = { //设置selinux权限,以后会有专门的文章或专题讲解selinux,这里不做讲解
{ SELABEL_OPT_PATH, "/file_contexts" }
};
sehandle = selabel_open(SELABEL_CTX_FILE, seopts, 1);
if (!sehandle) {
ui->Print("Warning: No file_contexts\n");
}
device->StartRecovery(); //此函数为空,没做任何事情
printf("Command:"); //打印/cache/recovery/command的参数
for (arg = 0; arg < argc; arg++) {
printf(" \"%s\"", argv[arg]);
}
printf("\n");
if (update_package) { //根据下面的注释可知,对old "root" 路径进行修改,把其放在/cache/文件中 。 当安装包的路径是以CACHE:开头,把其改为/cache/开头
// For backwards compatibility on the cache partition only, if
// we're given an old 'root' path "CACHE:foo", change it to
// "/cache/foo".
if (strncmp(update_package, "CACHE:", 6) == 0) {
int len = strlen(update_package) + 10;
char* modified_path = (char*)malloc(len);
strlcpy(modified_path, "/cache/", len);
strlcat(modified_path, update_package+6, len);
printf("(replacing path \"%s\" with \"%s\")\n",
update_package, modified_path);
update_package = modified_path;
}
}
printf("\n");
property_list(print_property, NULL); //打印属性列表,其实现没有找到代码在哪里,找到后会更新此文章
printf("\n");
ui->Print("Supported API: %d\n", RECOVERY_API_VERSION);
int status = INSTALL_SUCCESS; //设置标志位,默认为INSTALL_SUCCESS
if (update_package != NULL) { //install package情况
status = install_package(update_package, &should_wipe_cache, TEMPORARY_INSTALL_FILE, true); //安装ota升级包
if (status == INSTALL_SUCCESS && should_wipe_cache) { //如果安装前点击了清楚缓存,执行下面的语句,安装成功后清楚缓存
wipe_cache(false, device);
}
if (status != INSTALL_SUCCESS) { //安装失败,打印log,并根据is_ro_debuggable()决定是否打开ui->print信息(此信息显示在屏幕上)
ui->Print("Installation aborted.\n");
if (is_ro_debuggable()) {
ui->ShowText(true);
}
}
} else if (should_wipe_data) { //只清除用户数据
if (!wipe_data(false, device)) {
status = INSTALL_ERROR;
}
} else if (should_wipe_cache) { //只清除缓存
if (!wipe_cache(false, device)) {
status = INSTALL_ERROR;
}
} else if (sideload) { //执行adb reboot sideload命令后会跑到这个代码段
// 'adb reboot sideload' acts the same as user presses key combinations
// to enter the sideload mode. When 'sideload-auto-reboot' is used, text
// display will NOT be turned on by default. And it will reboot after
// sideload finishes even if there are errors. Unless one turns on the
// text display during the installation. This is to enable automated
// testing.
if (!sideload_auto_reboot) {
ui->ShowText(true);
}
status = apply_from_adb(ui, &should_wipe_cache, TEMPORARY_INSTALL_FILE);
if (status == INSTALL_SUCCESS && should_wipe_cache) {
if (!wipe_cache(false, device)) {
status = INSTALL_ERROR;
}
}
ui->Print("\nInstall from ADB complete (status: %d).\n", status);
if (sideload_auto_reboot) {
ui->Print("Rebooting automatically.\n");
}
} else if (!just_exit) { //当command命令中有just_exit字段
status = INSTALL_NONE; // No command specified
ui->SetBackground(RecoveryUI::NONE);
if (is_ro_debuggable()) {
ui->ShowText(true);
}
}
if (!sideload_auto_reboot && (status == INSTALL_ERROR || status == INSTALL_CORRUPT)) { //安装失败,复制log信息到/cache/recovery/。如果进行了wipe_data/wipe_cache/apply_from_sdcard(也就是修改了flash),
//直接return结束recovery,否则现实error背景图片
copy_logs();
ui->SetBackground(RecoveryUI::ERROR);
}
Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
if ((status != INSTALL_SUCCESS && !sideload_auto_reboot) || ui->IsTextVisible()) { //status在just_exit中已经变为none,会执行此if语句
#ifdef SUPPORT_UTF8_MULTILINGUAL
ml_select(device);
#endif
Device::BuiltinAction temp = prompt_and_wait(device, status); //prompt_and_wait()函数是个死循环 开始显示recovery选项 并处理用户通过按键或者触摸屏的选项,如Reboot system等
if (temp != Device::NO_ACTION) {
after = temp;
}
}
finish_recovery(send_intent);
switch (after) {
case Device::SHUTDOWN:
ui->Print("Shutting down...\n");
property_set(ANDROID_RB_PROPERTY, "shutdown,");
break;
case Device::REBOOT_BOOTLOADER:
ui->Print("Rebooting to bootloader...\n");
property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
break;
default:
char reason[PROPERTY_VALUE_MAX];
snprintf(reason, PROPERTY_VALUE_MAX, "reboot,%s", device->GetRebootReason());
ui->Print("Rebooting...\n");
property_set(ANDROID_RB_PROPERTY, reason);
break;
}
sleep(5);
return EXIT_SUCCESS;
}
二、细节描述
1. ui初始化
……
Device* device = make_device();
ui = device->GetUI();
gCurrentUI = ui;
ui->Init();
ui->SetLocale(locale);
……
prompt_and_wait(device, status); /*显示recovery升级 用户选择界面*/
这个函数初始化了一个基于framebuffer的简单ui界面,也就是recovery主界面。整个界面分为两部分:recovery背景图片(android小机器人)和现实安装进度的进度条。另外还启动了两个线程,一个用于处理进度条的显示(progress_thread
),另一个用于响应用户的按键(input_thread
)。
2. get_arg() recovery参数
get_args(&argc, &argv);
……
while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
switch (arg) {
case 'p': previous_runs = atoi(optarg); break;
case 'u': update_package = optarg; break;
case 's': send_intent = optarg; break;
case 'w': wipe_data = wipe_cache = 1; break;
case 'c': wipe_cache = 1; break;
case 'm': show_menu = 1; break;
}
}
get_args(&argc, &argv);
获取BCB和cache分区的recovery参数:
(1). get_bootloader_message(&boot);
读取BCB数据块到boot变量中,BCB数据块结构如下:
struct bootloader_message {
char command[32];
char status[32];
char recovery[1024];
};
然后判断recovery域是否为空,若非空解析recovery域中的内容;
若BCB中没有命令行参数,从cache/recovery/command中获取,如下:
FILE *fp = fopen_path(COMMAND_FILE, "r");
if (fp != NULL) {
char *argv0 = (*argv)[0];
*argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
(*argv)[0] = argv0; // use the same program name
char buf[MAX_ARG_LENGTH];
for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
if (!fgets(buf, sizeof(buf), fp))
break;
LOGI("Gets (%s)\n", buf);
(*argv)[*argc] = strdup(strtok(buf, "\r\n")); // Strip newline.
}
check_and_fclose(fp, COMMAND_FILE);
printf("Got arguments from %s\n", COMMAND_FILE);
}
最后将”boot-recovery”写入boot.command,”recovery\n”写入boot.recovery;并且将这两个状态更新到misc分区的BCB数据块中。
这样做的目的是:当recovery被中断时,下次上电开机,系统还是进入recovery,防止系统跑飞
strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
int i;
for (i = 1; i < *argc; ++i) {
strlcat(boot.recovery, (*argv)[i], sizeof(boot.recovery));
strlcat(boot.recovery, "\n", sizeof(boot.recovery));
}
set_bootloader_message(&boot); //将boot的内容设置到BCB数据块
整个过程如图:
3.解析获得的参数
int arg;
while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
switch (arg) {
case 'u': update_package = optarg; break;
case 'w': wipe_data = wipe_cache = 1; break;
case 'c': wipe_cache = 1; break;
case '?':
LOGE("Invalid command argument\n");
continue;
}
}
根据参数内容执行操作,update_package,wipe_data 或 wipe_cache
;
其中最重要的是update_package,下面分析升级过程。
4.update_package过程
status = install_package(update_package, &should_wipe_cache, TEMPORARY_INSTALL_FILE, true);
此函数安装升级包,update_package是路径;
static const char *TEMPORARY_INSTALL_FILE = “/tmp/last_install”; TEMPORARY_INSTALL_FILE存放升级时的log信息,后面会把此文件复制到/cache/recovery/文件中;
bootable/recovery/install.cpp
int
install_package(const char* path, bool* wipe_cache, const char* install_file,
bool needs_mount)
{
modified_flash = true;
FILE* install_log = fopen_path(install_file, "w"); //打开log文件
if (install_log) {
fputs(path, install_log); //向log文件中写入安装包路径
fputc('\n', install_log);
} else {
LOGE("failed to open last_install: %s\n", strerror(errno));
}
int result;
if (setup_install_mounts() != 0) { //mount /tmp和/cache ,成功返回0
LOGE("failed to set up expected mounts for install; aborting\n");
result = INSTALL_ERROR;
} else {
result = really_install_package(path, wipe_cache, needs_mount); //执行安装
}
if (install_log) { //向log文件写入安装结果,成功写入1,失败写入0
fputc(result == INSTALL_SUCCESS ? '1' : '0', install_log);
fputc('\n', install_log);
fclose(install_log);
}
return result;
}
static int
really_install_package(const char *path, bool* wipe_cache, bool needs_mount)
{
ui->SetBackground(RecoveryUI::INSTALLING_UPDATE); //设置背景为安装背景,就是小机器人
ui->Print("Finding update package...\n");
// Give verification half the progress bar...
ui->SetProgressType(RecoveryUI::DETERMINATE); //初始化升级时进度条
ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME); //设置进度条时间
LOGI("Update location: %s\n", path);
// Map the update package into memory.
ui->Print("Opening update package...\n");
if (path && needs_mount) { //判断升级包所在路径是否被挂在
ensure_path_mounted((path[0] == '@') ? path + 1 : path);
}
MemMapping map; //把升级包路径映射到内存中
if (sysMapFile(path, &map) != 0) {
LOGE("failed to map file\n");
return INSTALL_CORRUPT;
}
int numKeys; //加载密钥
Certificate* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
if (loadedKeys == NULL) {
LOGE("Failed to load keys\n");
return INSTALL_CORRUPT;
}
LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);
ui->Print("Verifying update package...\n");
int err; //校验升级包是否被修改,一般在调试ota升级时会把这段代码进行屏蔽,使本地编译的升级包可以正常升级
err = verify_file(map.addr, map.length, loadedKeys, numKeys);
free(loadedKeys);
LOGI("verify_file returned %d\n", err);
if (err != VERIFY_SUCCESS) {
LOGE("signature verification failed\n");
sysReleaseMap(&map);
return INSTALL_CORRUPT;
}
/* Try to open the package.
*/
ZipArchive zip; //打开升级包
err = mzOpenZipArchive(map.addr, map.length, &zip);
if (err != 0) {
LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
sysReleaseMap(&map); //这行代码很重要,只有失败时才释放map内存,结束安装。提前释放map内存会导致下面代码无法正常进行,界面上会显示失败。
return INSTALL_CORRUPT;
}
/* Verify and install the contents of the package.
*/
ui->Print("Installing update...\n");
ui->SetEnableReboot(false);
int result = try_update_binary(path, &zip, wipe_cache); //执行安装包内的执行脚本
ui->SetEnableReboot(true);
ui->Print("\n");
sysReleaseMap(&map);
#ifdef USE_MDTP
/* If MDTP update failed, return an error such that recovery will not finish. */
if (result == INSTALL_SUCCESS) {
if (!mdtp_update()) {
ui->Print("Unable to verify integrity of /system for MDTP, update aborted.\n");
return INSTALL_ERROR;
}
ui->Print("Successfully verified integrity of /system for MDTP.\n");
}
#endif /* USE_MDTP */
return result;
}
4.执行升级包中的升级文件
try_update_binary(const char* path, ZipArchive* zip, bool* wipe_cache) {
const ZipEntry* binary_entry = //在升级包中查找是否存在META-INF/com/google/android/update-binary文件
mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME);
if (binary_entry == NULL) {
mzCloseZipArchive(zip);
return INSTALL_CORRUPT;
}
const char* binary = "/tmp/update_binary"; //在tmp中创建临时文件夹,权限755
unlink(binary);
int fd = creat(binary, 0755);
if (fd < 0) {
mzCloseZipArchive(zip);
LOGE("Can't make %s\n", binary);
return INSTALL_ERROR;
}
bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd); //把update.zip升级包解压到/tmp/update_binary文件夹中
sync();
close(fd);
mzCloseZipArchive(zip);
if (!ok) {
LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME);
return INSTALL_ERROR;
}
int pipefd[2];
pipe(pipefd);
// When executing the update binary contained in the package, the
// arguments passed are:
//
// - the version number for this interface
//
// - an fd to which the program can write in order to update the
// progress bar. The program can write single-line commands:
//
// progress <frac> <secs>
// fill up the next <frac> part of of the progress bar
// over <secs> seconds. If <secs> is zero, use
// set_progress commands to manually control the
// progress of this segment of the bar.
//
// set_progress <frac>
// <frac> should be between 0.0 and 1.0; sets the
// progress bar within the segment defined by the most
// recent progress command.
//
// firmware <"hboot"|"radio"> <filename>
// arrange to install the contents of <filename> in the
// given partition on reboot.
//
// (API v2: <filename> may start with "PACKAGE:" to
// indicate taking a file from the OTA package.)
//
// (API v3: this command no longer exists.)
//
// ui_print <string>
// display <string> on the screen.
//
// wipe_cache
// a wipe of cache will be performed following a successful
// installation.
//
// clear_display
// turn off the text display.
//
// enable_reboot
// packages can explicitly request that they want the user
// to be able to reboot during installation (useful for
// debugging packages that don't exit).
//
// - the name of the package zip file.
//
const char** args = (const char**)malloc(sizeof(char*) * 5); //创建指针数组,并分配内存
args[0] = binary; //[0]存放字符串 "/tmp/update_binary" ,也就是升级包解压的目的地址
args[1] = EXPAND(RECOVERY_API_VERSION); // defined in Android.mk //[1]存放RECOVERY_API_VERSION,在Android.mk中定义,我的值为3 RECOVERY_API_VERSION := 3
char* temp = (char*)malloc(10);
sprintf(temp, "%d", pipefd[1]);
args[2] = temp;
args[3] = (char*)path; //[3]存放update.zip路径
args[4] = NULL;
pid_t pid = fork(); //创建一个新进程,为子进程
if (pid == 0) { //进程创建成功,执行META-INF/com/google/android/update-binary脚本,给脚本传入参数args
umask(022);
close(pipefd[0]);
execv(binary, (char* const*)args);
fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno));
_exit(-1);
}
close(pipefd[1]);
*wipe_cache = false;
char buffer[1024];
FILE* from_child = fdopen(pipefd[0], "r");
while (fgets(buffer, sizeof(buffer), from_child) != NULL) { //父进程通过管道pipe读取子进程的值,使用strtok分割函数把子进程传过来的参数进行解析,执行相应的ui修改
char* command = strtok(buffer, " \n");
if (command == NULL) {
continue;
} else if (strcmp(command, "progress") == 0) {
char* fraction_s = strtok(NULL, " \n");
char* seconds_s = strtok(NULL, " \n");
float fraction = strtof(fraction_s, NULL);
int seconds = strtol(seconds_s, NULL, 10);
ui->ShowProgress(fraction * (1-VERIFICATION_PROGRESS_FRACTION), seconds);
} else if (strcmp(command, "set_progress") == 0) {
char* fraction_s = strtok(NULL, " \n");
float fraction = strtof(fraction_s, NULL);
ui->SetProgress(fraction);
} else if (strcmp(command, "ui_print") == 0) {
char* str = strtok(NULL, "\n");
if (str) {
ui->Print("%s", str);
} else {
ui->Print("\n");
}
fflush(stdout);
} else if (strcmp(command, "wipe_cache") == 0) {
*wipe_cache = true;
} else if (strcmp(command, "clear_display") == 0) {
ui->SetBackground(RecoveryUI::NONE);
} else if (strcmp(command, "enable_reboot") == 0) {
// packages can explicitly request that they want the user
// to be able to reboot during installation (useful for
// debugging packages that don't exit).
ui->SetEnableReboot(true);
} else {
LOGE("unknown command [%s]\n", command);
}
}
fclose(from_child);
int status;
waitpid(pid, &status, 0);
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status));
return INSTALL_ERROR;
}
return INSTALL_SUCCESS;
}
try_update_binary流程:
1.查找META-INF/com/google/android/update-binary二进制脚本
2.解压update.zip包到/tmp/update_binary
3.创建子进程,执行update-binary二进制安装脚本,并通过管道与父进程通信,父进程更新ui界面。