写得较好的浅析 Android recovery mode分析

来源:互联网 发布:windows官方主题 云 编辑:程序博客网 时间:2024/06/04 19:50

# recovery介绍

从事android的开发者对recovery一定不会陌生.它主要用来擦除数据和进行系统升级.擦除数据就是为了上层恢复出厂设置提供接口.主要有wipe data和wipe cache.升级又分为在线升级和离线升级.在线升级一般通过网络(3G,WIFI,GPRS)下载资源包,然后进入recovery进行升级.离线升级一般把下载好的update包放至SD卡,然后选择从SD卡更新的方式进行升级(我们常常说的刷机就是这样).并且recovery还可以根据自己的需求定制.下面这个是HTC早期的recovery.

                                                                                 

# 使用recovery的不同情形

·恢复出厂设置

<1>用户在系统设置中选择“恢复出厂设置”
<
2>系统将"wipe_data"命令写入/cache/recovery/command
<3>系统重启,并进入recover模式(/sbin/recovery)
<4>get_args()将"boot-recovery"和"--wipe_data"写入BCB(bootloader control block)
<5>erase_volume("/data") 格式化(擦除)DATA分区
<6>erase_volume("/cache")格式化(擦除)CACHE分区
<7>finish_recovery() 擦除BCB
<8>reboot

·刷机

<1>用户按下power+volume down键进入recovery mode
<2>用户选择Flash Zip from SD card(以上图为例)
<3>update_directory将"boot-recovery"和"recovery\n"写入BCB
<4>在really_install_package中验证更新包
<5>在try_update_binary执行2进制更新文件"/tmp/update_binary"
<6>利用pipe通信更新recovery UI
<7>finish_recovery() 擦除BCB
<8>reboot

# SD卡升级流程(也就是我们一般所说的刷机)

1.首先从main函数入手吧
<有些注释直接添加到了源代码中>
[html] view plaincopyprint?
  1. int  
  2. main(int argc, char **argv) {  
  3.     time_t start = time(NULL);  
  4.   
  5.     // If these fail, there's not really anywhere to complain...  
  6.     freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL);  
  7.     freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL);  
  8.     printf("Starting recovery on %s", ctime(&start));  
  9.   
  10.     device_ui_init(&ui_parameters);  
  11.     ui_init();  
  12.     ui_set_background(BACKGROUND_ICON_INSTALLING);  
  13.     load_volume_table();  
  14.     get_args(&argc, &argv);//write the bcb partition  
  15.   
  16.     int previous_runs = 0;  
  17.     const char *send_intent = NULL;  
  18.     const char *update_package = NULL;  
  19.     int wipe_data = 0wipe_cache = 0;  
  20.   
  21.     int arg;  
  22.     while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {  
  23.         switch (arg) {  
  24.         case 'p': previous_runs = atoi(optarg); break;  
  25.         case 's': send_intent = optarg; break;  
  26.         case 'u': update_package = optarg; break;  
  27.         case 'w': wipe_data = wipe_cache = 1; break;  
  28.         case 'c': wipe_cache = 1; break;  
  29.         case 't': ui_show_text(1); break;  
  30.         case '?':  
  31.             LOGE("Invalid command argument\n");  
  32.             continue;  
  33.         }  
  34.     }  
  35.   
  36.     ......  
  37.     ......//省略部分代码  
  38.     ......  
  39.     int status = INSTALL_SUCCESS;  
  40.   
  41.     if (update_package != NULL) {  
  42.         status = install_package(update_package);  
  43.         if (status != INSTALL_SUCCESS) ui_print("Installation aborted.\n");  
  44.     } else if (wipe_data) {  
  45.         if (device_wipe_data()) status = INSTALL_ERROR;  
  46.         if (erase_volume("/data")) status = INSTALL_ERROR;  
  47.         if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;  
  48.         if (status != INSTALL_SUCCESS) ui_print("Data wipe failed.\n");  
  49.     } else if (wipe_cache) {  
  50.         if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;  
  51.         if (status != INSTALL_SUCCESS) ui_print("Cache wipe failed.\n");  
  52.     } else {  
  53.         status = INSTALL_ERROR;  // No command specified  
  54.     }  
  55.   
  56.     if (status != INSTALL_SUCCESS) ui_set_background(BACKGROUND_ICON_ERROR);  
  57.     if (status != INSTALL_SUCCESS || ui_text_visible()) {  
  58.         prompt_and_wait();  
  59.     }  
  60.   
  61.     // Otherwise, get ready to boot the main system...  
  62.     finish_recovery(send_intent);  
  63.     ui_print("Rebooting...\n");  
  64.     android_reboot(ANDROID_RB_RESTART, 0, 0);  
  65.     return EXIT_SUCCESS;  
  66. }  
