Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1292201
  • 博文数量: 478
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 4833
  • 用 户 组: 普通用户
  • 注册时间: 2014-06-28 11:12
文章分类

全部博文(478)

文章存档

2019年(1)

2018年(27)

2017年(21)

2016年(171)

2015年(258)

我的朋友

分类: Android平台

2016-05-31 11:35:38

转载自  http://blog.csdn.net/mu0206mu


         这篇及以后的篇幅将通过分析update.zip包在具体系统升级的过程,来理解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贴出来如下:


[python] view plain copy
 print?
  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的脚本,位置在/build/tools/releasetools/ota_from_target_files。这个脚本的作用是以第一步生成的zip原始包作为输入,最终生成可用的OTA升级zip包。

             下面我们分析使用这个脚本生成最终OTA升级包的过程。

                   ㈠ 首先看一下这个脚本开始部分的帮助文档。代码如下:

[python] view plain copy
 print?
  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)    
  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 plain copy
 print?
  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)有关。此问题在下一篇博客已经解决。


             在下一篇中讲解制作增量包失败的原因,以及解决方案。

-------------------------------------------



                      Android系统Recovery工作原理之使用update.zip升级过程分析(二)---update.zip差分包问题的解决

       在上一篇末尾提到的生成差分包时出现的问题,现已解决,由于最近比较忙,相隔的时间也比较长,所以单列一个篇幅提示大家。这个问题居然是源码中的问题,可能你已经制作成功了,不过我的这个问题确实是源码中的一个问题,不知道是不是一个bug,下文会具体分析!

一、生成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。


二、          差分包update.zip的更新测试     


                在上面制作差分包脚本命令中,生成差分包的原理是,参照第一个参数(target_zip),将第二个参数(source_zip)中不同的部分输出到第三个参数(output_zip)中。其中target_zip与source_zip的先后顺序不同,产生的差分包也将不同。

          在实际的测试过程中,我们的增量包要删除之前添加的一个应用(在使用update.zip全包升级时增加的),其他的部分如内核都没有改动,所以生成的差分包很简单,只有META-INF这个文件夹。主要的不同都体现在updater-script脚本中,其中的#----start make changes  here----之后的部分就是做出改变的部分,最主要的脚本命令是: delete(“/system/app/CheckUpdateAll.apk” , “/system/recovery.img”);在具体更新时它将删除CheckUpdateAll.apk这个应用。

          为了大家参考,还是把这个差分包的升级脚本贴出来,其对应的完全升级的脚本在第九篇已贴出

[python] view plain copy
 print?
  1. mount("yaffs2""MTD""system""/system");    
  2. assert(file_getprop("/system/build.prop""ro.build.fingerprint") == "telechips/full_tcc8800_evm/tcc8800:2.3.5/GRJ90/eng.mumu.20120309.100232:eng/test-keys" ||    
  3.        file_getprop("/system/build.prop""ro.build.fingerprint") == "telechips/full_tcc8800_evm/tcc8800:2.3.5/GRJ90/eng.mumu.20120309.100232:eng/test-keys");    
  4. assert(getprop("ro.product.device") == "tcc8800" ||    
  5.        getprop("ro.build.product") == "tcc8800");    
  6. ui_print("Verifying current system...");    
  7. show_progress(0.1000000);    
  8.     
  9. # ---- start making changes here ----    
  10.     
  11. ui_print("Removing unneeded files...");    
  12. delete("/system/app/CheckUpdateAll.apk",    
  13.        "/system/recovery.img");    
  14. show_progress(0.8000000);    
  15. ui_print("Patching system files...");    
  16. show_progress(0.10000010);    
  17. ui_print("Symlinks and permissions...");    
  18. set_perm_recursive(0007550644"/system");    
  19. set_perm_recursive(0200007550755"/system/bin");    
  20. set_perm(0300302750"/system/bin/netcfg");    
  21. set_perm(0300402755"/system/bin/ping");    
  22. set_perm(0200006750"/system/bin/run-as");    
  23. set_perm_recursive(1002100207550440"/system/etc/bluetooth");    
  24. set_perm(000755"/system/etc/bluetooth");    
  25. set_perm(100010000640"/system/etc/bluetooth/auto_pairing.conf");    
  26. set_perm(300230020444"/system/etc/bluetooth/blacklist.conf");    
  27. set_perm(100210020440"/system/etc/dbus.conf");    
  28. set_perm(101420000550"/system/etc/dhcpcd/dhcpcd-run-hooks");    
  29. set_perm(020000550"/system/etc/init.goldfish.sh");    
  30. set_perm_recursive(0007550555"/system/etc/ppp");    
  31. set_perm_recursive(0200007550755"/system/xbin");    
  32. set_perm(0006755"/system/xbin/librank");    
  33. set_perm(0006755"/system/xbin/procmem");    
  34. set_perm(0006755"/system/xbin/procrank");    
  35. set_perm(0006755"/system/xbin/su");    
  36. set_perm(0006755"/system/xbin/tcpdump");    
  37. unmount("/system");    



         在做更新测试时,我们要以target_zip系统为依据,也就是更新之前的开发板系统是用target_zip包升级后的系统。否则会更新就会失败,因为在更新时会从系统对应的目录下读取设备以及时间戳等信息(updater-script脚本一开始的部分),进行匹配正确后才进行下一步的安装。

         所有准备都完成后,将我们制作的差分包放到SD卡中,在Settings-->About Phone-->System Update-->Installed From SDCARD执行更新。最后更新完成并重启后,我们会发现之前的CheckUpdateAll.apk被成功删掉了,大功告成!

        至此终于将update.zip包以及其对应的差分包制作成功了,下面的文章开始具体分析制作的update.zip包在实际的更新中所走的过程!




----------------------------------------


            Android系统Recovery工作原理之使用update.zip升级过程分析(三)---Android系统的三种启动模式

        

        以下的篇幅开始分析我们在上两个篇幅中生成的update.zip包在具体更新中所经过的过程,并根据源码分析每一部分的工作原理。

一、       系统更新update.zip包的两种方式

    1.  通过上一个文档,我们知道了怎样制作一个update.zip升级包用于升级系统。Android在升级系统时获得update.zip包的方式有两种。一种是离线升级,即手动拷贝升级包到SD卡(或NAND)中,通过settings-->About phone-->System Update-->选择从SD卡升级。另一种是在线升级,即OTA  Install(over  the  air)。用户通过在线下载升级包到本地,然后更新。这种方式下的update.zip包一般被下载到系统的/CACHE分区下。

     2.  无论将升级包放在什么位置,在使用update.zip更新时都会重启并进入Recovery模式,然后启动recovery服务(/sbin/recovery)来安装我们的update.zip包。

    3.  为此,我们必须了解Recovery模式的工作原理以及Android系统重启时怎样进入Recovery工作模式而不是其他模式(如正常模式)。


