Android系统中Recovery模式服务的工作原理

原文链接:http://my.oschina.NET/u/572562/blog/63834
如有侵权,请联系我删除

这篇及以后的篇幅将通过分析update.zip包在具体Android系统升级的过程,来理解Android系统中Recovery模式服务的工作原理。我们先从update.zip包的制作开始,然后是Android系统的启动模式分析,Recovery工作原理,如何从我们上层开始选择system update到重启到Recovery服务,以及在Recovery服务中具体怎样处理update.zip包升级的,我们的安装脚本updater-script怎样被解析并执行的等一系列问题。分析过程中所用的Android源码是gingerbread0919(tcc88xx开发板标配的),测试开发板是tcc88xx。这是在工作中总结的文档,当然在网上参考了不少内容,如有雷同纯属巧合吧,在分析过程中也存在很多未解决的问题,也希望大家不吝指教。


一、 update.zip包的目录结构
          |----boot.img
          |----system/
          |----recovery/
                `|----recovery-from-boot.p
                `|----etc/
                        `|----install-recovery.sh
          |---META-INF/
              `|CERT.RSA
              `|CERT.SF
              `|MANIFEST.MF
              `|----com/
                     `|----google/
                             `|----android/
                                    `|----update-binary
                                    `|----updater-script
                             `|----android/
                                    `|----metadata
二、 update.zip包目录结构详解
         以上是我们用命令make otapackage 制作的update.zip包的标准目录结构。
         
1、 boot.img是更新boot分区所需要的文件。这个boot.img主要包括kernel+ramdisk。

         2、system/目录的内容在升级后会放在系统的system分区。主要用来更新系统的一些应用或则应用会用到的一些库等等。可以将Android源码编译out/target/product/tcc8800/system/中的所有文件拷贝到这个目录来代替。

          3、 recovery/目录中的recovery-from-boot.p是boot.img和recovery.img的补丁(patch),主要用来更新recovery分区,其中etc/目录下的install-recovery.sh是更新脚本。
         
4、 update-binary是一个二进制文件,相当于一个脚本解释器,能够识别updater-script中描述的操作。该文件在Android源码编译后out/target/product/tcc8800/system bin/updater生成,可将updater重命名为update-binary得到。
               该文件在具体的更新包中的名字由源码中bootable/recovery/install.c中的宏ASSUMED_UPDATE_BINARY_NAME的值而定。
         
5、 updater-script:此文件是一个脚本文件,具体描述了更新过程。我们可以根据具体情况编写该脚本来适应我们的具体需求。该文件的命名由源码中bootable/recovery/updater/updater.c文件中的宏SCRIPT_NAME的值而定。
         
6、 metadata文件是描述设备信息及环境变量的元数据。主要包括一些编译选项,签名公钥,时间戳以及设备型号等。
         
7、 我们还可以在包中添加userdata目录,来更新系统中的用户数据部分。这部分内容在更新后会存放在系统的/data目录下。

         8、update.zip包的签名:update.zip更新包在制作完成后需要对其签名,否则在升级时会出现认证失败的错误提示。而且签名要使用和目标板一致的加密公钥。加密公钥及加密需要的三个文件在Android源码编译后生成的具体路径为:

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

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

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

              我们用命令make otapackage制作生成的update.zip包是已签过名的,如果自己做update.zip包时必须手动对其签名。

              具体的加密方法:$ java –jar gingerbread/out/host/linux/framework/signapk.jar –w gingerbread/build/target/product/security/testkey.x509.pem                                      gingerbread/build/target/product/security/testkey.pk8 update.zip update_signed.zip
              以上命令在update.zip包所在的路径下执行,其中signapk.jar testkey.x509.pem以及testkey.pk8文件的引用使用绝对路径。update.zip 是我们已经打好的包,update_signed.zip包是命令执行完生成的已经签过名的包。
         
9、 MANIFEST.MF:这个manifest文件定义了与包的组成结构相关的数据。类似Android应用的mainfest.xml文件。
       
10、 CERT.RSA:与签名文件相关联的签名程序块文件,它存储了用于签名JAR文件的公共签名。
       
11、 CERT.SF:这是JAR文件的签名文件,其中前缀CERT代表签名者。
        另外,在具体升级时,对update.zip包检查时大致会分三步:①检验SF文件与RSA文件是否匹配。②检验MANIFEST.MF与签名文件中的digest是否一致。③检验包中的文件与MANIFEST中所描述的是否一致

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

 首先我们要了解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模式中的三个部分

         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

                               <recovery command>\n

                               <recovery command>”

            该文件存储的就是一个字符串,必须以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模式中完成什么样的操作。

一、从System Update到Reboot


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


        在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服务的主要功能有很大帮助。代码如下:

        /*
 * The recovery tool communicates with the main system through /cache files.
 *   /cache/recovery/command - INPUT - command line for tool, one arg per line
 *   /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
 *   /cache/recovery/intent - OUTPUT - intent that was passed in
 *
 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
 *   --just_exit - do nothing; exit and reboot
 *
 * After completing, we remove /cache/recovery/command and reboot.
 * Arguments may also be supplied in the bootloader control block (BCB).
 * These important scenarios must be safely restartable at any point:
 *
 * FACTORY RESET
 * 1. user selects "factory reset"
 * 2. main system writes "--wipe_data" to /cache/recovery/command
 * 3. main system reboots into recovery
 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
 *    -- after this, rebooting will restart the erase --
 * 5. erase_volume() reformats /data
 * 6. erase_volume() reformats /cache
 * 7. finish_recovery() erases BCB
 *    -- after this, rebooting will restart the main system --
 * 8. main() calls reboot() to boot main system
 *
 * OTA INSTALL
 * 1. main system downloads OTA package to /cache/some-filename.zip
 * 2. main system writes "--update_package=/cache/some-filename.zip"
 * 3. main system reboots into recovery
 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
 *    -- after this, rebooting will attempt to reinstall the update --
 * 5. install_package() attempts to install the update
 *    NOTE: the package install must itself be restartable from any point
 * 6. finish_recovery() erases BCB
 *    -- after this, rebooting will (try to) restart the main system --
 * 7. ** if install failed **
 *    7a. prompt_and_wait() shows an error icon and waits for the user
 *    7b; the user reboots (pulling the battery, etc) into the main system
 * 8. main() calls maybe_install_firmware_update()
 *    ** if the update contained radio/hboot firmware **:
 *    8a. m_i_f_u() writes BCB with "boot-recovery" and "--wipe_cache"
 *        -- after this, rebooting will reformat cache & restart main system --
 *    8b. m_i_f_u() writes firmware image into raw cache partition
 *    8c. m_i_f_u() writes BCB with "update-radio/hboot" and "--wipe_cache"
 *        -- after this, rebooting will attempt to reinstall firmware --
 *    8d. bootloader tries to flash firmware
 *    8e. bootloader writes BCB with "boot-recovery" (keeping "--wipe_cache")
 *        -- after this, rebooting will reformat cache & restart main system --
 *    8f. erase_volume() reformats /cache
 *    8g. finish_recovery() erases BCB
 *        -- after this, rebooting will (try to) restart the main system --
 * 9. main() calls reboot() to boot main system
 */

          从注释中我们可以看到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的那个分支。

Android系统Recovery工作原理之使用update.zip升级过程分析(七)---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函数的源码文件,还是把源码先贴出来如下:


/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <sys/stat.h> #include <sys/wait.h> #include <unistd.h> #include "common.h" #include "install.h" #include "mincrypt/rsa.h" #include "minui/minui.h" #include "minzip/SysUtil.h" #include "minzip/Zip.h" #include "mtdutils/mounts.h" #include "mtdutils/mtdutils.h" #include "roots.h" #include "verifier.h" #define ASSUMED_UPDATE_BINARY_NAME "META-INF/com/google/android/update-binary" #define PUBLIC_KEYS_FILE "/res/keys" // If the package contains an update binary, extract it and run it. static int try_update_binary(const char *path, ZipArchive *zip) { const ZipEntry* binary_entry = mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME); if (binary_entry == NULL) { mzCloseZipArchive(zip); return INSTALL_CORRUPT; } char* binary = "/tmp/update_binary"; unlink(binary); int fd = creat(binary, 0755); if (fd < 0) { mzCloseZipArchive(zip); LOGE("Can't make %s\n", binary); return 1; } bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd); close(fd); mzCloseZipArchive(zip); if (!ok) { LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME); return 1; } int pipefd[2]; pipe(pipefd); // When executing the update binary contained in the package, the // arguments passed are: // // - the version number for this interface // // - an fd to which the program can write in order to update the // progress bar. The program can write single-line commands: // // progress <frac> <secs> // fill up the next <frac> part of of the progress bar // over <secs> seconds. If <secs> is zero, use // set_progress commands to manually control the // progress of this segment of the bar // // set_progress <frac> // <frac> should be between 0.0 and 1.0; sets the // progress bar within the segment defined by the most // recent progress command. // // firmware <"hboot"|"radio"> <filename> // arrange to install the contents of <filename> in the // given partition on reboot. // // (API v2: <filename> may start with "PACKAGE:" to // indicate taking a file from the OTA package.) // // (API v3: this command no longer exists.) // // ui_print <string> // display <string> on the screen. // // - the name of the package zip file. // char** args = malloc(sizeof(char*) * 5); args[0] = binary; args[1] = EXPAND(RECOVERY_API_VERSION); // defined in Android.mk args[2] = malloc(10); sprintf(args[2], "%d", pipefd[1]); args[3] = (char*)path; args[4] = NULL; pid_t pid = fork(); if (pid == 0) { close(pipefd[0]); execv(binary, args); fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno)); _exit(-1); } close(pipefd[1]); char buffer[1024]; FILE* from_child = fdopen(pipefd[0], "r"); while (fgets(buffer, sizeof(buffer), from_child) != NULL) { char* command = strtok(buffer, " \n"); if (command == NULL) { continue; } else if (strcmp(command, "progress") == 0) { char* fraction_s = strtok(NULL, " \n"); char* seconds_s = strtok(NULL, " \n"); float fraction = strtof(fraction_s, NULL); int seconds = strtol(seconds_s, NULL, 10); ui_show_progress(fraction * (1-VERIFICATION_PROGRESS_FRACTION), seconds); } else if (strcmp(command, "set_progress") == 0) { char* fraction_s = strtok(NULL, " \n"); float fraction = strtof(fraction_s, NULL); ui_set_progress(fraction); } else if (strcmp(command, "ui_print") == 0) { char* str = strtok(NULL, "\n"); if (str) { ui_print("%s", str); } else { ui_print("\n"); } } else { LOGE("unknown command [%s]\n", command); } } fclose(from_child); int status; waitpid(pid, &status, 0); if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status)); return INSTALL_ERROR; } return INSTALL_SUCCESS; } // Reads a file containing one or more public keys as produced by // DumpPublicKey: this is an RSAPublicKey struct as it would appear // as a C source literal, eg: // // "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}" // // (Note that the braces and commas in this example are actual // characters the parser expects to find in the file; the ellipses // indicate more numbers omitted from this example.) // // The file may contain multiple keys in this format, separated by // commas. The last key must not be followed by a comma. // // Returns NULL if the file failed to parse, or if it contain zero keys. static RSAPublicKey* load_keys(const char* filename, int* numKeys) { RSAPublicKey* out = NULL; *numKeys = 0; FILE* f = fopen(filename, "r"); if (f == NULL) { LOGE("opening %s: %s\n", filename, strerror(errno)); goto exit; } int i; bool done = false; while (!done) { ++*numKeys; out = realloc(out, *numKeys * sizeof(RSAPublicKey)); RSAPublicKey* key = out + (*numKeys - 1); if (fscanf(f, " { %i , 0x%x , { %u", &(key->len), &(key->n0inv), &(key->n[0])) != 3) { goto exit; } if (key->len != RSANUMWORDS) { LOGE("key length (%d) does not match expected size\n", key->len); goto exit; } for (i = 1; i < key->len; ++i) { if (fscanf(f, " , %u", &(key->n[i])) != 1) goto exit; } if (fscanf(f, " } , { %u", &(key->rr[0])) != 1) goto exit; for (i = 1; i < key->len; ++i) { if (fscanf(f, " , %u", &(key->rr[i])) != 1) goto exit; } fscanf(f, " } } "); // if the line ends in a comma, this file has more keys. switch (fgetc(f)) { case ',': // more keys to come. break; case EOF: done = true; break; default: LOGE("unexpected character between keys\n"); goto exit; } } fclose(f); return out; exit: if (f) fclose(f); free(out); *numKeys = 0; return NULL; } int install_package(const char *path) { ui_set_background(BACKGROUND_ICON_INSTALLING); ui_print("Finding update package...\n"); ui_show_indeterminate_progress(); LOGI("Update location: %s\n", path); if (ensure_path_mounted(path) != 0) { LOGE("Can't mount %s\n", path); return INSTALL_CORRUPT; } ui_print("Opening update package...\n"); int numKeys; RSAPublicKey* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys); if (loadedKeys == NULL) { LOGE("Failed to load keys\n"); return INSTALL_CORRUPT; } LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE); // Give verification half the progress bar... ui_print("Verifying update package...\n"); ui_show_progress( VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME); int err; err = verify_file(path, loadedKeys, numKeys); free(loadedKeys); LOGI("verify_file returned %d\n", err); if (err != VERIFY_SUCCESS) { LOGE("signature verification failed\n"); return INSTALL_CORRUPT; } /* Try to open the package. */ ZipArchive zip; err = mzOpenZipArchive(path, &zip); if (err != 0) { LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad"); return INSTALL_CORRUPT; } /* Verify and install the contents of the package. */ ui_print("Installing update...\n"); return try_update_binary(path, &zip); }

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

            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  <frac> <secs>:根据第二个参数secs(秒)来设置进度条。

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

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

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

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

Android系统Recovery工作原理之使用update.zip升级过程分析(八)---升级程序update_binary的执行过程


一、update_binary的执行过程分析

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

/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include "edify/expr.h" #include "updater.h" #include "install.h" #include "minzip/Zip.h" // Generated by the makefile, this function defines the // RegisterDeviceExtensions() function, which calls all the // registration functions for device-specific extensions. #include "register.inc" // Where in the package we expect to find the edify script to execute. // (Note it's "updateR-script", not the older "update-script".) #define SCRIPT_NAME "META-INF/com/google/android/updater-script" int main(int argc, char** argv) { // Various things log information to stdout or stderr more or less // at random. The log file makes more sense if buffering is // turned off so things appear in the right order. setbuf(stdout, NULL); setbuf(stderr, NULL); if (argc != 4) { fprintf(stderr, "unexpected number of arguments (%d)\n", argc); return 1; } char* version = argv[1]; if ((version[0] != '1' && version[0] != '2' && version[0] != '3') || version[1] != '\0') { // We support version 1, 2, or 3. fprintf(stderr, "wrong updater binary API; expected 1, 2, or 3; " "got %s\n", argv[1]); return 2; } // Set up the pipe for sending commands back to the parent process. int fd = atoi(argv[2]); FILE* cmd_pipe = fdopen(fd, "wb"); setlinebuf(cmd_pipe); // Extract the script from the package. char* package_data = argv[3]; ZipArchive za; int err; err = mzOpenZipArchive(package_data, &za); if (err != 0) { fprintf(stderr, "failed to open package %s: %s\n", package_data, strerror(err)); return 3; } const ZipEntry* script_entry = mzFindZipEntry(&za, SCRIPT_NAME); if (script_entry == NULL) { fprintf(stderr, "failed to find %s in %s\n", SCRIPT_NAME, package_data); return 4; } char* script = malloc(script_entry->uncompLen+1); if (!mzReadZipEntry(&za, script_entry, script, script_entry->uncompLen)) { fprintf(stderr, "failed to read script from package\n"); return 5; } script[script_entry->uncompLen] = '\0'; // Configure edify's functions. RegisterBuiltins(); RegisterInstallFunctions(); RegisterDeviceExtensions(); FinishRegistration(); // Parse the script. Expr* root; int error_count = 0; yy_scan_string(script); int error = yyparse(&root, &error_count); if (error != 0 || error_count > 0) { fprintf(stderr, "%d parse errors\n", error_count); return 6; } // Evaluate the parsed script. UpdaterInfo updater_info; updater_info.cmd_pipe = cmd_pipe; updater_info.package_zip = &za; updater_info.version = atoi(version); State state; state.cookie = &updater_info; state.script = script; state.errmsg = NULL; char* result = Evaluate(&state, root); if (result == NULL) { if (state.errmsg == NULL) { fprintf(stderr, "script aborted (no error message)\n"); fprintf(cmd_pipe, "ui_print script aborted (no error message)\n"); } else { fprintf(stderr, "script aborted: %s\n", state.errmsg); char* line = strtok(state.errmsg, "\n"); while (line) { fprintf(cmd_pipe, "ui_print %s\n", line); line = strtok(NULL, "\n"); } fprintf(cmd_pipe, "ui_print\n"); } free(state.errmsg); return 7; } else { fprintf(stderr, "script result was [%s]\n", result); free(result); } if (updater_info.package_zip) { mzCloseZipArchive(updater_info.package_zip); } free(script); return 0; }

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

        函数参数以及版本的检查:当前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。

Android系统Recovery工作原理之使用update.zip升级过程分析(九)---updater-script脚本语法简介以及执行流程



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

一、update-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生成的升级脚本如下:

assert(!less_than_int(1331176658, getprop("ro.build.date.utc"))); assert(getprop("ro.product.device") == "tcc8800" || getprop("ro.build.product") == "tcc8800"); show_progress(0.500000, 0); format("yaffs2", "MTD", "system"); mount("yaffs2", "MTD", "system", "/system"); package_extract_dir("recovery", "/system"); package_extract_dir("system", "/system"); symlink("busybox", "/system/bin/cp", "/system/bin/grep", "/system/bin/tar", "/system/bin/unzip", "/system/bin/vi"); symlink("toolbox", "/system/bin/cat", "/system/bin/chmod", "/system/bin/chown", "/system/bin/cmp", "/system/bin/date", "/system/bin/dd", "/system/bin/df", "/system/bin/dmesg", "/system/bin/getevent", "/system/bin/getprop", "/system/bin/hd", "/system/bin/id", "/system/bin/ifconfig", "/system/bin/iftop", "/system/bin/insmod", "/system/bin/ioctl", "/system/bin/ionice", "/system/bin/kill", "/system/bin/ln", "/system/bin/log", "/system/bin/ls", "/system/bin/lsmod", "/system/bin/lsof", "/system/bin/mkdir", "/system/bin/mount", "/system/bin/mv", "/system/bin/nandread", "/system/bin/netstat", "/system/bin/newfs_msdos", "/system/bin/notify", "/system/bin/printenv", "/system/bin/ps", "/system/bin/reboot", "/system/bin/renice", "/system/bin/rm", "/system/bin/rmdir", "/system/bin/rmmod", "/system/bin/route", "/system/bin/schedtop", "/system/bin/sendevent", "/system/bin/setconsole", "/system/bin/setprop", "/system/bin/sleep", "/system/bin/smd", "/system/bin/start", "/system/bin/stop", "/system/bin/sync", "/system/bin/top", "/system/bin/umount", "/system/bin/uptime", "/system/bin/vmstat", "/system/bin/watchprops", "/system/bin/wipe"); set_perm_recursive(0, 0, 0755, 0644, "/system"); set_perm_recursive(0, 2000, 0755, 0755, "/system/bin"); set_perm(0, 3003, 02750, "/system/bin/netcfg"); set_perm(0, 3004, 02755, "/system/bin/ping"); set_perm(0, 2000, 06750, "/system/bin/run-as"); set_perm_recursive(1002, 1002, 0755, 0440, "/system/etc/bluetooth"); set_perm(0, 0, 0755, "/system/etc/bluetooth"); set_perm(1000, 1000, 0640, "/system/etc/bluetooth/auto_pairing.conf"); set_perm(3002, 3002, 0444, "/system/etc/bluetooth/blacklist.conf"); set_perm(1002, 1002, 0440, "/system/etc/dbus.conf"); set_perm(1014, 2000, 0550, "/system/etc/dhcpcd/dhcpcd-run-hooks"); set_perm(0, 2000, 0550, "/system/etc/init.goldfish.sh"); set_perm(0, 0, 0544, "/system/etc/install-recovery.sh"); set_perm_recursive(0, 0, 0755, 0555, "/system/etc/ppp"); set_perm_recursive(0, 2000, 0755, 0755, "/system/xbin"); set_perm(0, 0, 06755, "/system/xbin/librank"); set_perm(0, 0, 06755, "/system/xbin/procmem"); set_perm(0, 0, 06755, "/system/xbin/procrank"); set_perm(0, 0, 06755, "/system/xbin/su"); set_perm(0, 0, 06755, "/system/xbin/tcpdump"); show_progress(0.200000, 0); show_progress(0.200000, 10); assert(package_extract_file("boot.img", "/tmp/boot.img"), write_raw_image("/tmp/boot.img", "boot"), delete("/tmp/boot.img")); show_progress(0.100000, 0); 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升级包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贴出来如下:

省略

   根据上面的Makefile可以分析这个包的生成过程:

            首先创建一个root_zip根目录,并依次在此目录下创建所需要的如下其他目录

            ①创建RECOVERY目录,并填充该目录的内容,包括kernel的镜像和recovery根文件系统的镜像。此目录最终用于生成recovery.img。

            ②创建并填充BOOT目录。包含kernel和cmdline以及pagesize大小等,该目录最终用来生成boot.img。
            ③向SYSTEM目录填充system image。
            ④向DATA填充data image。
            ⑤用于生成OTA package包所需要的额外的内容。主要包括一些bin命令。
            ⑥创建META目录并向该目录下添加一些文本文件,如apkcerts.txt(描述apk文件用到的认证证书),misc_info.txt(描述Flash内存的块大小以及boot、recovery、system、userdata等分区的大小信息)。
            ⑦使用保留连接选项压缩我们在上面获得的root_zip目录。
            ⑧使用fs_config(build/tools/fs_config)配置上面的zip包内所有的系统文件(system/下各目录、文件)的权限属主等信息。fs_config包含了一个头文件#include“private/android_filesystem_config.h”。在这个头文件中以硬编码的方式设定了system目录下各文件的权限、属主。执行完配置后会将配置后的信息以文本方式输出 到META/filesystem_config.txt中。并再一次zip压缩成我们最终需要的原始包。

             第二步:上面的zip包只是一个编译过程中生成的原始包。这个原始zip包在实际的编译过程中有两个作用,一是用来生成OTA update升级包,二是用来生成系统镜像。在编译过程中若生成OTA update升级包时会调用(具体位置在Makefile的1037行到1058行)一个名为ota_from_target_files的python脚本,位置在/build/tools/releasetools/ota_from_target_files。这个脚本的作用是以第一步生成的zip原始包作为输入,最终生成可用的OTA升级zip包。

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

                  省略

                        下面简单翻译一下他们的使用方法以及选项的作用。

                        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包的。先讲这个脚本的代码贴出来如下:

省略

             主函数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)有关。


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值