while循环中读取recovery的command参数(/cache/recovery/command),在main函数中的OPTIONS中可以看到不同选项的定义
[cpp] view plaincopyprint?
  1. "send_intent", required_argument, NULL, 's' },  
  2. "update_package", required_argument, NULL, 'u' },  
  3. "wipe_data", no_argument, NULL, 'w' },  
  4. "wipe_cache", no_argument, NULL, 'c' },  
  5. "show_text", no_argument, NULL, 't' },  
之后根据设置的不同标志变量执行不同的操作,比如写入了"wipe_data"就调用erase_volume擦洗data和cache分区.如果没有任何标志变量被设置则
进入prompt_and_wait函数中.

2.进入prompt_and_wait,准备接收用户按键.

[cpp] view plaincopyprint?
  1. static void  
  2. prompt_and_wait() {  
  3.     char** headers = prepend_title((const char**)MENU_HEADERS);  
  4.   
  5.     for (;;) {  
  6.         finish_recovery(NULL);  
  7.         ui_reset_progress();  
  8.   
  9.         int chosen_item = get_menu_selection(headers, MENU_ITEMS, 0, 0);  
  10.         //get the item of you selection in the menu   
  11.   
  12.         // device-specific code may take some action here.  It may  
  13.         // return one of the core actions handled in the switch  
  14.         // statement below.  
  15.         chosen_item = device_perform_action(chosen_item);  
  16.   
  17.         int status;  
  18.         switch (chosen_item) {  
  19.             case ITEM_REBOOT:  
  20.                 return;  
  21.   
  22.             case ITEM_WIPE_DATA:  
  23.                 wipe_data(ui_text_visible());//wipe the data partition  
  24.                 if (!ui_text_visible()) return;  
  25.                 break;  
  26.   
  27.             case ITEM_WIPE_CACHE://wipe cache partition  
  28.                 ui_print("\n-- Wiping cache...\n");  
  29.                 erase_volume("/cache");  
  30.                 ui_print("Cache wipe complete.\n");  
  31.                 if (!ui_text_visible()) return;  
  32.                 break;  
  33.   
  34.             case ITEM_APPLY_SDCARD://update system use the zip in the SDcard  
  35.                 status = update_directory(SDCARD_ROOT, SDCARD_ROOT);//both "/sdcard"  
  36.                 if (status >= 0) {  
  37.                     if (status != INSTALL_SUCCESS) {  
  38.                         ui_set_background(BACKGROUND_ICON_ERROR);  
  39.                         ui_print("Installation aborted.\n");  
  40.                     } else if (!ui_text_visible()) {  
  41.                         return;  // reboot if logs aren't visible  
  42.                     } else {  
  43.                         ui_print("\nInstall from sdcard complete.\n");  
  44.                     }  
  45.                 }  
  46.                 break;  
  47.             case ITEM_APPLY_CACHE:  
  48.                 // Don't unmount cache at the end of this.  
  49.                 status = update_directory(CACHE_ROOT, NULL);  
  50.                 if (status >= 0) {  
  51.                     if (status != INSTALL_SUCCESS) {  
  52.                         ui_set_background(BACKGROUND_ICON_ERROR);  
  53.                         ui_print("Installation aborted.\n");  
  54.                     } else if (!ui_text_visible()) {  
  55.                         return;  // reboot if logs aren't visible  
  56.                     } else {  
  57.                         ui_print("\nInstall from cache complete.\n");  
  58.                     }  
  59.                 }  
  60.                 break;  
  61.   
  62.         }  
  63.     }  
  64. }  

