Android系統(tǒng)進行升級的時候,有兩種途徑,一種是通過接口傳遞升級包路徑自動升級(Android系統(tǒng)SD卡升級),升級完之后系統(tǒng)自動重啟;另一種是手動進入recovery模式下,選擇升級包進行升級,升級完成之后停留在recovery界面,需要手動選擇重啟。前者多用于手機廠商的客戶端在線升級,后者多用于開發(fā)和測試人員。但不管哪種,原理都是一樣的,都要在recovery模式下進行升級。
1、獲取升級包,可以從服務(wù)端下載,也可以直接拷貝到SD卡中
2、獲取升級包路徑,驗證簽名,通過installPackage接口升級
3、系統(tǒng)重啟進入Recovery模式
4、在install.cpp進行升級操作
5、try_update_binary執(zhí)行升級腳本
6、finish_recovery,重啟
一、獲取升級包,可以從服務(wù)端下載,也可以直接拷貝到SD卡中
假設(shè)SD卡中已有升級包update.zip
二、獲取升級包路徑,驗證簽名,通過installPackage接口升級
1、調(diào)用RecoverySystem類提供的verifyPackage方法進行簽名驗證
publicstaticvoidverifyPackage(File packageFile, ProgressListener listener, File deviceCertsZipFile)throwsIOException, GeneralSecurityException
簽名驗證函數(shù),實現(xiàn)過程就不貼出來了,參數(shù),
packageFile–升級文件
listener–進度監(jiān)督器
deviceCertsZipFile–簽名文件,如果為空,則使用系統(tǒng)默認的簽名
只有當簽名驗證正確才返回,否則將拋出異常。
在Recovery模式下進行升級時候也是會進行簽名驗證的,如果這里先不進行驗證也不會有什么問題。但是我們建議在重啟前,先驗證,以便及早發(fā)現(xiàn)問題。
如果簽名驗證沒有問題,就執(zhí)行installPackage開始升級。
2、installPackage開始升級
如果簽名驗證沒有問題,就進行重啟升級,
publicstaticvoidinstallPackage(Context context, File packageFile)throwsIOException { String filename = packageFile.getCanonicalPath(); Log.w(TAG, "!!! REBOOTING TO INSTALL "+ filename + " !!!"); finalString filenameArg = "--update_package="+ filename; finalString localeArg = "--locale="+ Locale.getDefault().toString(); bootCommand(context, filenameArg, localeArg); }
這里定義了兩個參數(shù),我們接著看,
privatestaticvoidbootCommand(Context context, String... args)throwsIOException { RECOVERY_DIR.mkdirs(); // In case we need it COMMAND_FILE.delete(); // In case it's not writable LOG_FILE.delete(); FileWriter command = new FileWriter(COMMAND_FILE); try { for (String arg : args) { if (!TextUtils.isEmpty(arg)) { command.write(arg); command.write("\n"); } } } finally { command.close(); } // Having written the command file, go ahead and reboot PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); pm.reboot(PowerManager.REBOOT_RECOVERY); throw new IOException("Reboot failed (no permissions?)"); }
創(chuàng)建目錄/cache/recovery/,command文件保存在該目錄下;如果存在command文件,將其刪除;然后將上面一步生成的兩個參數(shù)寫入到command文件。
最后重啟設(shè)備,重啟過程就不再詳述了。
三、系統(tǒng)重啟進入Recovery模式
系統(tǒng)重啟時會判斷/cache/recovery目錄下是否有command文件,如果存在就進入recovery模式,否則就正常啟動。
進入到Recovery模式下,將執(zhí)行recovery.cpp的main函數(shù),下面貼出關(guān)鍵代碼片段,
intarg; while((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) { switch(arg) { case's': send_intent = optarg; break; case'u': update_package = optarg; break; case'w': wipe_data = wipe_cache = 1; break; case'c': wipe_cache = 1; break; case't': show_text = 1; break; case'x': just_exit = true; break; case'l': locale = optarg; break; case'g': { if(stage == NULL|| *stage == '\0') { charbuffer[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; } }
這是一個While循環(huán),用來讀取 recovery的 command參數(shù), OPTIONS的不同選項定義如下,
staticconststructoptionOPTIONS[] = {{ "send_intent", required_argument, NULL, 's'}, { "update_package", required_argument, NULL, 'u'}, { "wipe_data", no_argument, NULL, 'w'}, { "wipe_cache", no_argument, NULL, 'c'}, { "show_text", no_argument, NULL, 't'}, { "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},};
顯然,根據(jù)第二步寫入的命令文件內(nèi)容,將為update_package 賦值。
接著看,
if(update_package) { // For backwards compatibility onthe 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; } }
兼容性處理。
int status= INSTALL_SUCCESS; if(update_package != NULL) { status= install_package(update_package, &wipe_cache, TEMPORARY_INSTALL_FILE, true); if(status== INSTALL_SUCCESS && wipe_cache) { if(erase_volume("/cache")) { LOGE("Cache wipe (requested by package) failed."); } } if(status!= INSTALL_SUCCESS) { ui->Print("Installation aborted.\n"); // If this is an eng oruserdebug build, thenautomatically // turn the text display on ifthe script fails so the error// message is visible. charbuffer[PROPERTY_VALUE_MAX+1]; property_get("ro.build.fingerprint", buffer, ""); if(strstr(buffer, ":userdebug/") || strstr(buffer, ":eng/")) { ui->ShowText(true); } } } elseif(wipe_data) { if(device->WipeData()) status= INSTALL_ERROR; if(erase_volume("/data")) status= INSTALL_ERROR; if(wipe_cache && erase_volume("/cache")) status= INSTALL_ERROR; if(erase_persistent_partition() == -1) status= INSTALL_ERROR; if(status!= INSTALL_SUCCESS) ui->Print("Data wipe failed.\n"); } elseif(wipe_cache) { if(wipe_cache && erase_volume("/cache")) status= INSTALL_ERROR; if(status!= INSTALL_SUCCESS) ui->Print("Cache wipe failed.\n"); } elseif(!just_exit) { status= INSTALL_NONE; // No command specified ui->SetBackground(RecoveryUI::NO_COMMAND); }
update_package不為空,執(zhí)行install_package方法。
我們也可以看到擦除數(shù)據(jù)、緩存的實現(xiàn)也是在這個里執(zhí)行的,這里就不展開了。
四、在install.cpp進行升級操作
具體的升級過程都是在install.cpp中執(zhí)行的,先看install_package方法,
intinstall_package(constchar* path, int* wipe_cache, constchar* install_file, boolneeds_mount){ FILE* install_log = fopen_path(install_file, "w"); if(install_log) { fputs(path, install_log); fputc('\n', install_log); } else{ LOGE("failed to open last_install: %s\n", strerror(errno)); } intresult; if(setup_install_mounts() != 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) { fputc(result == INSTALL_SUCCESS ? '1': '0', install_log); fputc('\n', install_log); fclose(install_log); } returnresult;}
這個方法中首先創(chuàng)建了log文件,升級過程包括出錯的信息都會寫到這個文件中,便于后續(xù)的分析工作。繼續(xù)跟進, really_install_package,
static intreally_install_package(const char*path, int* 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 packageinto memory. ui->Print("Opening update package...\n"); if(path&& needs_mount) { if(path[0] == '@') { ensure_path_mounted(path+1); } else{ ensure_path_mounted(path); } } MemMapping map; if(sysMapFile(path, &map) != 0) { LOGE("failed to map file\n"); returnINSTALL_CORRUPT; } // 裝入簽名文件 int numKeys; Certificate* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys); if(loadedKeys == NULL) { LOGE("Failed to load keys\n"); returnINSTALL_CORRUPT; } LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE); ui->Print("Verifying update package...\n"); // 驗證簽名 int err; 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); returnINSTALL_CORRUPT; } /* Try to openthe 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); returnINSTALL_CORRUPT; } /* Verify andinstall the contents of the package. */ ui->Print("Installing update...\n"); ui->SetEnableReboot(false); // 執(zhí)行升級腳本文件,開始升級 int result = try_update_binary(path, &zip, wipe_cache); ui->SetEnableReboot(true); ui->Print("\n"); sysReleaseMap(&map); returnresult;}
該方法主要做了三件事
1、驗證簽名
intnumKeys; Certificate* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys); if(loadedKeys == NULL) { LOGE("Failed to load keys\n"); returnINSTALL_CORRUPT; }
裝載簽名文件,如果為空 ,終止升級;
interr; 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; }
調(diào)用verify_file進行簽名驗證,這個方法定義在verifier.cpp文件中,此處不展開,如果驗證失敗立即終止升級。
2、讀取升級包信息
ZipArchivezip; 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); returnINSTALL_CORRUPT; }
執(zhí)行mzOpenZipArchive方法,打開升級包并掃描,將包的內(nèi)容拷貝到變量zip中,該變量將作為參數(shù)用來執(zhí)行升級腳本。
3、執(zhí)行升級腳本文件,開始升級
intresult = try_update_binary(path, &zip, wipe_cache);
try_update_binary方法用來處理升級包,執(zhí)行制作升級包中的腳本文件 update_binary ,進行系統(tǒng)更新。
五、try_update_binary執(zhí)行升級腳本
// If the packagecontains an update binary, extract it andrun it.static inttry_update_binary(const char*path, ZipArchive *zip, int* wipe_cache) { // 檢查update-binary是否存在 const ZipEntry* binary_entry = mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME); if(binary_entry == NULL) { mzCloseZipArchive(zip); returnINSTALL_CORRUPT; } const char* binary = "/tmp/update_binary"; unlink(binary); int fd = creat(binary, 0755); if(fd < 0) { mzCloseZipArchive(zip); LOGE("Can't make %s\n", binary); returnINSTALL_ERROR; } // update-binary拷貝到"/tmp/update_binary"bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd); close(fd); mzCloseZipArchive(zip); if(!ok) { LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME); returnINSTALL_ERROR; } // 創(chuàng)建管道,用于下面的子進程和父進程之間的通信 int pipefd[2]; pipe(pipefd); // When executing the update binary contained inthe package, the // arguments passed are: // // - the version number forthis interface // // - an fd to which the program can writeinorder to update the // progress bar. The program can writesingle-line commands: // // progress // fill up the next part of of the progress bar // over seconds. If is zero, use // set_progress commands to manually control the // progress of this segment of the bar // // set_progress // should be between 0.0and1.0; sets the // progress bar within the segment defined by the most // recent progress command. // // firmware // arrange to install the contents of inthe // given partition on reboot. // // (API v2: may start with "PACKAGE:"to // indicate taking a file from the OTA package.) // // (API v3: this command no longer exists.) // // ui_print // display on the screen. // // - the name of the packagezip file. // const char** args = (const char**)malloc(sizeof(char*) * 5); args[0] = binary; args[1] = EXPAND(RECOVERY_API_VERSION); // defined inAndroid.mk char* temp = (char*)malloc(10); sprintf(temp, "%d", pipefd[1]); args[2] = temp; args[3] = (char*)path; args[4] = NULL; // 創(chuàng)建子進程。負責執(zhí)行binary腳本 pid_t pid = fork(); if(pid == 0) { umask(022); close(pipefd[0]); execv(binary, (char* const*)args);// 執(zhí)行binary腳本 fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno)); _exit(-1); } close(pipefd[1]); *wipe_cache = 0; // 父進程負責接受子進程發(fā)送的命令去更新ui顯示 charbuffer[1024]; FILE* from_child = fdopen(pipefd[0], "r"); while(fgets(buffer, sizeof(buffer), from_child) != NULL) { char* command = strtok(buffer, " \n"); if(command == NULL) { continue; } elseif(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); } elseif(strcmp(command, "set_progress") == 0) { char* fraction_s = strtok(NULL, " \n"); float fraction = strtof(fraction_s, NULL); ui->SetProgress(fraction); } elseif(strcmp(command, "ui_print") == 0) { char* str = strtok(NULL, "\n"); if(str) { ui->Print("%s", str); } else{ ui->Print("\n"); } fflush(stdout); } elseif(strcmp(command, "wipe_cache") == 0) { *wipe_cache = 1; } elseif(strcmp(command, "clear_display") == 0) { ui->SetBackground(RecoveryUI::NONE); } elseif(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函數(shù),是真正實現(xiàn)讀取升級包中的腳本文件并執(zhí)行相應(yīng)的函數(shù)的地方。在此函數(shù)中,通過調(diào)用fork函數(shù)創(chuàng)建出一個子進程,在子進程中開始讀取并執(zhí)行升級腳本文件。在此需要注意的是函數(shù)fork的用法,fork被調(diào)用一次,將做兩次返回,在父進程中返回的是子進程的進程ID,為正數(shù);而在子進程中,則返回0。子進程創(chuàng)建成功后,開始執(zhí)行升級代碼,并通過管道與父進程交互,父進程則通過讀取子進程傳遞過來的信息更新UI。
六、finish_recovery,重啟
上一步完成之后,回到main函數(shù),
// Save logs and clean up before rebooting or shutting down. finish_recovery(send_intent);
保存升級過程中的log,清除臨時文件,包括command文件(不清除的話,下次重啟還會進入recovery模式),最后重啟。
以上就是升級的一個流程。
補充:
手動升級的流程也基本差不多,通過power key + volume上鍵組合,進入recovery模式,進入prompt_and_wait函數(shù)等待用戶按鍵事件。
recovery.cpp的main函數(shù),
Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT; if(status != INSTALL_SUCCESS || ui->IsTextVisible()) { Device::BuiltinAction temp = prompt_and_wait(device, status); if(temp != Device::NO_ACTION) after = temp; }
根據(jù)用戶選擇進入到相應(yīng)的分支進行處理,如下圖,
intchosen_item = get_menu_selection(headers, device->GetMenuItems(), 0, 0, device); // device-specific code may take some action here. It may // return one of the core actions handled in the switch // statement below. Device::BuiltinAction chosen_action = device->InvokeMenuItem(chosen_item);
當我們選擇從外置 sdcard升級,進入如下分支中,
caseDevice::APPLY_EXT: { ensure_path_mounted(SDCARD_ROOT); char* path = browse_directory(SDCARD_ROOT, device); if(path == NULL) { ui->Print("\n-- No package file selected.\n", path); break; } ui->Print("\n-- Install %s ...\n", path); set_sdcard_update_bootloader_message(); void* token = start_sdcard_fuse(path); int status = install_package(FUSE_SIDELOAD_HOST_PATHNAME, &wipe_cache, TEMPORARY_INSTALL_FILE, false); finish_sdcard_fuse(token); ensure_path_unmounted(SDCARD_ROOT); if(status == INSTALL_SUCCESS && wipe_cache) { ui->Print("\n-- Wiping cache (at package request)...\n"); if(erase_volume("/cache")) { ui->Print("Cache wipe failed.\n"); } else{ ui->Print("Cache wipe complete.\n"); } } if(status >= 0) { if(status != INSTALL_SUCCESS) { ui->SetBackground(RecoveryUI::ERROR); ui->Print("Installation aborted.\n"); } elseif(!ui->IsTextVisible()) { returnDevice::NO_ACTION; // reboot if logs aren't visible } else { ui->Print("\nInstall from sdcard complete.\n"); } } break; }
char* path = browse_directory(SDCARD_ROOT, device);這個函數(shù)瀏覽 SD card下的文件 ,并把路徑記錄下來 ,然后根據(jù)名稱排序 ,并處理用戶按鍵。
·當用戶選擇第一個條目“../”,直接跳轉(zhuǎn)到上級目錄,并且繼續(xù)瀏覽文件
·當用戶選擇的條目以“/”開頭,直接進入子目錄
·其它情況表明,該條目就是zip包.寫入BCB,copy 更新包至臨時目錄,直接轉(zhuǎn)入install_package
選擇zip包后,同樣也是執(zhí)行install_package函數(shù),后面與自動升級的流程是一樣的。
intstatus = install_package(FUSE_SIDELOAD_HOST_PATHNAME, &wipe_cache, TEMPORARY_INSTALL_FILE, false);