二、       Android系统中三种启动模式


       首先我们要了解Android系统启动后可能会进入的几种工作模式。先看下图:

                

       由上图可知Android系统启动后可能进入的模式有以下几种:

       (一) MAGIC KEY(组合键):

              即用户在启动后通过按下组合键,进入不同的工作模式,具体有两种:             

             ① camera + power:若用户在启动刚开始按了camera+power组合键则会进入bootloader模式,并可进一步进入fastboot(快速刷机模式)。

        ② home + power :若用户在启动刚开始按了home+power组合键,系统会直接进入Recovery模式。以这种方式进入Recovery模式时系统会进入一个简单的UI(使用了minui)界面,用来提示用户进一步操作。在tcc8800开发板中提供了一下几种选项操作:

                                “reboot system now”

                                “apply update from sdcard”

                                “wipe data/factory reset”

                                “wipe cache partition”

       (二)正常启动:

                 若启动过程中用户没有按下任何组合键,bootloader会读取位于MISC分区的启动控制信息块BCB(Bootloader Control Block)。它是一个结构体,存放着启动命令command。根据不同的命令,系统又 可以进入三种不同的启动模式。我们先看一下这个结构体的定义。

             struct bootloader_message{

                      char command[32];  //存放不同的启动命令

                      char status[32];   //update-radio或update-hboot完成存放执行结果

                      char recovery[1024]; //存放/cache/recovery/command中的命令

             };

         我们先看command可能的值,其他的在后文具体分析。command可能的值有两种,与值为空(即没有命令)一起区分三种启动模式。

         ①command=="boot-recovery"时,系统会进入Recovery模式。Recovery服务会具体根据/cache/recovery/command中的命令执行相应的操作(例如,升级update.zip或擦除cache,data等)。

         ②command=="update-radia"或"update-hboot"时,系统会进入更新firmware(更新bootloader),具体由bootloader完成。

         ③command为空时,即没有任何命令,系统会进入正常的启动,最后进入主系统(main system)。这种是最通常的启动流程。

         Android系统不同的启动模式的进入是在不同的情形下触发的,我们从SD卡中升级我们的update.zip时会进入Recovery模式是其中一种,其他的比如:系统崩溃,或则在命令行输入启动命令式也会进入Recovery或其他的启动模式。


        为了解我们的update.zip包具体是怎样在Recovery模式中更新完成,并重启到主系统的,我们还要分析Android中Recovery模式的工作原理。

     

             下一篇幅开始看具体的Recovery模式工作原理,以及其在更新中的重要作用。



-------------------------------


                             Android系统Recovery模式的工作原理


        在使用update.zip包升级时怎样从主系统(main system)重启进入Recovery模式,进入Recovery模式后怎样判断做何种操作,以及怎样获得主系统发送给Recovery服务的命令,这一系列问题的解决是通过整个软件平台的不同部分之间的密切通信配合来完成的。为此,我们必须要了解Recovery模式的工作原理,这样才能知道我们的update.zip包是怎样一步步进入Recovery中升级并最后到达主系统的。

一、Recovery模式中的三个部分

         Recovery的工作需要整个软件平台的配合,从通信上来看,主要有三个部分。

        ①MainSystem:即上面提到的正常启动模式(BCB中无命令),是用boot.img启动的系统,Android的正常工作模式。更新时,在这种模式中我们的上层操作就是使用OTA或则从SD卡中升级update.zip包。在重启进入Recovery模式之前,会向BCB中写入命令,以便在重启后告诉bootloader进入Recovery模式。

        ②Recovery:系统进入Recovery模式后会装载Recovery分区,该分区包含recovery.img(同boot.img相同,包含了标准的内核和根文件系统)。进入该模式后主要是运行Recovery服务(/sbin/recovery)来做相应的操作(重启、升级update.zip、擦除cache分区等)。

        ③Bootloader:除了正常的加载启动系统之外,还会通过读取MISC分区(BCB)获得来至Main system和Recovery的消息。

二、Recovery模式中的两个通信接口

       在Recovery服务中上述的三个实体之间的通信是必不可少的,他们相互之间又有以下两个通信接口。

       (一)通过CACHE分区中的三个文件:

             Recovery通过/cache/recovery/目录下的三个文件与mian system通信。具体如下             

            ①/cache/recovery/command:这个文件保存着Main system传给Recovery的命令行,每一行就是一条命令,支持一下几种的组合。

                --send_intent=anystring   //write the text out to recovery/intent     在Recovery结束时在finish_recovery函数中将定义的intent字符串作为参数传进来,并写入到/cache/recovery/intent中

                --update_package=root:path   //verify install an OTA package file     Main system将这条命令写入时,代表系统需要升级,在进入Recovery模式后,将该文件中的命令读取并写入BCB中,然后进行相应的更新update.zip包的操作。

                --wipe_data    //erase user data(and cache),then reboot。擦除用户数据。擦除data分区时必须要擦除cache分区。

                --wipe_cache   //wipe cache(but not user data),then reboot。擦除cache分区。

            ②/cache/recovery/log:Recovery模式在工作中的log打印。在recovery服务运行过程中,stdout以及stderr会重定位到/tmp/recovery.log在recovery退出之前会将其转存到/cache/recovery/log中,供查看。

            ③/cache/recovery/intent:Recovery传递给Main system的信息。作用不详。

       (二)通过BCB(Bootloader Control Block):


             BCB是bootloader与Recovery的通信接口,也是Bootloader与Main system之间的通信接口。存储在flash中的MISC分区,占用三个page,其本身就是一个结构体,具体成员以及各成员含义如下:

             struct bootloader_message{

                       char command[32];

                       char status[32];

                       char recovery[1024];

              };

            ①command成员:其可能的取值我们在上文已经分析过了,即当我们想要在重启进入Recovery模式时,会更新这个成员的值。另外在成功更新后结束Recovery时,会清除这个成员的值,防止重启时再次进入Recovery模式。

            ②status:在完成相应的更新后,Bootloader会将执行结果写入到这个字段。

            ③recovery:可被Main System写入,也可被Recovery服务程序写入。该文件的内容格式为:

                               “recovery\n

                               \n

                               

            该文件存储的就是一个字符串,必须以recovery\n开头,否则这个字段的所有内容域会被忽略。“recovery\n”之后的部分,是/cache/recovery/command支持的命令。可以将其理解为Recovery操作过程中对命令操作的备份。Recovery对其操作的过程为:先读取BCB然后读取/cache/recovery/command,然后将二者重新写回BCB,这样在进入Main system之前,确保操作被执行。在操作之后进入Main system之前,Recovery又会清空BCB的command域和recovery域,这样确保重启后不再进入Recovery模式。

三、如何从Main System重启并进入Recovery模式

       我们先看一下以上三个部分是怎样进行通信的,先看下图:

                       


               我们只看从Main System如何进入Recovery模式,其他的通信在后文中详述。先从Main System开始看,当我们在Main System使用update.zip包进行升级时,系统会重启并进入Recovery模式。在系统重启之前,我们可以看到,Main System定会向BCB中的command域写入boot-recovery(粉红色线),用来告知Bootloader重启后进入recovery模式。这一步是必须的。至于Main System是否向recovery域写入值我们在源码中不能肯定这一点。即便如此,重启进入Recovery模式后Bootloader会从/cache/recovery/command中读取值并放入到BCB的recovery域。而Main System在重启之前肯定会向/cache/recovery/command中写入Recovery将要进行的操作命令。

         至此,我们就大概知道了,在上层使用update.zip升级时,主系统是怎样告知重启后的系统进入Recovery模式的,以及在Recovery模式中完成什么样的操作。

         下一篇开始分析第一个阶段,即我们在上层使用update.zip包升级时,Main System怎样重启并进入Recovery服务的细节流程。


               文章开头我们就提到update.zip包来源有两种,一个是OTA在线下载(一般下载到/CACHE分区),一个是手动拷贝到SD卡中。不论是哪种方式获得update.zip包,在进入Recovery模式前,都未对这个zip包做处理。只是在重启之前将zip包的路径告诉了Recovery服务(通过将--update_package=CACHE:some_filename.zip或--update_package=SDCARD:update.zip命令写入到/cache/recovery/command中)。在这里我们假设update.zip包已经制作好并拷贝到了SD卡中,并以Settings-->About Phone-->System Update-->Installed From SDCARD方式升级。

         我们的测试开发板是TCC8800,使用的Android源码是gingerbread0919,在这种方式下升级的源码位于gingerbread/device/telechips/common/apps/TelechipsSystemUpdater/src/com/telechips/android/systemupdater/下。         下面我们具体分析这种升级方式下,我们的update.zip是怎样从上层一步步进入到Recovery模式的。


