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
以上是,是用make otapackage制作的update.zip包的白哦准目录结构,下面分析:
1. boot.img 是更新boot分区所需要的文件,其中boot.img主要包括kernel+ramdisk
2. system/目录的内容在升级后会放在系统的system分区,主要用来更新的一些应用或应用会用到的一些库等等。可以将android源码编译out/target/product/msm8916_64/system中的所有文件拷贝到这个目录来代替
3. recovery 目录中的recovery-from-boot.p是boot.img和recovery.img的补丁(patch),主要用来更新recovery分区,其中etc/目录下的install-recovery.sh是更新脚本
4. update-binary是一个二进制文件,相当于一个脚本解释器,能识别update-script中描述的操作。该文件在android源码编译后out/target/product/msm8916_64/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. update.zip包的签名:update.zip更新包在制作完成后需要对其签名,否则在升级时会出现认证失败的错误提示。而签名要使用和目标版一致的加密公钥。加密公钥以及加密需要的三个文件在android源码编译后的具体路径:
out/host/linux-x86/framework/signapk.jar
build/target/product/seturity/testkey.x509.pem
build/target/product/security/testkey.pk8
具体的加密方法: 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
此处,注意路径
8. MANIFEST.MF 这个manifest文件定义了与包的组成结构相关的数据。类似Android应用的mainfest.xml文件
9. CERT.RSA: 与签名文件相关联的签名程序块文件,存储了用于签名jar文件的公共签名
10. 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 plaincopy1. # -----------------------------------------------------------------  
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 plaincopy1. #!/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)   
25.       Deprecated. 
26.  
27.   -k  (--package_key)   
28.       Key to use to sign the package (default is 
29.       "build/target/product/security/testkey"). 
30.  
31.   -i  (--incremental_from)   
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)   
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 plaincopy1. 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 = 0, 0, 0644  
116.     i = cls.ITEMS.get("system/etc/install-recovery.sh", None)  
117.     if i: i.uid, i.gid, i.mode = 0, 0, 0544  
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, (0, 0))  
151.   
152.     # Now find the dmode and fmode that match the most descendants  
153.     # with that (uid, gid), and choose those.  
154.     best_dmode = (0, 0755)  
155.     best_fmode = (0, 0644)  
156.     for k, count in d.iteritems():  
157.       if k[:2] != ug: continue  
158.       if k[2] is not None and count >= best_dmode[0]: best_dmode = (count, k[2])  
159.       if k[3] is 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[0] or item.gid != current[1] or \  
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[0] or item.gid != current[1] or \  
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.5, 0)  
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.2, 0)  
348.   
349.   script.ShowProgress(0.2, 10)  
350.   script.WriteRawImage("/boot", "boot.img")  
351.   
352.   script.ShowProgress(0.1, 0)  
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.1, 0)  
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[0] for 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.8, 0)  
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.1, 10)  
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[1] for 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)有关。
一、生成OTA增量包失败的解决方案

           在上一篇中末尾使用ota_from_target_files脚本制作update.zip增量包时失败,我们先将出现的错误贴出来。

                  
    



              在执行这个脚本的最后读取input_zip中RADIO/bootloader.img时出现错误,显示DeviceSpecifiParams这个对象中没有input_zip属性。
         我们先从脚本中出现错误的调用函数中开始查找。出现错误的调用地方是在函WriteIncrementalOTAPackage(443行)中的 device_specific.IncrementalOTA_InstallEnd(),其位于 WriteIncrementalOTAPackage()中的末尾。进一步跟踪源码发现,这是一个回调函数,他的具体执行方法位于源码中/device /telechips/common/releasetools.py脚本中的IncrementalOTA_InstallEnd()函数。下面就分析 这个函数的作用。
          releasetools.py脚本中的两个函数FullOTA_InstallEnd()和IncrementalOTA_InstallEnd()的 作用都是从输入包中读取RADIO/下的bootloader.img文件写到输出包中,同时生成安装bootloader.img时执行脚本的那部分命 令。只不过一个是直接将输入包中的bootloader.img镜像写到输出包中,一个是先比较target_zip和source_zip中的 bootloader.img是否不同(使用选项-i生成差分包时),然后将新的镜像写入输出包中。下面先将这个函数(位于/device /telechips/common/releasetools.py)的具体实现贴出来:
                    


               我 们的实际情况是,在用命令make otapackage时生成的包中是没有这个RADIO目录下的bootloader.img镜像文件(因为这部分更新已被屏蔽掉了)。但是这个函数中对 于从包中未读取到bootloader.img文件的情况是有错误处理的,即返回。所以我们要从  出现的实际错误中寻找问题的原由。
         真正出现错误的地方是:
          target_bootloader=info.input_zip.read(“RADIO/bootloader.img”)。
         出现错误的原因是:AttributeError:‘DeviceSpecificParams’object has no attribute  ‘input_zip’,提示我们DeviceSpecificParams对象没有input_zip这个属性。
         在用ota_from_target_files脚本制作差分包时使用了选项-i,并且只有这种情况有三个参数,即target_zip 、source_zip、 out_zip。而出现错误的地方是 target_bootloader=info.input_zip_read(“RADIO/bootloader.img”),它使用的是 input_zip,我们要怀疑这个地方是不是使用错了,而应该使用info.target_zip.read()。下面可以证实一下我们的猜测。
         从ota_from_target_files脚本中WriteFullOTAPackage()和 WriteIncrementalOTAPackage这两个函数(分别用来生成全包和差分包)可以发现,在他们的开始部分都对 device_specific进行了赋值。其中WriteFullOTAPackage()对应的参数是input_zip和out_zip,而 WriteIncrementalOTAPackage对应的是target_zip,source_zip,out_zip,我们可以看一下在 WriteIncrementalOTAPackage函数中这部分的具体实现:
                               从上图可以发现,在WriteIncrementalOTAPackage函数对DeviceSpecificParams对象进行初始化时确实使用的是 target_zip而不是input_zip。而在releasetools.py脚本中使用的却是info.input_zip.read(),所以 才会出现DeviceSpecificParams对象没有input_zip这个属性。由此我们找到了问题的所在(这是不是源码中的一个Bug?)。


        将releasetools.py脚本IncrementalOTA_InstallEnd(info)函数中的 target_bootloader=info.input_zip.
read(“RADIO/bootloader.img”) 为:target_bootloader=info.target_zip.read(“RADIO/bootloader.img”),然后重新执行上 面提到的制作差分包命令。就生成了我们需要的差分包update.zip。

更多相关文章

  1. Android(安卓)签名证书
  2. 看完这篇,再也不怕被问到AsyncTask的原理
  3. android 生成二维码
  4. Android(安卓)7.1使用以太网口共享本机4G网络给其他设备
  5. android 7.0 制作ota差分包
  6. android后台执行定时任务(保活)&&使用AlarmManager的各种坑
  7. 解析ANDROID ps命令执行后各项参数的含义
  8. Android——init.rc脚本
  9. Android动画效果 translate、scale、alpha、rotate

随机推荐

  1. mac上的android apk安装器
  2. Android RelativeLayout
  3. Android中使用Context?这几点要注意
  4. Android中RelativeLayout各个属性,例如:and
  5. Android Studio 1.0 苹果电脑安装配置
  6. Android工具箱之组织你的代码文件
  7. Android 应用程序基础知识(1)
  8. AndroidDevTools收集整理Android开发所需
  9. Android布局之xml设置
  10. Android中application的theme不生效的bug