recovery 工作流程
一、recovery.cpp 文件分析
recovery 可以理解为一个最小系统,上电开机后,uboot引导kernel,然后加载recovery镜像文件recovery.img(正常启动加载rootfs),之后执行镜像中的init 进程。在init.rc中有如下两行代码:
service recovery /sbin/recoveryseclabel 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_SUCCESSif (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 specifiedui->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_MULTILINGUALml_select(device);
#endifDevice::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 namechar 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.cppint
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 ,成功返回0LOGE("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,失败写入0fputc(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中创建临时文件夹,权限755unlink(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 := 3char* 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脚本,给脚本传入参数argsumask(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界面。
recovery 工作流程相关推荐
- Android系统Recovery工作原理之使用update.zip升级过程分析(五)
Android系统Recovery工作原理之使用update.zip升级过程分析(五)---update.zip包从上层进入Recovery服务文章开头我们就提到update.zip包来源有两种,一个 ...
- 如何在Go中编写防弹代码:不会失败的服务器工作流程
by Tal Kol 通过塔尔科尔 如何在Go中编写防弹代码:不会失败的服务器工作流程 (How to write bulletproof code in Go: a workflow for ser ...
- Android系统Recovery工作原理之使用update.zip升级过程分析(一)
这篇及以后的篇幅将通过分析update.zip包在具体Android系统升级的过程,来理解Android系统中Recovery模式服务的工作原理.我们先从update.zip包的制作开始,然后是And ...
- Android系统Recovery工作原理之使用update.zip升级过程分析(一)---update.zip包的制作【转】...
本文转载自:http://blog.csdn.net/mu0206mu/article/details/7399822 这篇及以后的篇幅将通过分析update.zip包在具体Android系统升级的过 ...
- android recovery模式流程
前言: 前几天做了通过T卡安装gms应该,也做了在recovery中强制删除的动作,不过这些都是在eng-release版本软件中测试的.现在上面 要求以后发布user-release版本的软件,所 ...
- ceph原理及工作流程浅析
ceph工作原理及工作流程浅析 其命名和UCSC(Ceph诞生地)的吉祥物有关,这个吉祥物是"Sammy",一个香蕉色的蛞蝓,就是头足类中无壳的软体动物.这些有多触角的头足类动物, ...
- GPU—加速数据科学工作流程
GPU-加速数据科学工作流程 GPU-ACCELERATE YOUR DATA SCIENCE WORKFLOWS 传统上,数据科学工作流程是缓慢而繁琐的,依赖于cpu来加载.过滤和操作数据,训练和部 ...
- python爬虫之Scrapy框架的post请求和核心组件的工作 流程
python爬虫之Scrapy框架的post请求和核心组件的工作 流程 一 Scrapy的post请求的实现 在爬虫文件中的爬虫类继承了Spider父类中的start_urls,该方法就可以对star ...
- WifiP2pSettings工作流程
本文为<深入理解Android Wi-Fi.NFC和GPS卷>读书笔记,Android源码为Android 5.1 Android平台中,P2P操作用户只需执行如下三个步骤: 1)进入Wi ...
- Blender+SP+UE5游戏艺术工作流程学习
Blender到虚幻引擎5 Blender游戏艺术 Blender for Game Art 你会学到: 如何在Blender中创建三维模型 UV如何展开和布局 如何在Substance Painte ...
最新文章
- linux 中root用户与普通用户的切换
- Django框架(二十)—— Django rest_framework-认证组件
- 【Java集合源码剖析】TreeMap源码剖析
- 如何安装和使用RAutomation
- linux系统下pid的取值范围了解一下
- CTFshow 文件上传 web159
- Java 8 Stream Tutorial--转
- UVA dp题目汇总
- bzoj 4573: [Zjoi2016]大森林
- JAVA实现概率计算(数字不同范围按照不同几率产生随机数)
- 如何在家搭建oracle,oracle基本操作,自己亲手做过了
- (译)2019年前端性能优化清单 — 上篇
- Tomcat下载与安装
- LSB 图像隐写与提取算法
- 联想电脑虚拟化开启方法
- PDF文件如何编辑?这两种方法是我一直在用的
- Python 去除重复行数据
- python标准库复数运算包cmath
- 2022电大国家开放大学网上形考任务-实用卫生统计学非免费(非答案)
- 新手使用APICloud可视化开发搭建商城主页
热门文章
- 分享七个超好用的免费工具网站,每一个都是神器!
- 计算机桌面图片怎么设置大小,电脑桌面的图标大小怎么调整?
- 12级计算机动画制作专业,计算机专业技术12级是什么意思?
- zynq-7000系列基于zynq-zed的vivado初步设计之linux下控制PL扩展的UART
- 北航计算机学院本科优秀毕业论文,北航本科毕业论文
- 1976年图灵奖--米凯尔·拉宾和达纳·斯科特简介
- Kettle之定时运行Job
- 【必应】Bing自动提交收录python脚本
- Codeforces 227E/226C Anniversary 斐波那契数列性质+矩阵快速幂
- IP-guard功能模块简介