一、从System Update到Reboot


        当我们依次选择Settings-->About Phone-->System Update-->Installed From SDCARD后会弹出一个对话框,提示已有update.zip包是否现在更新,我们从这个地方跟踪。这个对话框的源码是SystemUpdateInstallDialog.。


        ①在mNowButton按钮的监听事件里,会调用mService.rebootAndUpdate(new  File(mFile))。这个mService就是SystemUpdateService的实例。 这  个类所在的源码文件是SystemUpdateService.java。这个函数的参数是一个文件。它肯定就是我们的update.zip包了。我们可以证实一下这个猜想。

        ②mFile的值:在SystemUpdateInstallDialog.java中的ServiceConnection中我们可以看到这个mFile的值有两个来源。

                 来源一:

                  mFile的一个来源是这个是否立即更新提示框接受的上一个Activity以“file”标记传来的值。这个Activity就是SystemUpdate.java。它是一个PreferenceActivity类型的。在其onPreferenceChange函数中定义了向下一个Activity传送的值,这个值是根据我们不同的选择而定的。如果我们在之前选择了从SD卡安装,则这个传下去的“file”值为“/sdcard/update.zip”。如果选择了从NAND安装,则对应的值为“/nand/update.zip”。


                 来源二:

                 另个一来源是从mService.getInstallFile()获得。我们进一步跟踪就可发现上面这个函数获得的值就是“/cache”+ mUpdateFileURL.getFile();这就是OTA在线下载后对应的文件路径。不论参数mFile的来源如何,我们可以发现在mNowButton按钮的监听事件里是将整个文件,也就是我们的update.zip包作为参数往rebootAndUpdate()中传递的。

        ③rebootAndUpdate:在这个函数中Main System做了重启前的准备。继续跟踪下去会发现,在SystemUpdateService.java中的rebootAndUpdate函数中新建了一个线程,在这个线程中最后调用的就是RecoverySystem.installPackage(mContext,mFile),我们的update.zip包也被传递进来了。

        ④RecoverySystem类:RecoverySystem类的源码所在文件路径为:gingerbread0919/frameworks/base/core/java/android/os/RecoverySystem.java。我们关心的是installPackage(Context context,FilepackageFile)函数。这个函数首先根据我们传过来的包文件,获取这个包文件的绝对路径filename。然后将其拼成arg=“--update_package=”+filename。它最终会被写入到BCB中。这个就是重启进入Recovery模式后,Recovery服务要进行的操作。它被传递到函数bootCommand(context,arg)。

        ⑤bootCommand():在这个函数中才是Main System在重启前真正做的准备。主要做了以下事情,首先创建/cache/recovery/目录,删除这个目录下的command和log(可能不存在)文件在sqlite中的备份。然后将上面④步中的arg命令写入到/cache/recovery/command文件中。下一步就是真正重启了。接下来看一下在重启函数reboot中所做的事情。

         ⑥pm.reboot():重启之前先获得了PowerManager(电源管理)并进一步获得其系统服务。然后调用了pm.reboot(“recovery”)函数。他就是/gingerbread0919/bionic/libc/unistd/reboot.c中的reboot函数。这个函数实际上是一个系统调用,即__reboot(LINUX_REBOOT_MAGIC1,LINUX_REBOOT_MAGIC2,mode,NULL);从这个函数我们可以看出前两个参数就代表了我们的组合键,mode就是我们传过来的“recovery”。再进一步跟踪就到了汇编代码了,我们无法直接查看它的具体实现细节。但可以肯定的是 这个函数只将“recovery”参数传递过去了,之后将“boot-recovery”写入到了MISC分区的BCB数据块的command域中。这样在重启之后Bootloader才知道要进入Recovery模式。


         在这里我们无法肯定Main System在重启之前对BCB的recovery域是否进行了操作。其实在重启前是否更新BCB的recovery域是不重要的,因为进入Recovery服务后,Recovery会自动去/cache/recovery/command中读取要进行的操作然后写入到BCB的recovery域中。

         至此,Main System就开始重启并进入Recovery模式。在这之前Main System做的最实质的就是两件事,一是将“boot-recovery”写入BCB的command域,二是将--update_package=/cache/update.zip”或则“--update_package=/sdcard/update.zip”写入/cache/recovery/command文件中。下面的部分就开始重启并进入Recovery服务了。


二、从reboot到Recovery服务

       

            这个过程我们在上文(对照第一个图)已经讲过了。从Bootloader开始如果没有组合键按下,就从MISC分区读取BCB块的command域(在主系统时已经将“boot-recovery”写入)。然后就以Recovery模式开始启动。与正常启动不同的是Recovery模式下加载的镜像是recovery.img。这个镜像同boot.img类似,也包含了标准的内核和根文件系统。其后就与正常的启动系统类似,也是启动内核,然后启动文件系统。在进入文件系统后会执行/init,init的配置文件就是/init.rc。这个配置文件来自bootable/recovery/etc/init.rc。查看这个文件我们可以看到它做的事情很简单:

       ①设置环境变量。

       ②建立etc连接。

       ③新建目录,备用。

       ④挂载/tmp为内存文件系统tmpfs

       ⑤启动recovery(/sbin/recovery)服务。

       ⑥启动adbd服务(用于调试)。

       这里最重要的就是当然就recovery服务了。在Recovery服务中将要完成我们的升级工作。

       我们将在下一篇详细分析Recovery服务的流程细节。






         Recovery服务毫无疑问是Recovery启动模式中最核心的部分。它完成Recovery模式所有的工作。Recovery程序对应的源码文件位于:/gingerbread0919/bootable/recovery/recovery.c。


一、 Recovery的三类服务:


         先看一下在这个源码文件中开始部分的一大段注释,这将对我们理解Recovery服务的主要功能有很大帮助。代码如下:

         

