轉載請注明來源:cuixiaolei的技術博客
這篇文章主要通過分析高通recovery目錄下的recovery.cpp源碼,對recovery啟動流程有一個宏觀的了解。MTK和高通的recovery幾乎一樣,只是使用自己家的mt_xxx文件。
為什么要分析recovery.cpp這個文件?
我們知道,當我們通過按鍵或者應用進入recovery模式,實質是kernel后加載recovery.img,kernel起來后執行的第一個進程就 是init,此進程會讀入init.rc啟動相應的服務。在recovery模式中,啟動的服務是執行recovery可執行文件,此文件是
bootable/recovery/recovery.cpp文件生成,我們就從recovery.cpp文件開始分析。此出可參考我的另一篇文章android-ramdisk.img分析、recovery.img&boot.img執行過程
下面的代碼位於bootable/recovery/etc/init.rc,由此可知,進入recovery模式后會執行sbin /recovery,此文件是bootable/recovery/recovery.cpp生成(可查看對應目錄的Android.mk查看),所以recovery.cpp是recovery模式的入口。
service recovery /sbin/recovery
seclabel u:r:recovery:s0
開始主題
bootable/recovery/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; }
上面的代碼中已經把recovery啟動后的流程描述的差不多了,下面是一點細節性的描述
1.獲取command命令
get_args(&argc, &argv);
此函數沒有什么可說的,先判斷事都有參數傳進來,如果有解析傳入的命令,否走從/cache/recovery/command文件中解析命令
注意,此函數會先把struct bootloader_message boot寫入到misc分區,目的是防止斷電等原因導致關機,開機后lk會從misc分區中讀取相關信息,如果發現是"boot-recovery"會再次進入recovery模式,misc分區會在退出recovery時被清除,以至於可以正常開機,如果手機每次都是進入recovery而不能正常開機,可以分析是否沒有清楚misc分區。
struct bootloader_message { char command[32]; char status[32]; char recovery[768]; // The 'recovery' field used to be 1024 bytes. It has only ever // been used to store the recovery command line, so 768 bytes // should be plenty. We carve off the last 256 bytes to store the // stage string (for multistage packages) and possible future // expansion. char stage[32]; char reserved[224]; };
// command line args come from, in decreasing precedence: // - the actual command line // - the bootloader control block (one per line, after "recovery") // - the contents of COMMAND_FILE (one per line) static void get_args(int *argc, char ***argv) { struct bootloader_message boot; memset(&boot, 0, sizeof(boot)); get_bootloader_message(&boot); // this may fail, leaving a zeroed structure stage = strndup(boot.stage, sizeof(boot.stage)); if (boot.command[0] != 0 && boot.command[0] != 255) { LOGI("Boot command: %.*s\n", (int)sizeof(boot.command), boot.command); } if (boot.status[0] != 0 && boot.status[0] != 255) { LOGI("Boot status: %.*s\n", (int)sizeof(boot.status), boot.status); } // --- if arguments weren't supplied, look in the bootloader control block if (*argc <= 1) { boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination const char *arg = strtok(boot.recovery, "\n"); if (arg != NULL && !strcmp(arg, "recovery")) { *argv = (char **) malloc(sizeof(char *) * MAX_ARGS); (*argv)[0] = strdup(arg); for (*argc = 1; *argc < MAX_ARGS; ++*argc) { if ((arg = strtok(NULL, "\n")) == NULL) break; (*argv)[*argc] = strdup(arg); } LOGI("Got arguments from boot message\n"); } else if (boot.recovery[0] != 0 && boot.recovery[0] != 255) { LOGE("Bad boot message\n\"%.20s\"\n", boot.recovery); } } // --- if that doesn't work, try the command file if (*argc <= 1) { FILE *fp = fopen_path(COMMAND_FILE, "r"); if (fp != NULL) { char *token; 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; token = strtok(buf, "\r\n"); if (token != NULL) { (*argv)[*argc] = strdup(token); // Strip newline. } else { --*argc; } } check_and_fclose(fp, COMMAND_FILE); LOGI("Got arguments from %s\n", COMMAND_FILE); } } // --> write the arguments we have back into the bootloader control block // always boot into recovery after this (until finish_recovery() is called) 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); }
2.解析command命令
while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {...}
可知從/cache/recovery/command文件中獲取並與OPTIONS列表參數進行比較,把相應的字符串賦值或者修改相應的變量
//while循環解析command或者傳入的參數,並把對應的功能設置為true或給相應的變量賦值,下面是command中可能的命令及其value /* static const struct option OPTIONS[] = { { "send_intent", required_argument, NULL, 'i' }, { "update_package", required_argument, NULL, 'u' }, { "wipe_data", no_argument, NULL, 'w' }, { "wipe_cache", no_argument, NULL, 'c' }, { "show_text", no_argument, NULL, 't' }, { "sideload", no_argument, NULL, 's' }, { "sideload_auto_reboot", no_argument, NULL, 'a' }, { "just_exit", no_argument, NULL, 'x' }, { "locale", required_argument, NULL, 'l' }, { "stages", required_argument, NULL, 'g' }, { "shutdown_after", no_argument, NULL, 'p' }, { "reason", required_argument, NULL, 'r' }, { NULL, 0, NULL, 0 }, }; */
3.安裝升級包
status = install_package(update_package, &should_wipe_cache, TEMPORARY_INSTALL_FILE, true);
此函數安裝升級包,update_package是路徑,從/cache/recovery/command文件中解析
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; }
int setup_install_mounts() { //掛在/cache /tmp分區 if (fstab == NULL) { LOGE("can't set up install mounts: no fstab loaded\n"); return -1; } for (int i = 0; i < fstab->num_entries; ++i) { Volume* v = fstab->recs + i; if (strcmp(v->mount_point, "/tmp") == 0 || strcmp(v->mount_point, "/cache") == 0) { if (ensure_path_mounted(v->mount_point) != 0) { LOGE("failed to mount %s\n", v->mount_point); return -1; } } else { if (ensure_path_unmounted(v->mount_point) != 0) { LOGE("failed to unmount %s\n", v->mount_point); return -1; } } } return 0; }
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; }
install_package流程:
1).設置ui界面,包括背景和進度條
2).檢查是否掛在tmp和cache,tmp存放升級log,cache存放升級包
3).加載密鑰並校驗升級包,防止升級包被用戶自己修改
4).打開升級包,並執行升級包內的安裝程序
4.執行升級包中的升級文件
try_update_binary()
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界面。
到此,android 的 Recovery的流程已經分析完了,知道流程后再去分析Recovery的相關問題就比較容易了。