Android系統Recovery工作原理之使用update.zip升級過程分析(一)---update.zip包的製作

          Android系統Recovery工作原理之使用update.zip升級過程分析(一)---update.zip包的製作

轉自:http://blog.csdn.net/mu0206mu/article/details/7399822

         這篇及以後的篇幅將通過分析update.zip包在具體Android系統升級的過程,來理解Android系統中Recovery模式服務的工作原理。我們先從update.zip包的製作開始,然後是Android系統的啓動模式分析,Recovery工作原理,如何從我們上層開始選擇system update到重啓到Recovery服務,以及在Recovery服務中具體怎樣處理update.zip包升級的,我們的安裝腳本updater-script怎樣被解析並執行的等一系列問題。分析過程中所用的Android源碼是gingerbread0919(tcc88xx開發板標配的),測試開發板是tcc88xx。這是在工作中總結的文檔,當然在網上參考了不少內容,如有雷同純屬巧合吧,在分析過程中也存在很多未解決的問題,也希望大家不吝指教。


一、 update.zip包的目錄結構
          |----boot.img
          |----system/
          |----recovery/
                `|----recovery-from-boot.p
                `|----etc/
                        `|----install-recovery.sh
          |---META-INF/
              `|CERT.RSA
              `|CERT.SF
              `|MANIFEST.MF
              `|----com/
                     `|----google/
                             `|----android/
                                    `|----update-binary
                                    `|----updater-script
                             `|----android/
                                    `|----metadata
二、 update.zip包目錄結構詳解
         以上是我們用命令make otapackage 製作的update.zip包的標準目錄結構。
         1、boot.img是更新boot分區所需要的文件。這個boot.img主要包括kernel+ramdisk。

         2、system/目錄的內容在升級後會放在系統的system分區。主要用來更新系統的一些應用或則應用會用到的一些庫等等。可以將Android源碼編譯out/target/product/tcc8800/system/中的所有文件拷貝到這個目錄來代替。

         3、recovery/目錄中的recovery-from-boot.p是boot.img和recovery.img的補丁(patch),主要用來更新recovery分區,其中etc/目錄下的install-recovery.sh是更新腳本。
         4、update-binary是一個二進制文件,相當於一個腳本解釋器,能夠識別updater-script中描述的操作。該文件在Android源碼編譯後out/target/product/tcc8800/system bin/updater生成,可將updater重命名爲update-binary得到。
               該文件在具體的更新包中的名字由源碼中bootable/recovery/install.c中的宏ASSUMED_UPDATE_BINARY_NAME的值而定。
         5、updater-script:此文件是一個腳本文件,具體描述了更新過程。我們可以根據具體情況編寫該腳本來適應我們的具體需求。該文件的命名由源碼中bootable/recovery/updater/updater.c文件中的宏SCRIPT_NAME的值而定。
         6、 metadata文件是描述設備信息及環境變量的元數據。主要包括一些編譯選項,簽名公鑰,時間戳以及設備型號等。
         7、我們還可以在包中添加userdata目錄,來更新系統中的用戶數據部分。這部分內容在更新後會存放在系統的/data目錄下。

         8、update.zip包的簽名:update.zip更新包在製作完成後需要對其簽名,否則在升級時會出現認證失敗的錯誤提示。而且簽名要使用和目標板一致的加密公鑰。加密公鑰及加密需要的三個文件在Android源碼編譯後生成的具體路徑爲:

               out/host/linux-x86/framework/signapk.jar 

               build/target/product/security/testkey.x509.pem         

               build/target/product/security/testkey.pk8 。

              我們用命令make otapackage製作生成的update.zip包是已簽過名的,如果自己做update.zip包時必須手動對其簽名。

              具體的加密方法:$ java –jar gingerbread/out/host/linux/framework/signapk.jar –w gingerbread/build/target/product/security/testkey.x509.pem                                      gingerbread/build/target/product/security/testkey.pk8 update.zip update_signed.zip
              以上命令在update.zip包所在的路徑下執行,其中signapk.jar testkey.x509.pem以及testkey.pk8文件的引用使用絕對路徑。update.zip 是我們已經打好的包,update_signed.zip包是命令執行完生成的已經簽過名的包。
         9、MANIFEST.MF:這個manifest文件定義了與包的組成結構相關的數據。類似Android應用的mainfest.xml文件。
        10、CERT.RSA:與簽名文件相關聯的簽名程序塊文件,它存儲了用於簽名JAR文件的公共簽名。
        11、CERT.SF:這是JAR文件的簽名文件,其中前綴CERT代表簽名者。
        另外,在具體升級時,對update.zip包檢查時大致會分三步:①檢驗SF文件與RSA文件是否匹配。②檢驗MANIFEST.MF與簽名文件中的digest是否一致。③檢驗包中的文件與MANIFEST中所描述的是否一致。
三、 Android升級包update.zip的生成過程分析

         1) 對於update.zip包的製作有兩種方式,即手動製作和命令生成。

          第一種手動製作:即按照update.zip的目錄結構手動創建我們需要的目錄。然後將對應的文件拷貝到相應的目錄下,比如我們向系統中新加一個應用程序。可以將新增的應用拷貝到我們新建的update/system/app/下(system目錄是事先拷貝編譯源碼後生成的system目錄),打包並簽名後,拷貝到SD卡就可以使用了。這種方式在實際的tcc8800開發板中未測試成功。簽名部分未通過,可能與具體的開發板相關。

          第二種製作方式:命令製作。Android源碼系統中爲我們提供了製作update.zip刷機包的命令,即make otapackage。該命令在編譯源碼完成後並在源碼根目錄下執行。 具體操作方式:在源碼根目錄下執行

                ①$ . build/envsetup.sh。 

                ②$ lunch 然後選擇你需要的配置(如17)。

                ③$ make otapackage。

          在編譯完源碼後最好再執行一遍上面的①、②步防止執行③時出現未找到對應規則的錯誤提示。命令執行完成後生成的升級包所在位置在out/target/product/full_tcc8800_evm_target_files-eng.mumu.20120309.111059.zip將這個包重新命名爲update.zip,並拷貝到SD卡中即可使用。

           這種方式(即完全升級)在tcc8800開發板中已測試成功。

       2) 使用make otapackage命令生成update.zip的過程分析。
            在源碼根目錄下執行make otapackage命令生成update.zip包主要分爲兩步,第一步是根據Makefile執行編譯生成一個update原包(zip格式)。第二步是運行一個python腳本,並以上一步準備的zip包作爲輸入,最終生成我們需要的升級包。下面進一步分析這兩個過程。

            第一步:編譯Makefile。對應的Makefile文件所在位置:build/core/Makefile。從該文件的884行(tcc8800,gingerbread0919)開始會生成一個zip包,這個包最後會用來製作OTA package 或者filesystem image。先將這部分的對應的Makefile貼出來如下:

          

[plain] view plain copy
  1. # -----------------------------------------------------------------  
  2. # A zip of the directories that map to the target filesystem.  
  3. # This zip can be used to create an OTA package or filesystem image  
  4. # as a post-build step.  
  5. #  
  6. name := $(TARGET_PRODUCT)  
  7. ifeq ($(TARGET_BUILD_TYPE),debug)  
  8.   name := $(name)_debug  
  9. endif  
  10. name := $(name)-target_files-$(FILE_NAME_TAG)  
  11.   
  12. intermediates := $(call intermediates-dir-for,PACKAGING,target_files)  
  13. BUILT_TARGET_FILES_PACKAGE := $(intermediates)/$(name).zip  
  14. $(BUILT_TARGET_FILES_PACKAGE): intermediates := $(intermediates)  
  15. $(BUILT_TARGET_FILES_PACKAGE): \  
  16.         zip_root := $(intermediates)/$(name)  
  17.   
  18. # $(1): Directory to copy  
  19. # $(2): Location to copy it to  
  20. # The "ls -A" is to prevent "acp s/* d" from failing if s is empty.  
  21. define package_files-copy-root  
  22.   if [ -d "$(strip $(1))" -a "$$(ls -A $(1))" ]; then \  
  23.     mkdir -p $(2) && \  
  24.     $(ACP) -rd $(strip $(1))/* $(2); \  
  25.   fi  
  26. endef  
  27.   
  28. built_ota_tools := \  
  29.     $(call intermediates-dir-for,EXECUTABLES,applypatch)/applypatch \  
  30.     $(call intermediates-dir-for,EXECUTABLES,applypatch_static)/applypatch_static \  
  31.     $(call intermediates-dir-for,EXECUTABLES,check_prereq)/check_prereq \  
  32.     $(call intermediates-dir-for,EXECUTABLES,updater)/updater  
  33. $(BUILT_TARGET_FILES_PACKAGE): PRIVATE_OTA_TOOLS := $(built_ota_tools)  
  34.   
  35. $(BUILT_TARGET_FILES_PACKAGE): PRIVATE_RECOVERY_API_VERSION := $(RECOVERY_API_VERSION)  
  36.   
  37. ifeq ($(TARGET_RELEASETOOLS_EXTENSIONS),)  
  38. # default to common dir for device vendor  
  39. $(BUILT_TARGET_FILES_PACKAGE): tool_extensions := $(TARGET_DEVICE_DIR)/../common  
  40. else  
  41. $(BUILT_TARGET_FILES_PACKAGE): tool_extensions := $(TARGET_RELEASETOOLS_EXTENSIONS)  
  42. endif  
  43.   
  44. # Depending on the various images guarantees that the underlying  
  45. # directories are up-to-date.  
  46. $(BUILT_TARGET_FILES_PACKAGE): \  
  47.         $(INSTALLED_BOOTIMAGE_TARGET) \  
  48.         $(INSTALLED_RADIOIMAGE_TARGET) \  
  49.         $(INSTALLED_RECOVERYIMAGE_TARGET) \  
  50.         $(INSTALLED_SYSTEMIMAGE) \  
  51.         $(INSTALLED_USERDATAIMAGE_TARGET) \  
  52.         $(INSTALLED_ANDROID_INFO_TXT_TARGET) \  
  53.         $(built_ota_tools) \  
  54.         $(APKCERTS_FILE) \  
  55.         $(HOST_OUT_EXECUTABLES)/fs_config \  
  56.         | $(ACP)  
  57.     @echo "Package target files: $@"  
  58.     $(hide) rm -rf $@ $(zip_root)  
  59.     $(hide) mkdir -p $(dir $@) $(zip_root)  
  60.     @# Components of the recovery image  
  61.     $(hide) mkdir -p $(zip_root)/RECOVERY  
  62.     $(hide) $(call package_files-copy-root, \  
  63.         $(TARGET_RECOVERY_ROOT_OUT),$(zip_root)/RECOVERY/RAMDISK)  
  64. ifdef INSTALLED_KERNEL_TARGET  
  65.     $(hide) $(ACP) $(INSTALLED_KERNEL_TARGET) $(zip_root)/RECOVERY/kernel  
  66. endif  
  67. ifdef INSTALLED_2NDBOOTLOADER_TARGET  
  68.     $(hide) $(ACP) \  
  69.         $(INSTALLED_2NDBOOTLOADER_TARGET) $(zip_root)/RECOVERY/second  
  70. endif  
  71. ifdef BOARD_KERNEL_CMDLINE  
  72.     $(hide) echo "$(BOARD_KERNEL_CMDLINE)" > $(zip_root)/RECOVERY/cmdline  
  73. endif  
  74. ifdef BOARD_KERNEL_BASE  
  75.     $(hide) echo "$(BOARD_KERNEL_BASE)" > $(zip_root)/RECOVERY/base  
  76. endif  
  77. ifdef BOARD_KERNEL_PAGESIZE  
  78.     $(hide) echo "$(BOARD_KERNEL_PAGESIZE)" > $(zip_root)/RECOVERY/pagesize  
  79. endif  
  80.     @# Components of the boot image  
  81.     $(hide) mkdir -p $(zip_root)/BOOT  
  82.     $(hide) $(call package_files-copy-root, \  
  83.         $(TARGET_ROOT_OUT),$(zip_root)/BOOT/RAMDISK)  
  84. ifdef INSTALLED_KERNEL_TARGET  
  85.     $(hide) $(ACP) $(INSTALLED_KERNEL_TARGET) $(zip_root)/BOOT/kernel  
  86. endif  
  87. ifdef INSTALLED_2NDBOOTLOADER_TARGET  
  88.     $(hide) $(ACP) \  
  89.         $(INSTALLED_2NDBOOTLOADER_TARGET) $(zip_root)/BOOT/second  
  90. endif  
  91. ifdef BOARD_KERNEL_CMDLINE  
  92.     $(hide) echo "$(BOARD_KERNEL_CMDLINE)" > $(zip_root)/BOOT/cmdline  
  93. endif  
  94. ifdef BOARD_KERNEL_BASE  
  95.     $(hide) echo "$(BOARD_KERNEL_BASE)" > $(zip_root)/BOOT/base  
  96. endif  
  97. ifdef BOARD_KERNEL_PAGESIZE  
  98.     $(hide) echo "$(BOARD_KERNEL_PAGESIZE)" > $(zip_root)/BOOT/pagesize  
  99. endif  
  100.     $(hide) $(foreach t,$(INSTALLED_RADIOIMAGE_TARGET),\  
  101.                 mkdir -p $(zip_root)/RADIO; \  
  102.                 $(ACP) $(t) $(zip_root)/RADIO/$(notdir $(t));)  
  103.     @# Contents of the system image  
  104.     $(hide) $(call package_files-copy-root, \  
  105.         $(SYSTEMIMAGE_SOURCE_DIR),$(zip_root)/SYSTEM)  
  106.     @# Contents of the data image  
  107.     $(hide) $(call package_files-copy-root, \  
  108.         $(TARGET_OUT_DATA),$(zip_root)/DATA)  
  109.     @# Extra contents of the OTA package  
  110.     $(hide) mkdir -p $(zip_root)/OTA/bin  
  111.     $(hide) $(ACP) $(INSTALLED_ANDROID_INFO_TXT_TARGET) $(zip_root)/OTA/  
  112.     $(hide) $(ACP) $(PRIVATE_OTA_TOOLS) $(zip_root)/OTA/bin/  
  113.     @# Files that do not end up in any images, but are necessary to  
  114.     @# build them.  
  115.     $(hide) mkdir -p $(zip_root)/META  
  116.     $(hide) $(ACP) $(APKCERTS_FILE) $(zip_root)/META/apkcerts.txt  
  117.     $(hide) echo "$(PRODUCT_OTA_PUBLIC_KEYS)" > $(zip_root)/META/otakeys.txt  
  118.     $(hide) echo "recovery_api_version=$(PRIVATE_RECOVERY_API_VERSION)" > $(zip_root)/META/misc_info.txt  
  119. ifdef BOARD_FLASH_BLOCK_SIZE  
  120.     $(hide) echo "blocksize=$(BOARD_FLASH_BLOCK_SIZE)" >> $(zip_root)/META/misc_info.txt  
  121. endif  
  122. ifdef BOARD_BOOTIMAGE_PARTITION_SIZE  
  123.     $(hide) echo "boot_size=$(BOARD_BOOTIMAGE_PARTITION_SIZE)" >> $(zip_root)/META/misc_info.txt  
  124. endif  
  125. ifdef BOARD_RECOVERYIMAGE_PARTITION_SIZE  
  126.     $(hide) echo "recovery_size=$(BOARD_RECOVERYIMAGE_PARTITION_SIZE)" >> $(zip_root)/META/misc_info.txt  
  127. endif  
  128. ifdef BOARD_SYSTEMIMAGE_PARTITION_SIZE  
  129.     $(hide) echo "system_size=$(BOARD_SYSTEMIMAGE_PARTITION_SIZE)" >> $(zip_root)/META/misc_info.txt  
  130. endif  
  131. ifdef BOARD_USERDATAIMAGE_PARTITION_SIZE  
  132.     $(hide) echo "userdata_size=$(BOARD_USERDATAIMAGE_PARTITION_SIZE)" >> $(zip_root)/META/misc_info.txt  
  133. endif  
  134.     $(hide) echo "tool_extensions=$(tool_extensions)" >> $(zip_root)/META/misc_info.txt  
  135. ifdef mkyaffs2_extra_flags  
  136.     $(hide) echo "mkyaffs2_extra_flags=$(mkyaffs2_extra_flags)" >> $(zip_root)/META/misc_info.txt  
  137. endif  
  138.     @# Zip everything up, preserving symlinks  
  139.     $(hide) (cd $(zip_root) && zip -qry ../$(notdir $@) .)  
  140.     @# Run fs_config on all the system files in the zip, and save the output  
  141.     $(hide) zipinfo -1 $@ | awk -F/ 'BEGIN { OFS="/" } /^SYSTEM\// {$$1 = "system"; print}' | $(HOST_OUT_EXECUTABLES)/fs_config > $(zip_root)/META/filesystem_config.txt  
  142.     $(hide) (cd $(zip_root) && zip -q ../$(notdir $@) META/filesystem_config.txt)  
  143.   
  144.   
  145. target-files-package: $(BUILT_TARGET_FILES_PACKAGE)  
  146.   
  147.   
  148. ifneq ($(TARGET_SIMULATOR),true)  
  149. ifneq ($(TARGET_PRODUCT),sdk)  
  150. ifneq ($(TARGET_DEVICE),generic)  
  151. ifneq ($(TARGET_NO_KERNEL),true)  
  152. ifneq ($(recovery_fstab),)  

            根據上面的Makefile可以分析這個包的生成過程:

            首先創建一個root_zip根目錄,並依次在此目錄下創建所需要的如下其他目錄

            ①創建RECOVERY目錄,並填充該目錄的內容,包括kernel的鏡像和recovery根文件系統的鏡像。此目錄最終用於生成recovery.img。

            ②創建並填充BOOT目錄。包含kernel和cmdline以及pagesize大小等,該目錄最終用來生成boot.img。
            ③向SYSTEM目錄填充system image。
            ④向DATA填充data image。
            ⑤用於生成OTA package包所需要的額外的內容。主要包括一些bin命令。
            ⑥創建META目錄並向該目錄下添加一些文本文件,如apkcerts.txt(描述apk文件用到的認證證書),misc_info.txt(描述Flash內存的塊大小以及boot、recovery、system、userdata等分區的大小信息)。
            ⑦使用保留連接選項壓縮我們在上面獲得的root_zip目錄。
            ⑧使用fs_config(build/tools/fs_config)配置上面的zip包內所有的系統文件(system/下各目錄、文件)的權限屬主等信息。fs_config包含了一個頭文件#include“private/android_filesystem_config.h”。在這個頭文件中以硬編碼的方式設定了system目錄下各文件的權限、屬主。執行完配置後會將配置後的信息以文本方式輸出 到META/filesystem_config.txt中。並再一次zip壓縮成我們最終需要的原始包。

             第二步:上面的zip包只是一個編譯過程中生成的原始包。這個原始zip包在實際的編譯過程中有兩個作用,一是用來生成OTA update升級包,二是用來生成系統鏡像。在編譯過程中若生成OTA update升級包時會調用(具體位置在Makefile的1037行到1058行)一個名爲ota_from_target_files的python腳本,位置在/build/tools/releasetools/ota_from_target_files。這個腳本的作用是以第一步生成的zip原始包作爲輸入,最終生成可用的OTA升級zip包。

             下面我們分析使用這個腳本生成最終OTA升級包的過程。

                   ㈠ 首先看一下這個腳本開始部分的幫助文檔。代碼如下:

[python] view plain copy
  1. #!/usr/bin/env python  
  2. #  
  3. # Copyright (C) 2008 The Android Open Source Project  
  4. #  
  5. # Licensed under the Apache License, Version 2.0 (the "License");  
  6. # you may not use this file except in compliance with the License.  
  7. # You may obtain a copy of the License at  
  8. #  
  9. #      http://www.apache.org/licenses/LICENSE-2.0  
  10. #  
  11. # Unless required by applicable law or agreed to in writing, software  
  12. # distributed under the License is distributed on an "AS IS" BASIS,  
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  14. # See the License for the specific language governing permissions and  
  15. # limitations under the License.  
  16.   
  17. """ 
  18. Given a target-files zipfile, produces an OTA package that installs 
  19. that build.  An incremental OTA is produced if -i is given, otherwise 
  20. a full OTA is produced. 
  21.  
  22. Usage:  ota_from_target_files [flags] input_target_files output_ota_package 
  23.  
  24.   -b  (--board_config)  <file> 
  25.       Deprecated. 
  26.  
  27.   -k  (--package_key)  <key> 
  28.       Key to use to sign the package (default is 
  29.       "build/target/product/security/testkey"). 
  30.  
  31.   -i  (--incremental_from)  <file> 
  32.       Generate an incremental OTA using the given target-files zip as 
  33.       the starting build. 
  34.  
  35.   -w  (--wipe_user_data) 
  36.       Generate an OTA package that will wipe the user data partition 
  37.       when installed. 
  38.  
  39.   -n  (--no_prereq) 
  40.       Omit the timestamp prereq check normally included at the top of 
  41.       the build scripts (used for developer OTA packages which 
  42.       legitimately need to go back and forth). 
  43.  
  44.   -e  (--extra_script)  <file> 
  45.       Insert the contents of file at the end of the update script. 
  46.  
  47. """  

                        下面簡單翻譯一下他們的使用方法以及選項的作用。

                        Usage: ota_from_target_files [flags] input_target_files output_ota_package
                        -b 過時的。
                        -k簽名所使用的密鑰
                        -i生成增量OTA包時使用此選項。後面我們會用到這個選項來生成OTA增量包。
                        -w是否清除userdata分區
                        -n在升級時是否不檢查時間戳,缺省要檢查,即缺省情況下只能基於舊版本升級。
                        -e是否有額外運行的腳本
                        -m執行過程中生成腳本(updater-script)所需要的格式,目前有兩種即amend和edify。對應上兩種版本升級時會採用不同的解釋器。缺省會同時生成兩種格式的腳 本。
                        -p定義腳本用到的一些可執行文件的路徑。
                        -s定義額外運行腳本的路徑。
                        -x定義額外運行的腳本可能用的鍵值對。
                        -v執行過程中打印出執行的命令。
                        -h命令幫助

                   ㈡ 下面我們分析ota_from_target_files這個python腳本是怎樣生成最終zip包的。先講這個腳本的代碼貼出來如下:

[python] view plain copy
  1. import sys  
  2.   
  3. if sys.hexversion < 0x02040000:  
  4.   print >> sys.stderr, "Python 2.4 or newer is required."  
  5.   sys.exit(1)  
  6.   
  7. import copy  
  8. import errno  
  9. import os  
  10. import re  
  11. import sha  
  12. import subprocess  
  13. import tempfile  
  14. import time  
  15. import zipfile  
  16.   
  17. import common  
  18. import edify_generator  
  19.   
  20. OPTIONS = common.OPTIONS  
  21. OPTIONS.package_key = "build/target/product/security/testkey"  
  22. OPTIONS.incremental_source = None  
  23. OPTIONS.require_verbatim = set()  
  24. OPTIONS.prohibit_verbatim = set(("system/build.prop",))  
  25. OPTIONS.patch_threshold = 0.95  
  26. OPTIONS.wipe_user_data = False  
  27. OPTIONS.omit_prereq = False  
  28. OPTIONS.extra_script = None  
  29. OPTIONS.worker_threads = 3  
  30.   
  31. def MostPopularKey(d, default):  
  32.   """Given a dict, return the key corresponding to the largest 
  33.   value.  Returns 'default' if the dict is empty."""  
  34.   x = [(v, k) for (k, v) in d.iteritems()]  
  35.   if not x: return default  
  36.   x.sort()  
  37.   return x[-1][1]  
  38.   
  39.   
  40. def IsSymlink(info):  
  41.   """Return true if the zipfile.ZipInfo object passed in represents a 
  42.   symlink."""  
  43.   return (info.external_attr >> 16) == 0120777  
  44.   
  45.   
  46. class Item:  
  47.   """Items represent the metadata (user, group, mode) of files and 
  48.   directories in the system image."""  
  49.   ITEMS = {}  
  50.   def __init__(self, name, dir=False):  
  51.     self.name = name  
  52.     self.uid = None  
  53.     self.gid = None  
  54.     self.mode = None  
  55.     self.dir = dir  
  56.   
  57.     if name:  
  58.       self.parent = Item.Get(os.path.dirname(name), dir=True)  
  59.       self.parent.children.append(self)  
  60.     else:  
  61.       self.parent = None  
  62.     if dir:  
  63.       self.children = []  
  64.   
  65.   def Dump(self, indent=0):  
  66.     if self.uid is not None:  
  67.       print "%s%s %d %d %o" % ("  "*indent, self.name, self.uid, self.gid, self.mode)  
  68.     else:  
  69.       print "%s%s %s %s %s" % ("  "*indent, self.name, self.uid, self.gid, self.mode)  
  70.     if self.dir:  
  71.       print "%s%s" % ("  "*indent, self.descendants)  
  72.       print "%s%s" % ("  "*indent, self.best_subtree)  
  73.       for i in self.children:  
  74.         i.Dump(indent=indent+1)  
  75.  
  76.   @classmethod  
  77.   def Get(cls, name, dir=False):  
  78.     if name not in cls.ITEMS:  
  79.       cls.ITEMS[name] = Item(name, dir=dir)  
  80.     return cls.ITEMS[name]  
  81.  
  82.   @classmethod  
  83.   def GetMetadata(cls, input_zip):  
  84.   
  85.     try:  
  86.       # See if the target_files contains a record of what the uid,  
  87.       # gid, and mode is supposed to be.  
  88.       output = input_zip.read("META/filesystem_config.txt")  
  89.     except KeyError:  
  90.       # Run the external 'fs_config' program to determine the desired  
  91.       # uid, gid, and mode for every Item object.  Note this uses the  
  92.       # one in the client now, which might not be the same as the one  
  93.       # used when this target_files was built.  
  94.       p = common.Run(["fs_config"], stdin=subprocess.PIPE,  
  95.                      stdout=subprocess.PIPE, stderr=subprocess.PIPE)  
  96.       suffix = { False: "", True: "/" }  
  97.       input = "".join(["%s%s\n" % (i.name, suffix[i.dir])  
  98.                        for i in cls.ITEMS.itervalues() if i.name])  
  99.       output, error = p.communicate(input)  
  100.       assert not error  
  101.   
  102.     for line in output.split("\n"):  
  103.       if not line: continue  
  104.       name, uid, gid, mode = line.split()  
  105.       i = cls.ITEMS.get(name, None)  
  106.       if i is not None:  
  107.         i.uid = int(uid)  
  108.         i.gid = int(gid)  
  109.         i.mode = int(mode, 8)  
  110.         if i.dir:  
  111.           i.children.sort(key=lambda i: i.name)  
  112.   
  113.     # set metadata for the files generated by this script.  
  114.     i = cls.ITEMS.get("system/recovery-from-boot.p"None)  
  115.     if i: i.uid, i.gid, i.mode = 000644  
  116.     i = cls.ITEMS.get("system/etc/install-recovery.sh"None)  
  117.     if i: i.uid, i.gid, i.mode = 000544  
  118.   
  119.   def CountChildMetadata(self):  
  120.     """Count up the (uid, gid, mode) tuples for all children and 
  121.     determine the best strategy for using set_perm_recursive and 
  122.     set_perm to correctly chown/chmod all the files to their desired 
  123.     values.  Recursively calls itself for all descendants. 
  124.  
  125.     Returns a dict of {(uid, gid, dmode, fmode): count} counting up 
  126.     all descendants of this node.  (dmode or fmode may be None.)  Also 
  127.     sets the best_subtree of each directory Item to the (uid, gid, 
  128.     dmode, fmode) tuple that will match the most descendants of that 
  129.     Item. 
  130.     """  
  131.   
  132.     assert self.dir  
  133.     d = self.descendants = {(self.uid, self.gid, self.mode, None): 1}  
  134.     for i in self.children:  
  135.       if i.dir:  
  136.         for k, v in i.CountChildMetadata().iteritems():  
  137.           d[k] = d.get(k, 0) + v  
  138.       else:  
  139.         k = (i.uid, i.gid, None, i.mode)  
  140.         d[k] = d.get(k, 0) + 1  
  141.   
  142.     # Find the (uid, gid, dmode, fmode) tuple that matches the most  
  143.     # descendants.  
  144.   
  145.     # First, find the (uid, gid) pair that matches the most  
  146.     # descendants.  
  147.     ug = {}  
  148.     for (uid, gid, _, _), count in d.iteritems():  
  149.       ug[(uid, gid)] = ug.get((uid, gid), 0) + count  
  150.     ug = MostPopularKey(ug, (00))  
  151.   
  152.     # Now find the dmode and fmode that match the most descendants  
  153.     # with that (uid, gid), and choose those.  
  154.     best_dmode = (00755)  
  155.     best_fmode = (00644)  
  156.     for k, count in d.iteritems():  
  157.       if k[:2] != ug: continue  
  158.       if k[2is not None and count >= best_dmode[0]: best_dmode = (count, k[2])  
  159.       if k[3is not None and count >= best_fmode[0]: best_fmode = (count, k[3])  
  160.     self.best_subtree = ug + (best_dmode[1], best_fmode[1])  
  161.   
  162.     return d  
  163.   
  164.   def SetPermissions(self, script):  
  165.     """Append set_perm/set_perm_recursive commands to 'script' to 
  166.     set all permissions, users, and groups for the tree of files 
  167.     rooted at 'self'."""  
  168.   
  169.     self.CountChildMetadata()  
  170.   
  171.     def recurse(item, current):  
  172.       # current is the (uid, gid, dmode, fmode) tuple that the current  
  173.       # item (and all its children) have already been set to.  We only  
  174.       # need to issue set_perm/set_perm_recursive commands if we're  
  175.       # supposed to be something different.  
  176.       if item.dir:  
  177.         if current != item.best_subtree:  
  178.           script.SetPermissionsRecursive("/"+item.name, *item.best_subtree)  
  179.           current = item.best_subtree  
  180.   
  181.         if item.uid != current[0or item.gid != current[1or \  
  182.            item.mode != current[2]:  
  183.           script.SetPermissions("/"+item.name, item.uid, item.gid, item.mode)  
  184.   
  185.         for i in item.children:  
  186.           recurse(i, current)  
  187.       else:  
  188.         if item.uid != current[0or item.gid != current[1or \  
  189.                item.mode != current[3]:  
  190.           script.SetPermissions("/"+item.name, item.uid, item.gid, item.mode)  
  191.   
  192.     recurse(self, (-1, -1, -1, -1))  
  193.   
  194.   
  195. def CopySystemFiles(input_zip, output_zip=None,  
  196.                     substitute=None):  
  197.   """Copies files underneath system/ in the input zip to the output 
  198.   zip.  Populates the Item class with their metadata, and returns a 
  199.   list of symlinks.  output_zip may be None, in which case the copy is 
  200.   skipped (but the other side effects still happen).  substitute is an 
  201.   optional dict of {output filename: contents} to be output instead of 
  202.   certain input files. 
  203.   """  
  204.   
  205.   symlinks = []  
  206.   
  207.   for info in input_zip.infolist():  
  208.     if info.filename.startswith("SYSTEM/"):  
  209.       basefilename = info.filename[7:]  
  210.       if IsSymlink(info):  
  211.         symlinks.append((input_zip.read(info.filename),  
  212.                          "/system/" + basefilename))  
  213.       else:  
  214.         info2 = copy.copy(info)  
  215.         fn = info2.filename = "system/" + basefilename  
  216.         if substitute and fn in substitute and substitute[fn] is None:  
  217.           continue  
  218.         if output_zip is not None:  
  219.           if substitute and fn in substitute:  
  220.             data = substitute[fn]  
  221.           else:  
  222.             data = input_zip.read(info.filename)  
  223.           output_zip.writestr(info2, data)  
  224.         if fn.endswith("/"):  
  225.           Item.Get(fn[:-1], dir=True)  
  226.         else:  
  227.           Item.Get(fn, dir=False)  
  228.   
  229.   symlinks.sort()  
  230.   return symlinks  
  231.   
  232.   
  233. def SignOutput(temp_zip_name, output_zip_name):  
  234.   key_passwords = common.GetKeyPasswords([OPTIONS.package_key])  
  235.   pw = key_passwords[OPTIONS.package_key]  
  236.   
  237.   common.SignFile(temp_zip_name, output_zip_name, OPTIONS.package_key, pw,  
  238.                   whole_file=True)  
  239.   
  240.   
  241. def AppendAssertions(script, input_zip):  
  242.   device = GetBuildProp("ro.product.device", input_zip)  
  243.   script.AssertDevice(device)  
  244.   
  245.   
  246. def MakeRecoveryPatch(output_zip, recovery_img, boot_img):  
  247.   """Generate a binary patch that creates the recovery image starting 
  248.   with the boot image.  (Most of the space in these images is just the 
  249.   kernel, which is identical for the two, so the resulting patch 
  250.   should be efficient.)  Add it to the output zip, along with a shell 
  251.   script that is run from init.rc on first boot to actually do the 
  252.   patching and install the new recovery image. 
  253.  
  254.   recovery_img and boot_img should be File objects for the 
  255.   corresponding images. 
  256.  
  257.   Returns an Item for the shell script, which must be made 
  258.   executable. 
  259.   """  
  260.   
  261.   d = common.Difference(recovery_img, boot_img)  
  262.   _, _, patch = d.ComputePatch()  
  263.   common.ZipWriteStr(output_zip, "recovery/recovery-from-boot.p", patch)  
  264.   Item.Get("system/recovery-from-boot.p", dir=False)  
  265.   
  266.   boot_type, boot_device = common.GetTypeAndDevice("/boot", OPTIONS.info_dict)  
  267.   recovery_type, recovery_device = common.GetTypeAndDevice("/recovery", OPTIONS.info_dict)  
  268.   
  269.   # Images with different content will have a different first page, so  
  270.   # we check to see if this recovery has already been installed by  
  271.   # testing just the first 2k.  
  272.   HEADER_SIZE = 2048  
  273.   header_sha1 = sha.sha(recovery_img.data[:HEADER_SIZE]).hexdigest()  
  274.   sh = """#!/system/bin/sh 
  275. if ! applypatch -c %(recovery_type)s:%(recovery_device)s:%(header_size)d:%(header_sha1)s; then 
  276.   log -t recovery "Installing new recovery image" 
  277.   applypatch %(boot_type)s:%(boot_device)s:%(boot_size)d:%(boot_sha1)s %(recovery_type)s:%(recovery_device)s %(recovery_sha1)s %(recovery_size)d %(boot_sha1)s:/system/recovery-from-boot.p 
  278. else 
  279.   log -t recovery "Recovery image already installed" 
  280. fi 
  281. """ % { 'boot_size': boot_img.size,  
  282.         'boot_sha1': boot_img.sha1,  
  283.         'header_size': HEADER_SIZE,  
  284.         'header_sha1': header_sha1,  
  285.         'recovery_size': recovery_img.size,  
  286.         'recovery_sha1': recovery_img.sha1,  
  287.         'boot_type': boot_type,  
  288.         'boot_device': boot_device,  
  289.         'recovery_type': recovery_type,  
  290.         'recovery_device': recovery_device,  
  291.         }  
  292.   common.ZipWriteStr(output_zip, "recovery/etc/install-recovery.sh", sh)  
  293.   return Item.Get("system/etc/install-recovery.sh", dir=False)  
  294.   
  295.   
  296. def WriteFullOTAPackage(input_zip, output_zip):  
  297.   # TODO: how to determine this?  We don't know what version it will  
  298.   # be installed on top of.  For now, we expect the API just won't  
  299.   # change very often.  
  300.   script = edify_generator.EdifyGenerator(3, OPTIONS.info_dict)  
  301.   
  302.   metadata = {"post-build": GetBuildProp("ro.build.fingerprint", input_zip),  
  303.               "pre-device": GetBuildProp("ro.product.device", input_zip),  
  304.               "post-timestamp": GetBuildProp("ro.build.date.utc", input_zip),  
  305.               }  
  306.   
  307.   device_specific = common.DeviceSpecificParams(  
  308.       input_zip=input_zip,  
  309.       input_version=OPTIONS.info_dict["recovery_api_version"],  
  310.       output_zip=output_zip,  
  311.       script=script,  
  312.       input_tmp=OPTIONS.input_tmp,  
  313.       metadata=metadata,  
  314.       info_dict=OPTIONS.info_dict)  
  315.   
  316.   if not OPTIONS.omit_prereq:  
  317.     ts = GetBuildProp("ro.build.date.utc", input_zip)  
  318.     script.AssertOlderBuild(ts)  
  319.   
  320.   AppendAssertions(script, input_zip)  
  321.   device_specific.FullOTA_Assertions()  
  322.   
  323.   script.ShowProgress(0.50)  
  324.   
  325.   if OPTIONS.wipe_user_data:  
  326.     script.FormatPartition("/data")  
  327.   
  328.   script.FormatPartition("/system")  
  329.   script.Mount("/system")  
  330.   script.UnpackPackageDir("recovery""/system")  
  331.   script.UnpackPackageDir("system""/system")  
  332.   
  333.   symlinks = CopySystemFiles(input_zip, output_zip)  
  334.   script.MakeSymlinks(symlinks)  
  335.   
  336.   boot_img = common.File("boot.img", common.BuildBootableImage(  
  337.       os.path.join(OPTIONS.input_tmp, "BOOT")))  
  338.   recovery_img = common.File("recovery.img", common.BuildBootableImage(  
  339.       os.path.join(OPTIONS.input_tmp, "RECOVERY")))  
  340.   MakeRecoveryPatch(output_zip, recovery_img, boot_img)  
  341.   
  342.   Item.GetMetadata(input_zip)  
  343.   Item.Get("system").SetPermissions(script)  
  344.   
  345.   common.CheckSize(boot_img.data, "boot.img", OPTIONS.info_dict)  
  346.   common.ZipWriteStr(output_zip, "boot.img", boot_img.data)  
  347.   script.ShowProgress(0.20)  
  348.   
  349.   script.ShowProgress(0.210)  
  350.   script.WriteRawImage("/boot""boot.img")  
  351.   
  352.   script.ShowProgress(0.10)  
  353.   device_specific.FullOTA_InstallEnd()  
  354.   
  355.   if OPTIONS.extra_script is not None:  
  356.     script.AppendExtra(OPTIONS.extra_script)  
  357.   
  358.   script.UnmountAll()  
  359.   script.AddToZip(input_zip, output_zip)  
  360.   WriteMetadata(metadata, output_zip)  
  361.   
  362.   
  363. def WriteMetadata(metadata, output_zip):  
  364.   common.ZipWriteStr(output_zip, "META-INF/com/android/metadata",  
  365.                      "".join(["%s=%s\n" % kv  
  366.                               for kv in sorted(metadata.iteritems())]))  
  367.   
  368.   
  369.   
  370.   
  371. def LoadSystemFiles(z):  
  372.   """Load all the files from SYSTEM/... in a given target-files 
  373.   ZipFile, and return a dict of {filename: File object}."""  
  374.   out = {}  
  375.   for info in z.infolist():  
  376.     if info.filename.startswith("SYSTEM/"and not IsSymlink(info):  
  377.       fn = "system/" + info.filename[7:]  
  378.       data = z.read(info.filename)  
  379.       out[fn] = common.File(fn, data)  
  380.   return out  
  381.   
  382.   
  383. def GetBuildProp(property, z):  
  384.   """Return the fingerprint of the build of a given target-files 
  385.   ZipFile object."""  
  386.   bp = z.read("SYSTEM/build.prop")  
  387.   if not property:  
  388.     return bp  
  389.   m = re.search(re.escape(property) + r"=(.*)\n", bp)  
  390.   if not m:  
  391.     raise common.ExternalError("couldn't find %s in build.prop" % (property,))  
  392.   return m.group(1).strip()  
  393.   
  394.   
  395. def WriteIncrementalOTAPackage(target_zip, source_zip, output_zip):  
  396.   source_version = OPTIONS.source_info_dict["recovery_api_version"]  
  397.   target_version = OPTIONS.target_info_dict["recovery_api_version"]  
  398.   
  399.   if source_version == 0:  
  400.     print ("WARNING: generating edify script for a source that "  
  401.            "can't install it.")  
  402.   script = edify_generator.EdifyGenerator(source_version, OPTIONS.info_dict)  
  403.   
  404.   metadata = {"pre-device": GetBuildProp("ro.product.device", source_zip),  
  405.               "post-timestamp": GetBuildProp("ro.build.date.utc", target_zip),  
  406.               }  
  407.   
  408.   device_specific = common.DeviceSpecificParams(  
  409.       source_zip=source_zip,  
  410.       source_version=source_version,  
  411.       target_zip=target_zip,  
  412.       target_version=target_version,  
  413.       output_zip=output_zip,  
  414.       script=script,  
  415.       metadata=metadata,  
  416.       info_dict=OPTIONS.info_dict)  
  417.   
  418.   print "Loading target..."  
  419.   target_data = LoadSystemFiles(target_zip)  
  420.   print "Loading source..."  
  421.   source_data = LoadSystemFiles(source_zip)  
  422.   
  423.   verbatim_targets = []  
  424.   patch_list = []  
  425.   diffs = []  
  426.   largest_source_size = 0  
  427.   for fn in sorted(target_data.keys()):  
  428.     tf = target_data[fn]  
  429.     assert fn == tf.name  
  430.     sf = source_data.get(fn, None)  
  431.   
  432.     if sf is None or fn in OPTIONS.require_verbatim:  
  433.       # This file should be included verbatim  
  434.       if fn in OPTIONS.prohibit_verbatim:  
  435.         raise common.ExternalError("\"%s\" must be sent verbatim" % (fn,))  
  436.       print "send", fn, "verbatim"  
  437.       tf.AddToZip(output_zip)  
  438.       verbatim_targets.append((fn, tf.size))  
  439.     elif tf.sha1 != sf.sha1:  
  440.       # File is different; consider sending as a patch  
  441.       diffs.append(common.Difference(tf, sf))  
  442.     else:  
  443.       # Target file identical to source.  
  444.       pass  
  445.   
  446.   common.ComputeDifferences(diffs)  
  447.   
  448.   for diff in diffs:  
  449.     tf, sf, d = diff.GetPatch()  
  450.     if d is None or len(d) > tf.size * OPTIONS.patch_threshold:  
  451.       # patch is almost as big as the file; don't bother patching  
  452.       tf.AddToZip(output_zip)  
  453.       verbatim_targets.append((tf.name, tf.size))  
  454.     else:  
  455.       common.ZipWriteStr(output_zip, "patch/" + tf.name + ".p", d)  
  456.       patch_list.append((tf.name, tf, sf, tf.size, sha.sha(d).hexdigest()))  
  457.       largest_source_size = max(largest_source_size, sf.size)  
  458.   
  459.   source_fp = GetBuildProp("ro.build.fingerprint", source_zip)  
  460.   target_fp = GetBuildProp("ro.build.fingerprint", target_zip)  
  461.   metadata["pre-build"] = source_fp  
  462.   metadata["post-build"] = target_fp  
  463.   
  464.   script.Mount("/system")  
  465.   script.AssertSomeFingerprint(source_fp, target_fp)  
  466.   
  467.   source_boot = common.File("/tmp/boot.img",  
  468.                             common.BuildBootableImage(  
  469.                                 os.path.join(OPTIONS.source_tmp, "BOOT")))  
  470.   target_boot = common.File("/tmp/boot.img",  
  471.                             common.BuildBootableImage(  
  472.                                 os.path.join(OPTIONS.target_tmp, "BOOT")))  
  473.   updating_boot = (source_boot.data != target_boot.data)  
  474.   
  475.   source_recovery = common.File("system/recovery.img",  
  476.                                 common.BuildBootableImage(  
  477.                                     os.path.join(OPTIONS.source_tmp, "RECOVERY")))  
  478.   target_recovery = common.File("system/recovery.img",  
  479.                                 common.BuildBootableImage(  
  480.                                     os.path.join(OPTIONS.target_tmp, "RECOVERY")))  
  481.   updating_recovery = (source_recovery.data != target_recovery.data)  
  482.   
  483.   # Here's how we divide up the progress bar:  
  484.   #  0.1 for verifying the start state (PatchCheck calls)  
  485.   #  0.8 for applying patches (ApplyPatch calls)  
  486.   #  0.1 for unpacking verbatim files, symlinking, and doing the  
  487.   #      device-specific commands.  
  488.   
  489.   AppendAssertions(script, target_zip)  
  490.   device_specific.IncrementalOTA_Assertions()  
  491.   
  492.   script.Print("Verifying current system...")  
  493.   
  494.   script.ShowProgress(0.10)  
  495.   total_verify_size = float(sum([i[2].size for i in patch_list]) + 1)  
  496.   if updating_boot:  
  497.     total_verify_size += source_boot.size  
  498.   so_far = 0  
  499.   
  500.   for fn, tf, sf, size, patch_sha in patch_list:  
  501.     script.PatchCheck("/"+fn, tf.sha1, sf.sha1)  
  502.     so_far += sf.size  
  503.     script.SetProgress(so_far / total_verify_size)  
  504.   
  505.   if updating_boot:  
  506.     d = common.Difference(target_boot, source_boot)  
  507.     _, _, d = d.ComputePatch()  
  508.     print "boot      target: %d  source: %d  diff: %d" % (  
  509.         target_boot.size, source_boot.size, len(d))  
  510.   
  511.     common.ZipWriteStr(output_zip, "patch/boot.img.p", d)  
  512.   
  513.     boot_type, boot_device = common.GetTypeAndDevice("/boot", OPTIONS.info_dict)  
  514.   
  515.     script.PatchCheck("%s:%s:%d:%s:%d:%s" %  
  516.                       (boot_type, boot_device,  
  517.                        source_boot.size, source_boot.sha1,  
  518.                        target_boot.size, target_boot.sha1))  
  519.     so_far += source_boot.size  
  520.     script.SetProgress(so_far / total_verify_size)  
  521.   
  522.   if patch_list or updating_recovery or updating_boot:  
  523.     script.CacheFreeSpaceCheck(largest_source_size)  
  524.   
  525.   device_specific.IncrementalOTA_VerifyEnd()  
  526.   
  527.   script.Comment("---- start making changes here ----")  
  528.   
  529.   if OPTIONS.wipe_user_data:  
  530.     script.Print("Erasing user data...")  
  531.     script.FormatPartition("/data")  
  532.   
  533.   script.Print("Removing unneeded files...")  
  534.   script.DeleteFiles(["/"+i[0for i in verbatim_targets] +  
  535.                      ["/"+i for i in sorted(source_data)  
  536.                             if i not in target_data] +  
  537.                      ["/system/recovery.img"])  
  538.   
  539.   script.ShowProgress(0.80)  
  540.   total_patch_size = float(sum([i[1].size for i in patch_list]) + 1)  
  541.   if updating_boot:  
  542.     total_patch_size += target_boot.size  
  543.   so_far = 0  
  544.   
  545.   script.Print("Patching system files...")  
  546.   for fn, tf, sf, size, _ in patch_list:  
  547.     script.ApplyPatch("/"+fn, "-", tf.size, tf.sha1, sf.sha1, "patch/"+fn+".p")  
  548.     so_far += tf.size  
  549.     script.SetProgress(so_far / total_patch_size)  
  550.   
  551.   if updating_boot:  
  552.     # Produce the boot image by applying a patch to the current  
  553.     # contents of the boot partition, and write it back to the  
  554.     # partition.  
  555.     script.Print("Patching boot image...")  
  556.     script.ApplyPatch("%s:%s:%d:%s:%d:%s"  
  557.                       % (boot_type, boot_device,  
  558.                          source_boot.size, source_boot.sha1,  
  559.                          target_boot.size, target_boot.sha1),  
  560.                       "-",  
  561.                       target_boot.size, target_boot.sha1,  
  562.                       source_boot.sha1, "patch/boot.img.p")  
  563.     so_far += target_boot.size  
  564.     script.SetProgress(so_far / total_patch_size)  
  565.     print "boot image changed; including."  
  566.   else:  
  567.     print "boot image unchanged; skipping."  
  568.   
  569.   if updating_recovery:  
  570.     # Is it better to generate recovery as a patch from the current  
  571.     # boot image, or from the previous recovery image?  For large  
  572.     # updates with significant kernel changes, probably the former.  
  573.     # For small updates where the kernel hasn't changed, almost  
  574.     # certainly the latter.  We pick the first option.  Future  
  575.     # complicated schemes may let us effectively use both.  
  576.     #  
  577.     # A wacky possibility: as long as there is room in the boot  
  578.     # partition, include the binaries and image files from recovery in  
  579.     # the boot image (though not in the ramdisk) so they can be used  
  580.     # as fodder for constructing the recovery image.  
  581.     MakeRecoveryPatch(output_zip, target_recovery, target_boot)  
  582.     script.DeleteFiles(["/system/recovery-from-boot.p",  
  583.                         "/system/etc/install-recovery.sh"])  
  584.     print "recovery image changed; including as patch from boot."  
  585.   else:  
  586.     print "recovery image unchanged; skipping."  
  587.   
  588.   script.ShowProgress(0.110)  
  589.   
  590.   target_symlinks = CopySystemFiles(target_zip, None)  
  591.   
  592.   target_symlinks_d = dict([(i[1], i[0]) for i in target_symlinks])  
  593.   temp_script = script.MakeTemporary()  
  594.   Item.GetMetadata(target_zip)  
  595.   Item.Get("system").SetPermissions(temp_script)  
  596.   
  597.   # Note that this call will mess up the tree of Items, so make sure  
  598.   # we're done with it.  
  599.   source_symlinks = CopySystemFiles(source_zip, None)  
  600.   source_symlinks_d = dict([(i[1], i[0]) for i in source_symlinks])  
  601.   
  602.   # Delete all the symlinks in source that aren't in target.  This  
  603.   # needs to happen before verbatim files are unpacked, in case a  
  604.   # symlink in the source is replaced by a real file in the target.  
  605.   to_delete = []  
  606.   for dest, link in source_symlinks:  
  607.     if link not in target_symlinks_d:  
  608.       to_delete.append(link)  
  609.   script.DeleteFiles(to_delete)  
  610.   
  611.   if verbatim_targets:  
  612.     script.Print("Unpacking new files...")  
  613.     script.UnpackPackageDir("system""/system")  
  614.   
  615.   if updating_recovery:  
  616.     script.Print("Unpacking new recovery...")  
  617.     script.UnpackPackageDir("recovery""/system")  
  618.   
  619.   script.Print("Symlinks and permissions...")  
  620.   
  621.   # Create all the symlinks that don't already exist, or point to  
  622.   # somewhere different than what we want.  Delete each symlink before  
  623.   # creating it, since the 'symlink' command won't overwrite.  
  624.   to_create = []  
  625.   for dest, link in target_symlinks:  
  626.     if link in source_symlinks_d:  
  627.       if dest != source_symlinks_d[link]:  
  628.         to_create.append((dest, link))  
  629.     else:  
  630.       to_create.append((dest, link))  
  631.   script.DeleteFiles([i[1for i in to_create])  
  632.   script.MakeSymlinks(to_create)  
  633.   
  634.   # Now that the symlinks are created, we can set all the  
  635.   # permissions.  
  636.   script.AppendScript(temp_script)  
  637.   
  638.   # Do device-specific installation (eg, write radio image).  
  639.   device_specific.IncrementalOTA_InstallEnd()  
  640.   
  641.   if OPTIONS.extra_script is not None:  
  642.     scirpt.AppendExtra(OPTIONS.extra_script)  
  643.   
  644.   script.AddToZip(target_zip, output_zip)  
  645.   WriteMetadata(metadata, output_zip)  
  646.   
  647.   
  648. def main(argv):  
  649.   
  650.   def option_handler(o, a):  
  651.     if o in ("-b""--board_config"):  
  652.       pass   # deprecated  
  653.     elif o in ("-k""--package_key"):  
  654.       OPTIONS.package_key = a  
  655.     elif o in ("-i""--incremental_from"):  
  656.       OPTIONS.incremental_source = a  
  657.     elif o in ("-w""--wipe_user_data"):  
  658.       OPTIONS.wipe_user_data = True  
  659.     elif o in ("-n""--no_prereq"):  
  660.       OPTIONS.omit_prereq = True  
  661.     elif o in ("-e""--extra_script"):  
  662.       OPTIONS.extra_script = a  
  663.     elif o in ("--worker_threads"):  
  664.       OPTIONS.worker_threads = int(a)  
  665.     else:  
  666.       return False  
  667.     return True  
  668.   
  669.   args = common.ParseOptions(argv, __doc__,  
  670.                              extra_opts="b:k:i:d:wne:",  
  671.                              extra_long_opts=["board_config=",  
  672.                                               "package_key=",  
  673.                                               "incremental_from=",  
  674.                                               "wipe_user_data",  
  675.                                               "no_prereq",  
  676.                                               "extra_script=",  
  677.                                               "worker_threads="],  
  678.                              extra_option_handler=option_handler)  
  679.   
  680.   if len(args) != 2:  
  681.     common.Usage(__doc__)  
  682.     sys.exit(1)  
  683.   
  684.   if OPTIONS.extra_script is not None:  
  685.     OPTIONS.extra_script = open(OPTIONS.extra_script).read()  
  686.   
  687.   print "unzipping target target-files..."  
  688.   OPTIONS.input_tmp = common.UnzipTemp(args[0])  
  689.   
  690.   OPTIONS.target_tmp = OPTIONS.input_tmp  
  691.   input_zip = zipfile.ZipFile(args[0], "r")  
  692.   OPTIONS.info_dict = common.LoadInfoDict(input_zip)  
  693.   if OPTIONS.verbose:  
  694.     print "--- target info ---"  
  695.     common.DumpInfoDict(OPTIONS.info_dict)  
  696.   
  697.   if OPTIONS.device_specific is None:  
  698.     OPTIONS.device_specific = OPTIONS.info_dict.get("tool_extensions"None)  
  699.   if OPTIONS.device_specific is not None:  
  700.     OPTIONS.device_specific = os.path.normpath(OPTIONS.device_specific)  
  701.     print "using device-specific extensions in", OPTIONS.device_specific  
  702.   
  703.   if OPTIONS.package_key:  
  704.     temp_zip_file = tempfile.NamedTemporaryFile()  
  705.     output_zip = zipfile.ZipFile(temp_zip_file, "w",  
  706.                                  compression=zipfile.ZIP_DEFLATED)  
  707.   else:  
  708.     output_zip = zipfile.ZipFile(args[1], "w",  
  709.                                  compression=zipfile.ZIP_DEFLATED)  
  710.   
  711.   if OPTIONS.incremental_source is None:  
  712.     WriteFullOTAPackage(input_zip, output_zip)  
  713.   else:  
  714.     print "unzipping source target-files..."  
  715.     OPTIONS.source_tmp = common.UnzipTemp(OPTIONS.incremental_source)  
  716.     source_zip = zipfile.ZipFile(OPTIONS.incremental_source, "r")  
  717.     OPTIONS.target_info_dict = OPTIONS.info_dict  
  718.     OPTIONS.source_info_dict = common.LoadInfoDict(source_zip)  
  719.     if OPTIONS.verbose:  
  720.       print "--- source info ---"  
  721.       common.DumpInfoDict(OPTIONS.source_info_dict)  
  722.     WriteIncrementalOTAPackage(input_zip, source_zip, output_zip)  
  723.   
  724.   output_zip.close()  
  725.   if OPTIONS.package_key:  
  726.     SignOutput(temp_zip_file.name, args[1])  
  727.     temp_zip_file.close()  
  728.   
  729.   common.Cleanup()  
  730.   
  731.   print "done."  
  732.   
  733.   
  734. if __name__ == '__main__':  
  735.   try:  
  736.     common.CloseInheritedPipes()  
  737.     main(sys.argv[1:])  
  738.   except common.ExternalError, e:  
  739.     print  
  740.     print "   ERROR: %s" % (e,)  
  741.     print  
  742.     sys.exit(1)  

                       主函數main是python的入口函數,我們從main函數開始看,大概看一下main函數(腳本最後)裏的流程就能知道腳本的執行過程了。

                       ① 在main函數的開頭,首先將用戶設定的option選項存入OPTIONS變量中,它是一個python中的類。緊接着判斷有沒有額外的腳本,如果有就讀入到OPTIONS變量中。
                       ② 解壓縮輸入的zip包,即我們在上文生成的原始zip包。然後判斷是否用到device-specific extensions(設備擴展)如果用到,隨即讀入到OPTIONS變量中。
                       ③ 判斷是否簽名,然後判斷是否有新內容的增量源,有的話就解壓該增量源包放入一個臨時變量中(source_zip)。自此,所有的準備工作已完畢,隨即會調用該 腳本中最主要的函數WriteFullOTAPackage(input_zip,output_zip)
                       ④ WriteFullOTAPackage函數的處理過程是先獲得腳本的生成器。默認格式是edify。然後獲得metadata元數據,此數據來至於Android的一些環境變量。然後獲得設備配置參數比如api函數的版本。然後判斷是否忽略時間戳。
                       ⑤ WriteFullOTAPackage函數做完準備工作後就開始生成升級用的腳本文件(updater-script)了。生成腳本文件後將上一步獲得的metadata元數據寫入到輸出包out_zip。
                       ⑥至此一個完整的update.zip升級包就生成了。生成位置在:out/target/product/tcc8800/full_tcc8800_evm-ota-eng.mumu.20120315.155326.zip。將升級包拷貝到SD卡中就可以用來升級了。
四、 Android OTA增量包update.zip的生成

         在上面的過程中生成的update.zip升級包是全部系統的升級包。大小有80M多。這對手機用戶來說,用來升級的流量是很大的。而且在實際升級中,我們只希望能夠升級我們改變的那部分內容。這就需要使用增量包來升級。生成增量包的過程也需要上文中提到的ota_from_target_files.py的參與。

         下面是製作update.zip增量包的過程。

          ① 在源碼根目錄下依次執行下列命令
           $ . build/envsetup.sh
           $ lunch 選擇17
           $ make
           $ make otapackage
           執行上面的命令後會在out/target/product/tcc8800/下生成我們第一個系統升級包。我們先將其命名爲A.zip
          ② 在源碼中修改我們需要改變的部分,比如修改內核配置,增加新的驅動等等。修改後再一次執行上面的命令。就會生成第二個我們修改後生成的update.zip升級包。將  其命名爲B.zip。

          ③ 在上文中我們看了ota_from_target_files.py腳本的使用幫助,其中選項-i就是用來生成差分增量包的。使用方法是以上面的A.zip 和B.zip包作爲輸入,以update.zip包作  爲輸出。生成的update.zip就是我們最後需要的增量包。

              具體使用方式是:將上述兩個包拷貝到源碼根目錄下,然後執行下面的命令。

              $ ./build/tools/releasetools/ota_from_target_files -i A.zip B.zip update.zip。

              在執行上述命令時會出現未找到recovery_api_version的錯誤。原因是在執行上面的腳本時如果使用選項i則會調用WriteIncrementalOTAPackage會從A包和B包中的META目錄下搜索misc_info.txt來讀取recovery_api_version的值。但是在執行make  otapackage命令時生成的update.zip包中沒有這個目錄更沒有這個文檔。

              此時我們就需要使用執行make otapackage生成的原始的zip包。這個包的位置在out/target/product/tcc8800/obj/PACKAGING/target_files_intermediates/目錄下,它是在用命令make otapackage之後的中間生產物,是最原始的升級包。我們將兩次編譯的生成的包分別重命名爲A.zip和B.zip,並拷貝到SD卡根目錄下重複執行上面的命令:

               $ ./build/tools/releasetools/ota_form_target_files -i A.zip B.zip update.zip。

              在上述命令即將執行完畢時,在device/telechips/common/releasetools.py會調用IncrementalOTA_InstallEnd,在這個函數中讀取包中的RADIO/bootloader.img。

              而包中是沒有這個目錄和bootloader.img的。所以執行失敗,未能生成對應的update.zip。可能與我們未修改bootloader(升級firmware)有關。此問題在下一篇博客已經解決。


             在下一篇中講解制作增量包失敗的原因,以及解決方案。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章