[cpp] view plain copy
 print?
  1. /*  
  2.  * The recovery tool communicates with the main system through /cache files.  
  3.  *   /cache/recovery/command - INPUT - command line for tool, one arg per line  
  4.  *   /cache/recovery/log - OUTPUT - combined log file from recovery run(s)  
  5.  *   /cache/recovery/intent - OUTPUT - intent that was passed in  
  6.  *  
  7.  * The arguments which may be supplied in the recovery.command file:  
  8.  *   --send_intent=anystring - write the text out to recovery.intent  
  9.  *   --update_package=path - verify install an OTA package file  
  10.  *   --wipe_data - erase user data (and cache), then reboot  
  11.  *   --wipe_cache - wipe cache (but not user data), then reboot  
  12.  *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs  
  13.  *  
  14.  * After completing, we remove /cache/recovery/command and reboot.  
  15.  * Arguments may also be supplied in the bootloader control block (BCB).  
  16.  * These important scenarios must be safely restartable at any point:  
  17.  *  
  18.  * FACTORY RESET  
  19.  * 1. user selects "factory reset"  
  20.  * 2. main system writes "--wipe_data" to /cache/recovery/command  
  21.  * 3. main system reboots into recovery  
  22.  * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"  
  23.  *    -- after this, rebooting will restart the erase --  
  24.  * 5. erase_volume() reformats /data  
  25.  * 6. erase_volume() reformats /cache  
  26.  * 7. finish_recovery() erases BCB  
  27.  *    -- after this, rebooting will restart the main system --  
  28.  * 8. main() calls reboot() to boot main system  
  29.  *  
  30.  * OTA INSTALL  
  31.  * 1. main system downloads OTA package to /cache/some-filename.zip  
  32.  * 2. main system writes "--update_package=/cache/some-filename.zip"  
  33.  * 3. main system reboots into recovery  
  34.  * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."  
  35.  *    -- after this, rebooting will attempt to reinstall the update --  
  36.  * 5. install_package() attempts to install the update  
  37.  *    NOTE: the package install must itself be restartable from any point  
  38.  * 6. finish_recovery() erases BCB  
  39.  *    -- after this, rebooting will (try to) restart the main system --  
  40.  * 7. ** if install failed **  
  41.  *    7a. prompt_and_wait() shows an error icon and waits for the user  
  42.  *    7b; the user reboots (pulling the battery, etc) into the main system  
  43.  * 8. main() calls maybe_install_firmware_update()  
  44.  *    ** if the update contained radio/hboot firmware **:  
  45.  *    8a. m_i_f_u() writes BCB with "boot-recovery" and "--wipe_cache"  
  46.  *        -- after this, rebooting will reformat cache & restart main system --  
  47.  *    8b. m_i_f_u() writes firmware image into raw cache partition  
  48.  *    8c. m_i_f_u() writes BCB with "update-radio/hboot" and "--wipe_cache"  
  49.  *        -- after this, rebooting will attempt to reinstall firmware --  
  50.  *    8d. bootloader tries to flash firmware  
  51.  *    8e. bootloader writes BCB with "boot-recovery" (keeping "--wipe_cache")  
  52.  *        -- after this, rebooting will reformat cache & restart main system --  
  53.  *    8f. erase_volume() reformats /cache  
  54.  *    8g. finish_recovery() erases BCB  
  55.  *        -- after this, rebooting will (try to) restart the main system --  
  56.  * 9. main() calls reboot() to boot main system  
  57.  *  
  58.  * SECURE FILE SYSTEMS ENABLE/DISABLE  
  59.  * 1. user selects "enable encrypted file systems"  
  60.  * 2. main system writes "--set_encrypted_filesystems=on|off" to  
  61.  *    /cache/recovery/command  
  62.  * 3. main system reboots into recovery  
  63.  * 4. get_args() writes BCB with "boot-recovery" and  
  64.  *    "--set_encrypted_filesystems=on|off"  
  65.  *    -- after this, rebooting will restart the transition --  
  66.  * 5. read_encrypted_fs_info() retrieves encrypted file systems settings from /data  
  67.  *    Settings include: property to specify the Encrypted FS istatus and  
  68.  *    FS encryption key if enabled (not yet implemented)  
  69.  * 6. erase_volume() reformats /data  
  70.  * 7. erase_volume() reformats /cache  
  71.  * 8. restore_encrypted_fs_info() writes required encrypted file systems settings to /data  
  72.  *    Settings include: property to specify the Encrypted FS status and  
  73.  *    FS encryption key if enabled (not yet implemented)  
  74.  * 9. finish_recovery() erases BCB  
  75.  *    -- after this, rebooting will restart the main system --  
  76.  * 10. main() calls reboot() to boot main system  
  77.  */    




          从注释中我们可以看到Recovery的服务内容主要有三类:

         ①FACTORY RESET,恢复出厂设置。

         ②OTA INSTALL,即我们的update.zip包升级。

         ③ENCRYPTED FILE SYSTEM ENABLE/DISABLE,使能/关闭加密文件系统。具体的每一类服务的大概工作流程,注释中都有,我们在下文中会详细讲解OTA INSTALL的工作流程。这三类服务的大概的流程都是通用的,只是不同操作体现与不同的操作细节。下面我们看Recovery服务的通用流程。


二、Recovery服务的通用流程:


        在这里我们以OTA INSTALL的流程为例具体分析。并从相关函数的调用过程图开始,如下图:


          

          我们顺着流程图分析,从recovery.c的main函数开始:

          1.    ui_init():Recovery服务使用了一个基于framebuffer的简单ui(miniui)系统。这个函数对其进行了简单的初始化。在Recovery服务的过程中主要用于显示一个背景图片(正在安装或安装失败)和一个进度条(用于显示进度)。另外还启动了两个线程,一个用于处理进度条的显示(progress_thread),另一个用于响应用户的按键(input_thread)。

          2.    get_arg():这个函数主要做了上图中get_arg()往右往下直到parse arg/v的工作。我们对照着流程一个一个看。


                ①get_bootloader_message():主要工作是根据分区的文件格式类型(mtd或emmc)从MISC分区中读取BCB数据块到一个临时的变量中。

                ②然后开始判断Recovery服务是否有带命令行的参数(/sbin/recovery,根据现有的逻辑是没有的),若没有就从BCB中读取recovery域。如果读取失败则从/cache/recovery/command中读取然后。这样这个BCB的临时变量中的recovery域就被更新了。在将这个BCB的临时变量写回真实的BCB之前,又更新的这个BCB临时变量的command域为“boot-recovery”。这样做的目的是如果在升级失败(比如升级还未结束就断电了)时,系统在重启之后还会进入Recovery模式,直到升级完成。

                ③在这个BCB临时变量的各个域都更新完成后使用set_bootloader_message()写回到真正的BCB块中。

                这个过程可以用一个简单的图来概括,这样更清晰:

                                 


          3.     parserargc/argv:解析我们获得参数。注册所解析的命令(register_update_command),在下面的操作中会根据这一步解析的值进行一步步的判断,然后进行相应的操作。

          4.    if(update_package):判断update_package是否有值,若有就表示需要升级更新包,此时就会调用install_package()(即图中红色的第二个阶段)。在这一步中将要完成安装实际的升级包。这是最为复杂,也是升级update.zip包最为核心的部分。我们在下一节详细分析这一过程。为从宏观上理解Recovery服务的框架,我们将这一步先略过,假设已经安装完成了。我们接着往下走,看安装完成后Recovery怎样一步步结束服务,并重启到新的主系统的。

          5.    if(wipe_data/wipe_cache):这一步判断实际是两步,在源码中是先判断是否擦除data分区(用户数据部分)的,然后再判断是否擦除cache分区。值得注意的是在擦除data分区的时候必须连带擦除cache分区。在只擦除cache分区的情形下可以不擦除data分区。

          6.    maybe_install_firmware_update():如果升级包中包含/radio/hboot firmware的更新,则会调用这个函数。查看源码发现,在注释中(OTA INSTALL)有这一个流程。但是main函数中并没有显示调用这个函数。目前尚未发现到底是在什么地方处理。但是其流程还是向上面的图示一样。即,① 先向BCB中写入“boot-recovery”和“—wipe_cache”之后将cache分区格式化,然后将firmware image 写入原始的cache分区中。②将命令“update-radio/hboot”和“—wipe_cache”写入BCB中,然后开始重新安装firmware并刷新firmware。③之后又会进入图示中的末尾,即finish_recovery()。

          7.    prompt_and_wait():这个函数是在一个判断中被调用的。其意义是如果安装失败(update.zip包错误或验证签名失败),则等待用户的输入处理(如通过组合键reboot等)。

          8.    finish_recovery():这是Recovery关闭并进入Main System的必经之路。其大体流程如下:

                                               


               ① 将intent(字符串)的内容作为参数传进finish_recovery中。如果有intent需要告知Main System,则将其写入/cache/recovery/intent中。这个intent的作用尚不知有何用。

               ② 将内存文件系统中的Recovery服务的日志(/tmp/recovery.log)拷贝到cache(/cache/recovery/log)分区中,以便告知重启后的Main System发生过什么。

               ③ 擦除MISC分区中的BCB数据块的内容,以便系统重启后不在进入Recovery模式而是进入更新后的主系统。

               ④ 删除/cache/recovery/command文件。这一步也是很重要的,因为重启后Bootloader会自动检索这个文件,如果未删除的话又会进入Recovery模式。原理在上面已经讲的很清楚了。


          9.    reboot():这是一个系统调用。在这一步Recovery完成其服务重启并进入Main System。这次重启和在主系统中重启进入Recovery模式调用的函数是一样的,但是其方向是不一样的。所以参数也就不一样。查看源码发现,其重启模式是RB_AUTOBOOT。这是一个系统的宏。


 

            至此,我们对Recovery服务的整个流程框架已有了大概的认识。下面就是升级update.zip包时特有的也是Recovery服务中关于安装升级包最核心的第二个阶段。即我们图例中的红色2的那个分支。


           我们将在下一篇详细讲解这一部分,即Recovery服务的核心部分install_package函数



