Android OTA update package creation script (2. Decompress), androidota

Source: Internet
Author: User

Android OTA update package creation script (2. Decompress), androidota

Step 1: extract (ota_from_target_files)

  print "unzipping target target-files..."  OPTIONS.input_tmp, input_zip = common.UnzipTemp(args[0])
The above code is the portal to start decompression.
Def UnzipTemp (filename, pattern = None): "Unzip the given archive into a temporary directory and return the name. if filename is of the form "foo.zipw.bar.zip", unzip foo.zip into a temp dir, then unzip bar.zip into that_dir/BOOTABLE_IMAGES. returns (tempdir, zipobj) where zipobj is a zipfile. zipFile (of the main file), open for reading. "# This function is used to create a temporary folder. The parameter indicates the prefix of the Temporary Folder. The returned value tmp is the absolute path of the Temporary Folder and is assigned to OPTION S's tempfiles attribute tmp = tempfile. mkdtemp (prefix = "targetfiles-") OPTIONS. tempfiles. append (tmp) def unzip_to_dir (filename, dirname): # Set an array of variable name cmd, which stores the commands and parameters to be executed, this command is called "unzip-o-q filename-d dirname" cmd = ["unzip", "-o", "-q", filename, "-d ", dirname] if pattern is not None: cmd. append (pattern) # Run Method p = Run (cmd, stdout = subprocess is called here. PIPE) "" Popen. communicate (input = None) Interacts with sub-processes. Send data to stdin or read data from stdout and stderr. Optional parameter input specifies the parameter sent to the sub-process. Communicate () returns a tuples (stdoutdata, stderrdata ). Note: If you want to send data to the process through stdin, The stdin parameter must be set to PIPE when you create a Popen object. Similarly, if you want to obtain data from stdout and stderr, you must set stdout and stderr to PIPE. "P. communicate () if p. returncode! = 0: raise ExternalError ("failed to unzip input target-files \" % s \ "" % (filename,) # match: matches the regular expression only from the start of the string, if the matching is successful, the matched items are returned; otherwise, none; m = re. match (r "^ (. * [.] zip) \ + (. * [.] zip) $ ", filename, re. IGNORECASE) # if you add and execute the "print m" Statement, the result is "Export target.zip]" if m: unzip_to_dir (m. group (1), tmp) unzip_to_dir (m. group (2), OS. path. join (tmp, "BOOTABLE_IMAGES") filename = m. group (1) else: # Here the decompression operation is executed, the file name value is "target.zip", the tem value is "/tmp/targetfiles-fEX9aH ", and call the upzip_to_dir method to execute the unzip_to_dir (filename, tmp) command. # Return the temporary path and the variable that stores zipfile content. # The second parameter here uses r to read the zip file, w is to create a zip file return tmp, zipfile. zipFile (filename, "r ")
# Start a new process to execute the decompression command.
Def Run (args, ** kwargs): "" Create and return a subprocess. popen object, printing the command line on the terminal if-v was specified. "if OPTIONS. verbose: print "running :","". join (args) "Here we call the Popen module to start a new process to execute system commands. In this way, we can use process control to copy the returned results to the variables, it is easier to process. The args value is actually a list used to specify the executable file and its parameters of the process. "" Return subprocess. Popen (args, ** kwargs)
Return to the main function to process the results returned by decompression.

  OPTIONS.target_tmp = OPTIONS.input_tmp  OPTIONS.info_dict = common.LoadInfoDict(input_zip)
Step 2: complete the information in META/misc_info.txt=imagesizes.txt in target.zip, for example:


The content in misc_info.txt is as follows:

recovery_api_version=3fstab_version=2tool_extensions=out/target/product/wt98360/obj/CUSTGEN/config/../commondefault_system_dev_certificate=build/target/product/security/testkeymkbootimg_args=use_set_metadata=1update_rename_support=1fs_type=ext4system_size=1363148800userdata_size=1152385024cache_size=132120576extfs_sparse_flag=-smkyaffs2_extra_flags=-c 2048 -s 64   selinux_fc=out/target/product/wt98360/root/file_contexts

The Code is as follows:

Def LoadInfoDict (zip): "" Read and parse the META/misc_info.txt key/value pairs from the input target files and return a dict. "" # define a dictionary variable to store the processed information d ={} try: unzip here zip.read(unzip ← open META/misc_info.txt in update.zip, and slice for line in zip according to "\ n. read ("META/misc_info.txt "). split ("\ n"): line = line. strip () # Remove the specified character (space by default) if not line or line. startswith ("#"): continue # Skip annotation information k, v = line. split ("=", 1) # Here we use the first "=" to slice d [k] = v # encapsulate it into a data dictionary partition t KeyError: # OK if misc_info.txt doesn't exist pass # backwards compatibility: These values used to be in their own # files. look for them, in case we're re processing an old # target_files zip. if "mkyaffs2_extra_flags" not in d: try: d ["mkyaffs2_extra_flags"] = zip. read ("META/mkyaffs2-extra-flags.txt "). strip () doesn t KeyError: # OK if flags don't exist pass if "recovery_api_version" not in d: try: d ["recovery_api_version"] = zip. read ("META/recovery-api-version.txt "). strip () failed t KeyError: raise ValueError ("can't find resions API version in input target-files") if "tool_extensions" not in d: try: d ["tool_extensions"] = zip. read ("META/tool-extensions.txt "). strip () doesn t KeyError: # OK if extensions don't exist pass if "fstab_version" not in d: d ["fstab_version"] = "1" try: data = zip. read ("META/imagesizes.txt") for line in data. split ("\ n"): if not line: continue name, value = line. split ("", 1) if not value: continue if name = "blocksize": d [name] = value else: d [name + "_ size"] = value into T KeyError: pass def makeint (key): if key in d: if d [key]. endswith ('M'): d [key] = d [key]. split ("M") [0] d [key] = int (d [key], 0) * 1024*1024 else: d [key] = int (d [key], 0) makeint ("recovery_api_version") makeint ("blocksize") makeint ("system_size") makeint ("userdata_size ") makeint ("cache_size") makeint ("recovery_size") makeint ("boot_size") makeint ("fstab_version") # wschen 2012-11-07 makeint ("custom_size ") d ["fstab"] = LoadRecoveryFSTab (zip, d ["fstab_version"]) d ["build. prop "] = LoadBuildProp (zip) return d

In the code above, the partition table and Build attributes are parsed at the end of the method, so the specific operation process is analyzed in detail below.

Step 3: parse the recovery partition information
Fastab_version is 2, so

Def LoadRecoveryFSTab (zip, fstab_version ):
Class Partition (object ):
Pass
Try:
Data = zip. read ("RECOVERY/RAMDISK/etc/recovery. fstab" does not contain this file in target.zip. Therefore, we will not provide details here.
Failed t KeyError:
Print "Warning: cocould not find RECOVERY/RAMDISK/etc/recovery. fstab in % s." % zip
Data = ""
If fstab_version = 1:
D = {}
For line in data. split ("\ n "):
Line = line. strip ()
If not line or line. startswith ("#"): continue
Pieces = line. split ()
If not (3 <= len (pieces) <= 4 ):
Raise ValueError ("malformed recovery. fstab line: \" % s \ "" % (line ,))
P = Partition ()
P. mount_point = pieces [0]
P. fs_type = pieces [1]
P. device = pieces [2]
P. length = 0
Options = None
If len (pieces)> = 4:
If pieces [3]. startswith ("/"):
P. device2 = pieces [3]
If len (pieces)> = 5:
Options = pieces [4]
Else:
P. device2 = None
Options = pieces [3]
Else:
P. device2 = None
If options:
Options = options. split (",")
For I in options:
If I. startswith ("length = "):
P. length = int (I [7:])
Else:
Print "% s: unknown option \" % s \ "" % (p. mount_point, I)
D [p. mount_point] = p

Elif fstab_version = 2:
D = {}
For line in data. split ("\ n "):
Line = line. strip ()
If not line or line. startswith ("#"): continue
Pieces = line. split ()
If len (pieces )! = 5:
Raise ValueError ("malformed recovery. fstab line: \" % s \ "" % (line ,))
# Ignore entries that are managed by vold
Options = pieces [4]
If "voldmanaged =" in options: continue
# It's a good line, parse it
P = Partition ()
P. device = pieces [0]
P. mount_point = pieces [1]
P. fs_type = pieces [2]
P. device2 = None
P. length = 0
Options = options. split (",")
For I in options:
If I. startswith ("length = "):
P. length = int (I [7:])
Else:
# Ignore all unknown options in the unified fstab
Continue
D [p. mount_point] = p
Else:
Raise ValueError ("Unknown fstab_version: \" % d \ "" % (fstab_version ,))
Return d
Step 4: parse the SYSTEM/build. prop attribute information, save the parsed attribute information as a data dictionary, and return

def LoadBuildProp(zip):  try:    data = zip.read("SYSTEM/build.prop")  except KeyError:    print "Warning: could not find SYSTEM/build.prop in %s" % zip    data = ""  d = {}  for line in data.split("\n"):    line = line.strip()    if not line or line.startswith("#"): continue    name, value = line.split("=", 1)    d[name] = value  return d


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.