这个函数比较简单,调用get_menu_selection进入循环等待用户按键.这里会根据用户选择进行分支处理.这段代码比较简单.就不用多介绍了.
配个简单的调用图,更直观一点


3.当我们选择从SD卡更新后,流程直接走到update_directory.

[cpp] view plaincopyprint?
  1. update_directory(const char* path, const char* unmount_when_done) {  
  2.     ensure_path_mounted(path);//ensure the path is mounted  
  3.   
  4.     const char* MENU_HEADERS[] = { "Choose a package to install:",  
  5.                                    path,  
  6.                                    "",  
  7.                                    NULL };  
  8.     DIR* d;  
  9.     struct dirent* de;  
  10.     d = opendir(path);  
  11.     if (d == NULL) {  
  12.         LOGE("error opening %s: %s\n", path, strerror(errno));  
  13.         if (unmount_when_done != NULL) {  
  14.             ensure_path_unmounted(unmount_when_done);  
  15.         }  
  16.         return 0;  
  17.     }  
  18.   
  19.     char** headers = prepend_title(MENU_HEADERS);//prepare the frameUI  
  20.   
  21.     int d_size = 0;  
  22.     int d_alloc = 10;  
  23.     char** dirs = malloc(d_alloc * sizeof(char*));//40 bytes 10 char * eg:char * [10]  
  24.     int z_size = 1;  
  25.     int z_alloc = 10;  
  26.     char** zips = malloc(z_alloc * sizeof(char*));  
  27.     zips[0] = strdup("../");//duplicate the string "../"  
  28.     ......  
  29.     ......//省略部分代码  
  30.     ......  
  31.     int result;  
  32.     int chosen_item = 0;  
  33.     do {  
  34.         chosen_item = get_menu_selection(headers, zips, 1, chosen_item);  
  35.   
  36.         char* item = zips[chosen_item];  
  37.         int item_len = strlen(item);  
  38.         if (chosen_item == 0) {          // item 0 is always "../"  
  39.             // go up but continue browsing (if the caller is update_directory)  
  40.             result = -1;  
  41.             break;  
  42.         } else if (item[item_len-1] == '/') {  
  43.             // recurse down into a subdirectory  
  44.             char new_path[PATH_MAX];  
  45.             strlcpy(new_path, path, PATH_MAX);  
  46.             strlcat(new_path, "/", PATH_MAX);//append the full path   
  47.             strlcat(new_path, item, PATH_MAX);  
  48.             new_path[strlen(new_path)-1] = '\0';  // truncate the trailing '/'  
  49.             result = update_directory(new_path, unmount_when_done);  
  50.             if (result >= 0) break;  
  51.         } else {  
  52.             // selected a zip file:  attempt to install it, and return  
  53.             // the status to the caller.  
  54.             char new_path[PATH_MAX];  
  55.             strlcpy(new_path, path, PATH_MAX);  
  56.             strlcat(new_path, "/", PATH_MAX);  
  57.             strlcat(new_path, item, PATH_MAX);  
  58.   
  59.             ui_print("\n-- Install %s ...\n", path);  
  60.             set_sdcard_update_bootloader_message();//set the boot command with boot-recovery  
  61.             char* copy = copy_sideloaded_package(new_path);//copy update.zip into SIDELOAD_TEMP_DIR  
  62.             if (unmount_when_done != NULL) {  
  63.                 ensure_path_unmounted(unmount_when_done);  
  64.             }  
  65.             if (copy) {  
  66.                 result = install_package(copy);//important function to install the update.zip file  
  67.                 free(copy);  
  68.             } else {  
  69.                 result = INSTALL_ERROR;  
  70.             }  
  71.             break;  
  72.         }  
  73.     } while (true);  
  74.   
  75.     int i;  
  76.     for (i = 0; i < z_size; ++i) free(zips[i]);  
  77.     free(zips);  
  78.     free(headers);  
  79.   
  80.     if (unmount_when_done != NULL) {  
  81.         ensure_path_unmounted(unmount_when_done);  
  82.     }  
  83.     return result;  
  84. }  