一、       Recovery服务的核心install_package(升级update.zip特有)


              和Recovery服务中的wipe_data、wipe_cache不同,install_package()是升级update.zip特有的一部分,也是最核心的部分。在这一步才真正开始对我们的update.zip包进行处理。下面就开始分析这一部分。还是先看图例:

                          


            这一部分的源码文件位于:/gingerbread0919/bootable/recovery/install.c。这是一个没有main函数的源码文件,还是把源码先贴出来如下:

[cpp] view plain copy
 print?
  1. /*  
  2.  * Copyright (C) 2007 The Android Open Source Project  
  3.  *  
  4.  * Licensed under the Apache License, Version 2.0 (the "License");  
  5.  * you may not use this file except in compliance with the License.  
  6.  * You may obtain a copy of the License at  
  7.  *  
  8.  *      http://www.apache.org/licenses/LICENSE-2.0  
  9.  *  
  10.  * Unless required by applicable law or agreed to in writing, software  
  11.  * distributed under the License is distributed on an "AS IS" BASIS,  
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  13.  * See the License for the specific language governing permissions and  
  14.  * limitations under the License.  
  15.  */    
  16.     
  17. #include     
  18. #include     
  19. #include     
  20. #include     
  21. #include     
  22. #include     
  23. #include     
  24.     
  25. #include "common.h"    
  26. #include "install.h"    
  27. #include "mincrypt/rsa.h"    
  28. #include "minui/minui.h"    
  29. #include "minzip/SysUtil.h"    
  30. #include "minzip/Zip.h"    
  31. #include "mtdutils/mounts.h"    
  32. #include "mtdutils/mtdutils.h"    
  33. #include "roots.h"    
  34. #include "verifier.h"    
  35.     
  36. #define ASSUMED_UPDATE_BINARY_NAME  "META-INF/com/google/android/update-binary"    
  37. #define PUBLIC_KEYS_FILE "/res/keys"    
  38.     
  39. // If the package contains an update binary, extract it and run it.    
  40. static int    
  41. try_update_binary(const char *path, ZipArchive *zip) {    
  42.     const ZipEntry* binary_entry =    
  43.             mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME);    
  44.     if (binary_entry == NULL) {    
  45.         mzCloseZipArchive(zip);    
  46.         return INSTALL_CORRUPT;    
  47.     }    
  48.     
  49.     char* binary = "/tmp/update_binary";    
  50.     unlink(binary);    
  51.     int fd = creat(binary, 0755);    
  52.     if (fd < 0) {    
  53.         mzCloseZipArchive(zip);    
  54.         LOGE("Can't make %s\n", binary);    
  55.         return 1;    
  56.     }    
  57.     bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd);    
  58.     close(fd);    
  59.     mzCloseZipArchive(zip);    
  60.     
  61.     if (!ok) {    
  62.         LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME);    
  63.         return 1;    
  64.     }    
  65.     
  66.     int pipefd[2];    
  67.     pipe(pipefd);    
  68.     
  69.     // When executing the update binary contained in the package, the    
  70.     // arguments passed are:    
  71.     //    
  72.     //   - the version number for this interface    
  73.     //    
  74.     //   - an fd to which the program can write in order to update the    
  75.     //     progress bar.  The program can write single-line commands:    
  76.     //    
  77.     //        progress      
  78.     //            fill up the next  part of of the progress bar    
  79.     //            over  seconds.  If  is zero, use    
  80.     //            set_progress commands to manually control the    
  81.     //            progress of this segment of the bar    
  82.     //    
  83.     //        set_progress     
  84.     //             should be between 0.0 and 1.0; sets the    
  85.     //            progress bar within the segment defined by the most    
  86.     //            recent progress command.    
  87.     //    
  88.     //        firmware <"hboot"|"radio">     
  89.     //            arrange to install the contents of  in the    
  90.     //            given partition on reboot.    
  91.     //    
  92.     //            (API v2:  may start with "PACKAGE:" to    
  93.     //            indicate taking a file from the OTA package.)    
  94.     //    
  95.     //            (API v3: this command no longer exists.)    
  96.     //    
  97.     //        ui_print     
  98.     //            display  on the screen.    
  99.     //    
  100.     //   - the name of the package zip file.    
  101.     //    
  102.     
  103.     char** args = malloc(sizeof(char*) * 5);    
  104.     args[0] = binary;    
  105.     args[1] = EXPAND(RECOVERY_API_VERSION);   // defined in Android.mk    
  106.     args[2] = malloc(10);    
  107.     sprintf(args[2], "%d", pipefd[1]);    
  108.     args[3] = (char*)path;    
  109.     args[4] = NULL;    
  110.     
  111.     pid_t pid = fork();    
  112.     if (pid == 0) {    
  113.         close(pipefd[0]);    
  114.         execv(binary, args);    
  115.         fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno));    
  116.         _exit(-1);    
  117.     }    
  118.     close(pipefd[1]);    
  119.     
  120.     char buffer[1024];    
  121.     FILE* from_child = fdopen(pipefd[0], "r");    
  122.     while (fgets(buffer, sizeof(buffer), from_child) != NULL) {    
  123.         char* command = strtok(buffer, " \n");    
  124.         if (command == NULL) {    
  125.             continue;    
  126.         } else if (strcmp(command, "progress") == 0) {    
  127.             char* fraction_s = strtok(NULL, " \n");    
  128.             char* seconds_s = strtok(NULL, " \n");    
  129.     
  130.             float fraction = strtof(fraction_s, NULL);    
  131.             int seconds = strtol(seconds_s, NULL, 10);    
  132.     
  133.             ui_show_progress(fraction * (1-VERIFICATION_PROGRESS_FRACTION),    
  134.                              seconds);    
  135.         } else if (strcmp(command, "set_progress") == 0) {    
  136.             char* fraction_s = strtok(NULL, " \n");    
  137.             float fraction = strtof(fraction_s, NULL);    
  138.             ui_set_progress(fraction);    
  139.         } else if (strcmp(command, "ui_print") == 0) {    
  140.             char* str = strtok(NULL, "\n");    
  141.             if (str) {    
  142.                 ui_print("%s", str);    
  143.             } else {    
  144.                 ui_print("\n");    
  145.             }    
  146.         } else {    
  147.             LOGE("unknown command [%s]\n", command);    
  148.         }    
  149.     }    
  150.     fclose(from_child);    
  151.     
  152.     int status;    
  153.     waitpid(pid, &status, 0);    
  154.     if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {    
  155.         LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status));    
  156.         return INSTALL_ERROR;    
  157.     }    
  158.     
  159.     return INSTALL_SUCCESS;    
  160. }    
  161.     
  162. // Reads a file containing one or more public keys as produced by    
  163. // DumpPublicKey:  this is an RSAPublicKey struct as it would appear    
  164. // as a C source literal, eg:    
  165. //    
  166. //  "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"    
  167. //    
  168. // (Note that the braces and commas in this example are actual    
  169. // characters the parser expects to find in the file; the ellipses    
  170. // indicate more numbers omitted from this example.)    
  171. //    
  172. // The file may contain multiple keys in this format, separated by    
  173. // commas.  The last key must not be followed by a comma.    
  174. //    
  175. // Returns NULL if the file failed to parse, or if it contain zero keys.    
  176. static RSAPublicKey*    
  177. load_keys(const char* filename, int* numKeys) {    
  178.     RSAPublicKey* out = NULL;    
  179.     *numKeys = 0;    
  180.     
  181.     FILE* f = fopen(filename, "r");    
  182.     if (f == NULL) {    
  183.         LOGE("opening %s: %s\n", filename, strerror(errno));    
  184.         goto exit;    
  185.     }    
  186.     
  187.     int i;    
  188.     bool done = false;    
  189.     while (!done) {    
  190.         ++*numKeys;    
  191.         out = realloc(out, *numKeys * sizeof(RSAPublicKey));    
  192.         RSAPublicKey* key = out + (*numKeys - 1);    
  193.         if (fscanf(f, " { %i , 0x%x , { %u",    
  194.                    &(key->len), &(key->n0inv), &(key->n[0])) != 3) {    
  195.             goto exit;    
  196.         }    
  197.         if (key->len != RSANUMWORDS) {    
  198.             LOGE("key length (%d) does not match expected size\n", key->len);    
  199.             goto exit;    
  200.         }    
  201.         for (i = 1; i < key->len; ++i) {    
  202.             if (fscanf(f, " , %u", &(key->n[i])) != 1) goto exit;    
  203.         }    
  204.         if (fscanf(f, " } , { %u", &(key->rr[0])) != 1) goto exit;    
  205.         for (i = 1; i < key->len; ++i) {    
  206.             if (fscanf(f, " , %u", &(key->rr[i])) != 1) goto exit;    
  207.         }    
  208.         fscanf(f, " } } ");    
  209.     
  210.         // if the line ends in a comma, this file has more keys.    
  211.         switch (fgetc(f)) {    
  212.             case ',':    
  213.                 // more keys to come.    
  214.                 break;    
  215.     
  216.             case EOF:    
  217.                 done = true;    
  218.                 break;    
  219.     
  220.             default:    
  221.                 LOGE("unexpected character between keys\n");    
  222.                 goto exit;    
  223.         }    
  224.     }    
  225.     
  226.     fclose(f);    
  227.     return out;    
  228.     
  229. exit:    
  230.     if (f) fclose(f);    
  231.     free(out);    
  232.     *numKeys = 0;    
  233.     return NULL;    
  234. }    
  235.     
  236. int    
  237. install_package(const char *path)    
  238. {    
  239.     ui_set_background(BACKGROUND_ICON_INSTALLING);    
  240.     ui_print("Finding update package...\n");    
  241.     ui_show_indeterminate_progress();    
  242.     LOGI("Update location: %s\n", path);    
  243.     
  244.     if (ensure_path_mounted(path) != 0) {    
  245.         LOGE("Can't mount %s\n", path);    
  246.         return INSTALL_CORRUPT;    
  247.     }    
  248.     
  249.     ui_print("Opening update package...\n");    
  250.     
  251.     int numKeys;    
  252.     RSAPublicKey* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);    
  253.     if (loadedKeys == NULL) {    
  254.         LOGE("Failed to load keys\n");    
  255.         return INSTALL_CORRUPT;    
  256.     }    
  257.     LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);    
  258.     
  259.     // Give verification half the progress bar...    
  260.     ui_print("Verifying update package...\n");    
  261.     ui_show_progress(    
  262.             VERIFICATION_PROGRESS_FRACTION,    
  263.             VERIFICATION_PROGRESS_TIME);    
  264.     
  265.     int err;    
  266.     err = verify_file(path, loadedKeys, numKeys);    
  267.     free(loadedKeys);    
  268.     LOGI("verify_file returned %d\n", err);    
  269.     if (err != VERIFY_SUCCESS) {    
  270.         LOGE("signature verification failed\n");    
  271.         return INSTALL_CORRUPT;    
  272.     }    
  273.     
  274.     /* Try to open the package.  
  275.      */    
  276.     ZipArchive zip;    
  277.     err = mzOpenZipArchive(path, &zip);    
  278.     if (err != 0) {    
  279.         LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");    
  280.         return INSTALL_CORRUPT;    
  281.     }    
  282.     
  283.     /* Verify and install the contents of the package.  
  284.      */    
  285.     ui_print("Installing update...\n");    
  286.     return try_update_binary(path, &zip);    
  287. }    




             下面顺着上面的流程图和源码来分析这一流程:

            ①ensure_path_mount():先判断所传的update.zip包路径所在的分区是否已经挂载。如果没有则先挂载。

            ②load_keys():加载公钥源文件,路径位于/res/keys。这个文件在Recovery镜像的根文件系统中。

            ③verify_file():对升级包update.zip包进行签名验证。

            ④mzOpenZipArchive():打开升级包,并将相关的信息拷贝到一个临时的ZipArchinve变量中。这一步并未对我们的update.zip包解压。

            ⑤try_update_binary():在这个函数中才是对我们的update.zip升级的地方。这个函数一开始先根据我们上一步获得的zip包信息,以及升级包的绝对路径将update_binary文件拷贝到内存文件系统的/tmp/update_binary中。以便后面使用。

            ⑥pipe():创建管道,用于下面的子进程和父进程之间的通信。

            ⑦fork():创建子进程。其中的子进程主要负责执行binary(execv(binary,args),即执行我们的安装命令脚本),父进程负责接受子进程发送的命令去更新ui显示(显示当前的进度)。子父进程间通信依靠管道。

            ⑧其中,在创建子进程后,父进程有两个作用。一是通过管道接受子进程发送的命令来更新UI显示。二是等待子进程退出并返回INSTALL SUCCESS。其中子进程在解析执行安装脚本的同时所发送的命令有以下几种:

                       progress   :根据第二个参数secs(秒)来设置进度条。

                       set_progress  :直接设置进度条,frac取值在0.0到0.1之间。


                       firmware <”hboot”|”radio”>:升级firmware时使用,在API  V3中不再使用。

                       ui_print :在屏幕上显示字符串,即打印更新过程。

                 execv(binary,args)的作用就是去执行binary程序,这个程序的实质就是去解析update.zip包中的updater-script脚本中的命令并执行。由此,Recovery服务就进入了实际安装update.zip包的过程。

                 下一篇继续分析使用update-binary解析并执行updater-script的过程。



一、update_binary的执行过程分析

       上一篇幅中的子进程所执行的程序binary实际上就是update.zip包中的update-binary。我们在上文中也说过,Recovery服务在做这一部分工作的时候是先将包中update-binary拷贝到内存文件系统中的/tmp/update_binary,然后再执行的。update_binary程序的源码位于gingerbread0919/bootable/recovery/updater/updater.c,源码如下:

[cpp] view plain copy
 print?
  1. /*  
  2.  * Copyright (C) 2009 The Android Open Source Project  
  3.  *  
  4.  * Licensed under the Apache License, Version 2.0 (the "License");  
  5.  * you may not use this file except in compliance with the License.  
  6.  * You may obtain a copy of the License at  
  7.  *  
  8.  *      http://www.apache.org/licenses/LICENSE-2.0  
  9.  *  
  10.  * Unless required by applicable law or agreed to in writing, software  
  11.  * distributed under the License is distributed on an "AS IS" BASIS,  
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  13.  * See the License for the specific language governing permissions and  
  14.  * limitations under the License.  
  15.  */    
  16.     
  17. #include     
  18. #include     
  19. #include     
  20.     
  21. #include "edify/expr.h"    
  22. #include "updater.h"    
  23. #include "install.h"    
  24. #include "minzip/Zip.h"    
  25.     
  26. // Generated by the makefile, this function defines the    
  27. // RegisterDeviceExtensions() function, which calls all the    
  28. // registration functions for device-specific extensions.    
  29. #include "register.inc"    
  30.     
  31. // Where in the package we expect to find the edify script to execute.    
  32. // (Note it's "updateR-script", not the older "update-script".)    
  33. #define SCRIPT_NAME "META-INF/com/google/android/updater-script"    
  34.     
  35. int main(int argc, char** argv) {    
  36.     // Various things log information to stdout or stderr more or less    
  37.     // at random.  The log file makes more sense if buffering is    
  38.     // turned off so things appear in the right order.    
  39.     setbuf(stdout, NULL);    
  40.     setbuf(stderr, NULL);    
  41.     
  42.     if (argc != 4) {    
  43.         fprintf(stderr, "unexpected number of arguments (%d)\n", argc);    
  44.         return 1;    
  45.     }    
  46.     
  47.     char* version = argv[1];    
  48.     if ((version[0] != '1' && version[0] != '2' && version[0] != '3') ||    
  49.         version[1] != '\0') {    
  50.         // We support version 1, 2, or 3.    
  51.         fprintf(stderr, "wrong updater binary API; expected 1, 2, or 3; "    
  52.                         "got %s\n",    
  53.                 argv[1]);    
  54.         return 2;    
  55.     }    
  56.     
  57.     // Set up the pipe for sending commands back to the parent process.    
  58.     
  59.     int fd = atoi(argv[2]);    
  60.     FILE* cmd_pipe = fdopen(fd, "wb");    
  61.     setlinebuf(cmd_pipe);    
  62.     
  63.     // Extract the script from the package.    
  64.     
  65.     char* package_data = argv[3];    
  66.     ZipArchive za;    
  67.     int err;    
  68.     err = mzOpenZipArchive(package_data, &za);    
  69.     if (err != 0) {    
  70.         fprintf(stderr, "failed to open package %s: %s\n",    
  71.                 package_data, strerror(err));    
  72.         return 3;    
  73.     }    
  74.     
  75.     const ZipEntry* script_entry = mzFindZipEntry(&za, SCRIPT_NAME);    
  76.     if (script_entry == NULL) {    
  77.         fprintf(stderr, "failed to find %s in %s\n", SCRIPT_NAME, package_data);    
  78.         return 4;    
  79.     }    
  80.     
  81.     char* script = malloc(script_entry->uncompLen+1);    
  82.     if (!mzReadZipEntry(&za, script_entry, script, script_entry->uncompLen)) {    
  83.         fprintf(stderr, "failed to read script from package\n");    
  84.         return 5;    
  85.     }    
  86.     script[script_entry->uncompLen] = '\0';    
  87.     
  88.     // Configure edify's functions.    
  89.     
  90.     RegisterBuiltins();    
  91.     RegisterInstallFunctions();    
  92.     RegisterDeviceExtensions();    
  93.     FinishRegistration();    
  94.     
  95.     // Parse the script.    
  96.     
  97.     Expr* root;    
  98.     int error_count = 0;    
  99.     yy_scan_string(script);    
  100.     int error = yyparse(&root, &error_count);    
  101.     if (error != 0 || error_count > 0) {    
  102.         fprintf(stderr, "%d parse errors\n", error_count);    
  103.         return 6;    
  104.     }    
  105.     
  106.     // Evaluate the parsed script.    
  107.     
  108.     UpdaterInfo updater_info;    
  109.     updater_info.cmd_pipe = cmd_pipe;    
  110.     updater_info.package_zip = &za;    
  111.     updater_info.version = atoi(version);    
  112.     
  113.     State state;    
  114.     state.cookie = &updater_info;    
  115.     state.script = script;    
  116.     state.errmsg = NULL;    
  117.     
  118.     char* result = Evaluate(&state, root);    
  119.     if (result == NULL) {    
  120.         if (state.errmsg == NULL) {    
  121.             fprintf(stderr, "script aborted (no error message)\n");    
  122.             fprintf(cmd_pipe, "ui_print script aborted (no error message)\n");    
  123.         } else {    
  124.             fprintf(stderr, "script aborted: %s\n", state.errmsg);    
  125.             char* line = strtok(state.errmsg, "\n");    
  126.             while (line) {    
  127.                 fprintf(cmd_pipe, "ui_print %s\n", line);    
  128.                 line = strtok(NULL, "\n");    
  129.             }    
  130.             fprintf(cmd_pipe, "ui_print\n");    
  131.         }    
  132.         free(state.errmsg);    
  133.         return 7;    
  134.     } else {    
  135.         fprintf(stderr, "script result was [%s]\n", result);    
  136.         free(result);    
  137.     }    
  138.     
  139.     if (updater_info.package_zip) {    
  140.         mzCloseZipArchive(updater_info.package_zip);    
  141.     }    
  142.     free(script);    
  143.     
  144.     return 0;    
  145. }    

        通过上面的源码来分析下这个程序的执行过程:


        ①函数参数以及版本的检查:当前updater binary API所支持的版本号有1,2,3这三个。

        ②获取管道并打开:在执行此程序的过程中向该管道写入命令,用于通知其父进程根据命令去更新UI显示。

        ③读取updater-script脚本:从update.zip包中将updater-script脚本读到一块动态内存中,供后面执行。

        ④Configure edify’s functions:注册脚本中的语句处理函数,即识别脚本中命令的函数。主要有以下几类

                   RegisterBuiltins():注册程序中控制流程的语句,如ifelse、assert、abort、stdout等。

                            RegisterInstallFunctions():实际安装过程中安装所需的功能函数,比如mount、format、set_progress、set_perm等等。

                   RegisterDeviceExtensions():与设备相关的额外添加項,在源码中并没有任何实现。


                   FinishRegistration():结束注册。

        ⑤Parsethe script:调用yy*库函数解析脚本,并将解析后的内容存放到一个Expr类型的python类中。主要函数是yy_scan_string()和yyparse()。

        ⑥执行脚本:核心函数是Evaluate(),它会调用其他的callback函数,而这些callback函数又会去调用Evaluate去解析不同的脚本片段,从而实现一个简单的脚本解释器。

        ⑦错误信息提示:最后就是根据Evaluate()执行后的返回值,给出一些打印信息。


            这一执行过程非常简单,最主要的函数就是Evaluate。它负责最终执行解析的脚本命令。而安装过程中的命令就是updater-script。

            下一篇幅将介绍updater-script脚本中的语法以及这个脚本在具体升级中的执行流程。




          目前updater-script脚本格式是edify,其与amend有何区别,暂不讨论,我们只分析其中主要的语法,以及脚本的流程控制。