上半部分的代码就是在SD card下的文件.并把路径记录下来,然后根据名称排序.然后处理用户按键(这里powe键是确认)
·当用户选择第一个条目“../”,直接跳转到上级目录,并且继续浏览文件.
·当用户选择的条目以"/"开头,直接进入子目录
·其它情况表明,该条目就是zip包.写入BCB,copy 更新包至临时目录.直接转入install_package
实际上这里就是一个基于frameUI的一个建议文件浏览器.只能显示zip文件和目录.
老规矩,配个调用图方便理解函数


4.进入install_package函数之前,先看看set_sdcard_update_bootloader_message
[cpp] view plaincopyprint?
  1. static void  
  2. set_sdcard_update_bootloader_message() {  
  3.     struct bootloader_message boot;  
  4.     memset(&boot, 0, sizeof(boot));  
  5.     strlcpy(boot.command, "boot-recovery"sizeof(boot.command));  
  6.     strlcpy(boot.recovery, "recovery\n"sizeof(boot.recovery));  
  7.     set_bootloader_message(&boot);  
  8. }  
构造了bootloader_message结构之后,其余工作就交给set_bootloader_message去做.里面根据不同的/misc类别去
写mtd或者block.有兴趣的可以深入了解.
5.install_package只是简单的包装了一下really_install_package.在really_install_package中更新了一下背景,验证了更新包.
验证成功则转入try_update_binary函数.
[cpp] view plaincopyprint?
  1. static int  
  2. try_update_binary(const char *path, ZipArchive *zip) {  
  3.     const ZipEntry* binary_entry =  
  4.             mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME);  
  5.     if (binary_entry == NULL) {  
  6.         mzCloseZipArchive(zip);  
  7.         return INSTALL_CORRUPT;  
  8.     }  
  9.   
  10.     char* binary = "/tmp/update_binary";  
  11.     unlink(binary);  
  12.     int fd = creat(binary, 0755);  
  13.     if (fd < 0) {  
  14.         mzCloseZipArchive(zip);  
  15.         LOGE("Can't make %s\n", binary);  
  16.         return 1;  
  17.     }  
  18.     bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd);  
  19.     close(fd);  
  20.     mzCloseZipArchive(zip);  
  21.   
  22.     if (!ok) {  
  23.         LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME);  
  24.         return 1;  
  25.     }  
  26.   
  27.     int pipefd[2];  
  28.     pipe(pipefd);//use pipe  
  29.   
  30.     // When executing the update binary contained in the package, the  
  31.     // arguments passed are:  
  32.     //  
  33.     //   - the version number for this interface  
  34.     //  
  35.     //   - an fd to which the program can write in order to update the  
  36.     //     progress bar.  The program can write single-line commands:  
  37.     //  
  38.     //        progress <frac> <secs>  
  39.     //            fill up the next <frac> part of of the progress bar  
  40.     //            over <secs> seconds.  If <secs> is zero, use  
  41.     //            set_progress commands to manually control the  
  42.     //            progress of this segment of the bar  
  43.     //  
  44.     //        set_progress <frac>  
  45.     //            <frac> should be between 0.0 and 1.0; sets the  
  46.     //            progress bar within the segment defined by the most  
  47.     //            recent progress command.  
  48.     //  
  49.     //        firmware <"hboot"|"radio"> <filename>  
  50.     //            arrange to install the contents of <filename> in the  
  51.     //            given partition on reboot.  
  52.     //  
  53.     //            (API v2: <filename> may start with "PACKAGE:" to  
  54.     //            indicate taking a file from the OTA package.)  
  55.     //  
  56.     //            (API v3: this command no longer exists.)  
  57.     //  
  58.     //        ui_print <string>  
  59.     //            display <string> on the screen.  
  60.     //  
  61.     //   - the name of the package zip file.  
  62.     //  
  63.   
  64.     char** args = malloc(sizeof(char*) * 5);  
  65.     args[0] = binary;  
  66.     args[1] = EXPAND(RECOVERY_API_VERSION);   // defined in Android.mk  
  67.     args[2] = malloc(10);  
  68.     sprintf(args[2], "%d", pipefd[1]);  
  69.     args[3] = (char*)path;  
  70.     args[4] = NULL;  
  71.   
  72.     pid_t pid = fork();  
  73.     if (pid == 0) {//in child process   
  74.         close(pipefd[0]);  
  75.         execv(binary, args);  
  76.         fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno));  
  77.         _exit(-1);  
  78.     }  
  79.     close(pipefd[1]);  
  80.   
  81.     char buffer[1024];  
  82.     FILE* from_child = fdopen(pipefd[0], "r");  
  83.     while (fgets(buffer, sizeof(buffer), from_child) != NULL) {  
  84.         char* command = strtok(buffer, " \n");  
  85.         if (command == NULL) {  
  86.             continue;  
  87.         } else if (strcmp(command, "progress") == 0) {  
  88.             char* fraction_s = strtok(NULL, " \n");  
  89.             char* seconds_s = strtok(NULL, " \n");  
  90.   
  91.             float fraction = strtof(fraction_s, NULL);  
  92.             int seconds = strtol(seconds_s, NULL, 10);  
  93.   
  94.             ui_show_progress(fraction * (1-VERIFICATION_PROGRESS_FRACTION),  
  95.                              seconds);  
  96.         } else if (strcmp(command, "set_progress") == 0) {  
  97.             char* fraction_s = strtok(NULL, " \n");  
  98.             float fraction = strtof(fraction_s, NULL);  
  99.             ui_set_progress(fraction);  
  100.         } else if (strcmp(command, "ui_print") == 0) {  
  101.             char* str = strtok(NULL, "\n");  
  102.             if (str) {  
  103.                 ui_print("%s", str);  
  104.             } else {  
  105.                 ui_print("\n");  
  106.             }  
  107.         } else {  
  108.             LOGE("unknown command [%s]\n", command);  
  109.         }  
  110.     }  
  111.     fclose(from_child);  
  112.   
  113.     int status;  
  114.     waitpid(pid, &status, 0);  
  115.     if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {  
  116.         LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status));  
  117.         return INSTALL_ERROR;  
  118.     }  
  119.   
  120.     return INSTALL_SUCCESS;  
  121. }  