一、updater-script脚本语法简介:

        我们顺着所生成的脚本来看其中主要涉及的语法。

        1.assert(condition):如果condition参数的计算结果为False,则停止脚本执行,否则继续执行脚本。

        2.show_progress(frac,sec):frac表示进度完成的数值,sec表示整个过程的总秒数。主要用与显示UI上的进度条。

        3.format(fs_type,partition_type,location):fs_type,文件系统类型,取值一般为“yaffs2”或“ext4”。Partition_type,分区类型,一般取值为“MTD”或则“EMMC”。主要用于格式化为指定的文件系统。事例如下:format(”yaffs2”,”MTD”,”system”)。

        4.mount(fs_type,partition_type,location,mount_point):前两个参数同上,location要挂载的设备,mount_point挂载点。作用:挂载一个文件系统到指定的挂载点。

        5.package_extract_dir(src_path,destination_path):src_path,要提取的目录,destination_path目标目录。作用:从升级包内,提取目录到指定的位置。示例:package_extract_dir(“system”,”/system”)。

        6.symlink(target,src1,src2,……,srcN):target,字符串类型,是符号连接的目标。SrcX代表要创建的符号连接的目标点。示例:symlink(“toolbox”,”/system/bin/ps”),建立指向toolbox符号连接/system/bin/ps,值得注意的是,在建立新的符号连接之前,要断开已经存在的符号连接。

        7.set_perm(uid,gid,mode,file1,file2,……,fileN):作用是设置单个文件或则一系列文件的权限,最少要指定一个文件。

        8.set_perm_recursive(uid,gid,mode,dir1,dir2,……,dirN):作用同上,但是这里同时改变的是一个或多个目录及其文件的权限。

        9.package_extract_file(srcfile_path,desfile_paht):srcfile_path,要提取的文件,desfile_path,提取文件的目标位置。示例:package_extract_file(“boot.img”,”/tmp/boot.img”)将升级包中的boot.img文件拷贝到内存文件系统的/tmp下。

      10.write_raw_image(src-image,partition):src-image源镜像文件,partition,目标分区。作用:将镜像写入目标分区。示例:write_raw_image(“/tmp/boot.img”,”boot”)将boot.img镜像写入到系统的boot分区。

      11.getprop(key):通过指定key的值来获取对应的属性信息。示例:getprop(“ro.product.device”)获取ro.product.device的属性值。


二、updater-script脚本执行流程分析:

          先看一下在测试过程中用命令make otapackage生成的升级脚本如下:

[python] view plain copy
 print?
  1. assert(!less_than_int(1331176658, getprop("ro.build.date.utc")));    
  2. assert(getprop("ro.product.device") == "tcc8800" ||    
  3.        getprop("ro.build.product") == "tcc8800");    
  4. show_progress(0.5000000);    
  5. format("yaffs2""MTD""system");    
  6. mount("yaffs2""MTD""system""/system");    
  7. package_extract_dir("recovery""/system");    
  8. package_extract_dir("system""/system");    
  9. symlink("busybox""/system/bin/cp""/system/bin/grep",    
  10.         "/system/bin/tar""/system/bin/unzip",    
  11.         "/system/bin/vi");    
  12. symlink("toolbox""/system/bin/cat""/system/bin/chmod",    
  13.         "/system/bin/chown""/system/bin/cmp""/system/bin/date",    
  14.         "/system/bin/dd""/system/bin/df""/system/bin/dmesg",    
  15.         "/system/bin/getevent""/system/bin/getprop""/system/bin/hd",    
  16.         "/system/bin/id""/system/bin/ifconfig""/system/bin/iftop",    
  17.         "/system/bin/insmod""/system/bin/ioctl""/system/bin/ionice",    
  18.         "/system/bin/kill""/system/bin/ln""/system/bin/log",    
  19.         "/system/bin/ls""/system/bin/lsmod""/system/bin/lsof",    
  20.         "/system/bin/mkdir""/system/bin/mount""/system/bin/mv",    
  21.         "/system/bin/nandread""/system/bin/netstat",    
  22.         "/system/bin/newfs_msdos""/system/bin/notify""/system/bin/printenv",    
  23.         "/system/bin/ps""/system/bin/reboot""/system/bin/renice",    
  24.         "/system/bin/rm""/system/bin/rmdir""/system/bin/rmmod",    
  25.         "/system/bin/route""/system/bin/schedtop""/system/bin/sendevent",    
  26.         "/system/bin/setconsole""/system/bin/setprop""/system/bin/sleep",    
  27.         "/system/bin/smd""/system/bin/start""/system/bin/stop",    
  28.         "/system/bin/sync""/system/bin/top""/system/bin/umount",    
  29.         "/system/bin/uptime""/system/bin/vmstat""/system/bin/watchprops",    
  30.         "/system/bin/wipe");    
  31. set_perm_recursive(0007550644"/system");    
  32. set_perm_recursive(0200007550755"/system/bin");    
  33. set_perm(0300302750"/system/bin/netcfg");    
  34. set_perm(0300402755"/system/bin/ping");    
  35. set_perm(0200006750"/system/bin/run-as");    
  36. set_perm_recursive(1002100207550440"/system/etc/bluetooth");    
  37. set_perm(000755"/system/etc/bluetooth");    
  38. set_perm(100010000640"/system/etc/bluetooth/auto_pairing.conf");    
  39. set_perm(300230020444"/system/etc/bluetooth/blacklist.conf");    
  40. set_perm(100210020440"/system/etc/dbus.conf");    
  41. set_perm(101420000550"/system/etc/dhcpcd/dhcpcd-run-hooks");    
  42. set_perm(020000550"/system/etc/init.goldfish.sh");    
  43. set_perm(000544"/system/etc/install-recovery.sh");    
  44. set_perm_recursive(0007550555"/system/etc/ppp");    
  45. set_perm_recursive(0200007550755"/system/xbin");    
  46. set_perm(0006755"/system/xbin/librank");    
  47. set_perm(0006755"/system/xbin/procmem");    
  48. set_perm(0006755"/system/xbin/procrank");    
  49. set_perm(0006755"/system/xbin/su");    
  50. set_perm(0006755"/system/xbin/tcpdump");    
  51. show_progress(0.2000000);    
  52. show_progress(0.20000010);    
  53. assert(package_extract_file("boot.img""/tmp/boot.img"),    
  54.        write_raw_image("/tmp/boot.img""boot"),    
  55.        delete("/tmp/boot.img"));    
  56. show_progress(0.1000000);    
  57. unmount("/system");    

          下面分析下这个脚本的执行过程:



         ①比较时间戳:如果升级包较旧则终止脚本的执行。

         ②匹配设备信息:如果和当前的设备信息不一致,则停止脚本的执行。

         ③显示进度条:如果以上两步匹配则开始显示升级进度条。

         ④格式化system分区并挂载。

         ⑤提取包中的recovery以及system目录下的内容到系统的/system下。

         为/system/bin/下的命令文件建立符号连接。

         ⑦设置/system/下目录以及文件的属性。

         ⑧将包中的boot.img提取到/tmp/boot.img。

         ⑨将/tmp/boot.img镜像文件写入到boot分区。

         ⑩完成后卸载/system。

         以上就是updater-script脚本中的语法,及其执行的具体过程。通过分析其执行流程,我们可以发现在执行过程中,并未将升级包另外解压到一个地方,而是需要什么提取什么。值得主要的是在提取recovery和system目录中的内容时,一并放在了/system/下。在操作的过程中,并未删除或改变update.zip包中的任何内容。在实际的更新完成后,我们的update.zip包确实还存在于原来的位置。


三、总结


        以上的九篇着重分析了Android系统中Recovery模式中的一种,即我们做好的update.zip包在系统更新时所走过的流程。其核心部分就是Recovery服务的工作原理。其他两种FACTORY RESET、ENCRYPTED FILE SYSTEM ENABLE/DISABLE与OTA INSTALL是相通的。重点是要理解Recovery服务的工作原理。另外详细分析其升级过程,对于我们在实际升级时,可以根据我们的需要做出相应的修改。

         不足之处,请大家不吝指正!
阅读(5250) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~