fork了一个进程去执行update_binary,并且父进程于子进程通过管道进行通信,父进程根据子进程的数据去更新进度.
不过在android代码注释里看到有更新固件的选项.在代码中又没有发现,应该是被和谐了吧.

6.之后返回至main中,执行finish_recovery
[cpp] view plaincopyprint?
  1. static void  
  2. finish_recovery(const char *send_intent) {  
  3.     // By this point, we're ready to return to the main system...  
  4.     if (send_intent != NULL) {  
  5.         FILE *fp = fopen_path(INTENT_FILE, "w");  
  6.         if (fp == NULL) {  
  7.             LOGE("Can't open %s\n", INTENT_FILE);  
  8.         } else {  
  9.             fputs(send_intent, fp);  
  10.             check_and_fclose(fp, INTENT_FILE);  
  11.         }  
  12.     }  
  13.   
  14.     // Copy logs to cache so the system can find out what happened.  
  15.     copy_log_file(LOG_FILE, true);  
  16.     copy_log_file(LAST_LOG_FILE, false);  
  17.     chmod(LAST_LOG_FILE, 0640);  
  18.   
  19.     // Reset to mormal system boot so recovery won't cycle indefinitely.  
  20.     struct bootloader_message boot;  
  21.     memset(&boot, 0, sizeof(boot));  
  22.     set_bootloader_message(&boot);  
  23.   
  24.     // Remove the command file, so recovery won't repeat indefinitely.  
  25.     if (ensure_path_mounted(COMMAND_FILE) != 0 ||  
  26.         (unlink(COMMAND_FILE) && errno != ENOENT)) {  
  27.         LOGW("Can't unlink %s\n", COMMAND_FILE);  
  28.     }  
  29.   
  30.     sync();  // For good measure.  
  31. }  

最后在finish_recovery中copy安装日志,清理BCB,调用sync()进行文件系统同步.



0 0
原创粉丝点击