| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1 | # Copyright (C) 2008 The Android Open Source Project |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 15 | import copy |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 16 | import errno |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 17 | import getopt |
| 18 | import getpass |
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 19 | import imp |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 20 | import os |
| Ying Wang | 7e6d4e4 | 2010-12-13 16:25:36 -0800 | [diff] [blame] | 21 | import platform |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 22 | import re |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 23 | import shlex |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 24 | import shutil |
| 25 | import subprocess |
| 26 | import sys |
| 27 | import tempfile |
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 28 | import threading |
| 29 | import time |
| Doug Zongker | 048e7ca | 2009-06-15 14:31:53 -0700 | [diff] [blame] | 30 | import zipfile |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 31 | |
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 32 | import blockimgdiff |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 33 | import rangelib |
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 34 | |
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 35 | from hashlib import sha1 as sha1 |
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 36 | |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 37 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 38 | class Options(object): |
| 39 | def __init__(self): |
| 40 | platform_search_path = { |
| 41 | "linux2": "out/host/linux-x86", |
| 42 | "darwin": "out/host/darwin-x86", |
| Doug Zongker | 8544877 | 2014-09-09 14:59:20 -0700 | [diff] [blame] | 43 | } |
| Doug Zongker | 8544877 | 2014-09-09 14:59:20 -0700 | [diff] [blame] | 44 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 45 | self.search_path = platform_search_path.get(sys.platform, None) |
| 46 | self.signapk_path = "framework/signapk.jar" # Relative to search_path |
| 47 | self.extra_signapk_args = [] |
| 48 | self.java_path = "java" # Use the one on the path by default. |
| 49 | self.java_args = "-Xmx2048m" # JVM Args |
| 50 | self.public_key_suffix = ".x509.pem" |
| 51 | self.private_key_suffix = ".pk8" |
| Dan Albert | cd9ecc0 | 2015-03-27 16:37:23 -0700 | [diff] [blame] | 52 | # use otatools built boot_signer by default |
| 53 | self.boot_signer_path = "boot_signer" |
| Baligh Uddin | 601ddea | 2015-06-09 15:48:14 -0700 | [diff] [blame] | 54 | self.boot_signer_args = [] |
| 55 | self.verity_signer_path = None |
| 56 | self.verity_signer_args = [] |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 57 | self.verbose = False |
| 58 | self.tempfiles = [] |
| 59 | self.device_specific = None |
| 60 | self.extras = {} |
| 61 | self.info_dict = None |
| 62 | self.worker_threads = None |
| Tao Bao | 575d68a | 2015-08-07 19:49:45 -0700 | [diff] [blame] | 63 | # Stash size cannot exceed cache_size * threshold. |
| 64 | self.cache_size = None |
| 65 | self.stash_threshold = 0.8 |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 66 | |
| 67 | |
| 68 | OPTIONS = Options() |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 69 | |
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 70 | |
| 71 | # Values for "certificate" in apkcerts that mean special things. |
| 72 | SPECIAL_CERT_STRINGS = ("PRESIGNED", "EXTERNAL") |
| 73 | |
| 74 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 75 | class ExternalError(RuntimeError): |
| 76 | pass |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 77 | |
| 78 | |
| 79 | def Run(args, **kwargs): |
| 80 | """Create and return a subprocess.Popen object, printing the command |
| 81 | line on the terminal if -v was specified.""" |
| 82 | if OPTIONS.verbose: |
| 83 | print " running: ", " ".join(args) |
| 84 | return subprocess.Popen(args, **kwargs) |
| 85 | |
| 86 | |
| Ying Wang | 7e6d4e4 | 2010-12-13 16:25:36 -0800 | [diff] [blame] | 87 | def CloseInheritedPipes(): |
| 88 | """ Gmake in MAC OS has file descriptor (PIPE) leak. We close those fds |
| 89 | before doing other work.""" |
| 90 | if platform.system() != "Darwin": |
| 91 | return |
| 92 | for d in range(3, 1025): |
| 93 | try: |
| 94 | stat = os.fstat(d) |
| 95 | if stat is not None: |
| 96 | pipebit = stat[0] & 0x1000 |
| 97 | if pipebit != 0: |
| 98 | os.close(d) |
| 99 | except OSError: |
| 100 | pass |
| 101 | |
| 102 | |
| Tao Bao | 2c15d9e | 2015-07-09 11:51:16 -0700 | [diff] [blame] | 103 | def LoadInfoDict(input_file, input_dir=None): |
| Doug Zongker | c19a8d5 | 2010-07-01 15:30:11 -0700 | [diff] [blame] | 104 | """Read and parse the META/misc_info.txt key/value pairs from the |
| 105 | input target files and return a dict.""" |
| 106 | |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 107 | def read_helper(fn): |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 108 | if isinstance(input_file, zipfile.ZipFile): |
| 109 | return input_file.read(fn) |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 110 | else: |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 111 | path = os.path.join(input_file, *fn.split("/")) |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 112 | try: |
| 113 | with open(path) as f: |
| 114 | return f.read() |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 115 | except IOError as e: |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 116 | if e.errno == errno.ENOENT: |
| 117 | raise KeyError(fn) |
| Doug Zongker | c19a8d5 | 2010-07-01 15:30:11 -0700 | [diff] [blame] | 118 | d = {} |
| 119 | try: |
| Michael Runge | 6e83611 | 2014-04-15 17:40:21 -0700 | [diff] [blame] | 120 | d = LoadDictionaryFromLines(read_helper("META/misc_info.txt").split("\n")) |
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 121 | except KeyError: |
| 122 | # ok if misc_info.txt doesn't exist |
| 123 | pass |
| Doug Zongker | c19a8d5 | 2010-07-01 15:30:11 -0700 | [diff] [blame] | 124 | |
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 125 | # backwards compatibility: These values used to be in their own |
| 126 | # files. Look for them, in case we're processing an old |
| 127 | # target_files zip. |
| 128 | |
| 129 | if "mkyaffs2_extra_flags" not in d: |
| 130 | try: |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 131 | d["mkyaffs2_extra_flags"] = read_helper( |
| 132 | "META/mkyaffs2-extra-flags.txt").strip() |
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 133 | except KeyError: |
| 134 | # ok if flags don't exist |
| 135 | pass |
| 136 | |
| 137 | if "recovery_api_version" not in d: |
| 138 | try: |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 139 | d["recovery_api_version"] = read_helper( |
| 140 | "META/recovery-api-version.txt").strip() |
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 141 | except KeyError: |
| 142 | raise ValueError("can't find recovery API version in input target-files") |
| 143 | |
| 144 | if "tool_extensions" not in d: |
| 145 | try: |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 146 | d["tool_extensions"] = read_helper("META/tool-extensions.txt").strip() |
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 147 | except KeyError: |
| 148 | # ok if extensions don't exist |
| 149 | pass |
| 150 | |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 151 | if "fstab_version" not in d: |
| 152 | d["fstab_version"] = "1" |
| 153 | |
| Tao Bao | 84e7568 | 2015-07-19 02:38:53 -0700 | [diff] [blame] | 154 | # A few properties are stored as links to the files in the out/ directory. |
| 155 | # It works fine with the build system. However, they are no longer available |
| 156 | # when (re)generating from target_files zip. If input_dir is not None, we |
| 157 | # are doing repacking. Redirect those properties to the actual files in the |
| 158 | # unzipped directory. |
| Tao Bao | 2c15d9e | 2015-07-09 11:51:16 -0700 | [diff] [blame] | 159 | if input_dir is not None: |
| Tao Bao | 84e7568 | 2015-07-19 02:38:53 -0700 | [diff] [blame] | 160 | # We carry a copy of file_contexts under META/. If not available, search |
| 161 | # BOOT/RAMDISK/. Note that sometimes we may need a different file_contexts |
| 162 | # to build images than the one running on device, such as when enabling |
| 163 | # system_root_image. In that case, we must have the one for image |
| 164 | # generation copied to META/. |
| Tao Bao | 2c15d9e | 2015-07-09 11:51:16 -0700 | [diff] [blame] | 165 | fc_config = os.path.join(input_dir, "META", "file_contexts") |
| Tao Bao | 84e7568 | 2015-07-19 02:38:53 -0700 | [diff] [blame] | 166 | if d.get("system_root_image") == "true": |
| 167 | assert os.path.exists(fc_config) |
| Tao Bao | 2c15d9e | 2015-07-09 11:51:16 -0700 | [diff] [blame] | 168 | if not os.path.exists(fc_config): |
| 169 | fc_config = os.path.join(input_dir, "BOOT", "RAMDISK", "file_contexts") |
| 170 | if not os.path.exists(fc_config): |
| 171 | fc_config = None |
| 172 | |
| 173 | if fc_config: |
| 174 | d["selinux_fc"] = fc_config |
| 175 | |
| Tao Bao | 84e7568 | 2015-07-19 02:38:53 -0700 | [diff] [blame] | 176 | # Similarly we need to redirect "ramdisk_dir" and "ramdisk_fs_config". |
| 177 | if d.get("system_root_image") == "true": |
| 178 | d["ramdisk_dir"] = os.path.join(input_dir, "ROOT") |
| 179 | d["ramdisk_fs_config"] = os.path.join( |
| 180 | input_dir, "META", "root_filesystem_config.txt") |
| 181 | |
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 182 | try: |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 183 | data = read_helper("META/imagesizes.txt") |
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 184 | for line in data.split("\n"): |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 185 | if not line: |
| 186 | continue |
| Doug Zongker | 1684d9c | 2010-09-17 07:44:38 -0700 | [diff] [blame] | 187 | name, value = line.split(" ", 1) |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 188 | if not value: |
| 189 | continue |
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 190 | if name == "blocksize": |
| 191 | d[name] = value |
| 192 | else: |
| 193 | d[name + "_size"] = value |
| 194 | except KeyError: |
| 195 | pass |
| 196 | |
| 197 | def makeint(key): |
| 198 | if key in d: |
| 199 | d[key] = int(d[key], 0) |
| 200 | |
| 201 | makeint("recovery_api_version") |
| 202 | makeint("blocksize") |
| 203 | makeint("system_size") |
| Daniel Rosenberg | f4eabc3 | 2014-07-10 15:42:38 -0700 | [diff] [blame] | 204 | makeint("vendor_size") |
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 205 | makeint("userdata_size") |
| Ying Wang | 9f8e8db | 2011-11-04 11:37:01 -0700 | [diff] [blame] | 206 | makeint("cache_size") |
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 207 | makeint("recovery_size") |
| 208 | makeint("boot_size") |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 209 | makeint("fstab_version") |
| Doug Zongker | c19a8d5 | 2010-07-01 15:30:11 -0700 | [diff] [blame] | 210 | |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 211 | d["fstab"] = LoadRecoveryFSTab(read_helper, d["fstab_version"], |
| 212 | d.get("system_root_image", False)) |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 213 | d["build.prop"] = LoadBuildProp(read_helper) |
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 214 | return d |
| 215 | |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 216 | def LoadBuildProp(read_helper): |
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 217 | try: |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 218 | data = read_helper("SYSTEM/build.prop") |
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 219 | except KeyError: |
| 220 | print "Warning: could not find SYSTEM/build.prop in %s" % zip |
| 221 | data = "" |
| Michael Runge | 6e83611 | 2014-04-15 17:40:21 -0700 | [diff] [blame] | 222 | return LoadDictionaryFromLines(data.split("\n")) |
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 223 | |
| Michael Runge | 6e83611 | 2014-04-15 17:40:21 -0700 | [diff] [blame] | 224 | def LoadDictionaryFromLines(lines): |
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 225 | d = {} |
| Michael Runge | 6e83611 | 2014-04-15 17:40:21 -0700 | [diff] [blame] | 226 | for line in lines: |
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 227 | line = line.strip() |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 228 | if not line or line.startswith("#"): |
| 229 | continue |
| Ying Wang | 114b46f | 2014-04-15 11:24:00 -0700 | [diff] [blame] | 230 | if "=" in line: |
| 231 | name, value = line.split("=", 1) |
| 232 | d[name] = value |
| Doug Zongker | c19a8d5 | 2010-07-01 15:30:11 -0700 | [diff] [blame] | 233 | return d |
| 234 | |
| Daniel Rosenberg | e6853b0 | 2015-06-05 17:59:27 -0700 | [diff] [blame] | 235 | def LoadRecoveryFSTab(read_helper, fstab_version, system_root_image=False): |
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 236 | class Partition(object): |
| Tao Bao | 548eb76 | 2015-06-10 12:32:41 -0700 | [diff] [blame] | 237 | def __init__(self, mount_point, fs_type, device, length, device2, context): |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 238 | self.mount_point = mount_point |
| 239 | self.fs_type = fs_type |
| 240 | self.device = device |
| 241 | self.length = length |
| 242 | self.device2 = device2 |
| Tao Bao | 548eb76 | 2015-06-10 12:32:41 -0700 | [diff] [blame] | 243 | self.context = context |
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 244 | |
| 245 | try: |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 246 | data = read_helper("RECOVERY/RAMDISK/etc/recovery.fstab") |
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 247 | except KeyError: |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 248 | print "Warning: could not find RECOVERY/RAMDISK/etc/recovery.fstab" |
| Jeff Davidson | 033fbe2 | 2011-10-26 18:08:09 -0700 | [diff] [blame] | 249 | data = "" |
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 250 | |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 251 | if fstab_version == 1: |
| 252 | d = {} |
| 253 | for line in data.split("\n"): |
| 254 | line = line.strip() |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 255 | if not line or line.startswith("#"): |
| 256 | continue |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 257 | pieces = line.split() |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 258 | if not 3 <= len(pieces) <= 4: |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 259 | raise ValueError("malformed recovery.fstab line: \"%s\"" % (line,)) |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 260 | options = None |
| 261 | if len(pieces) >= 4: |
| 262 | if pieces[3].startswith("/"): |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 263 | device2 = pieces[3] |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 264 | if len(pieces) >= 5: |
| 265 | options = pieces[4] |
| 266 | else: |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 267 | device2 = None |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 268 | options = pieces[3] |
| Doug Zongker | 086cbb0 | 2011-02-17 15:54:20 -0800 | [diff] [blame] | 269 | else: |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 270 | device2 = None |
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 271 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 272 | mount_point = pieces[0] |
| 273 | length = 0 |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 274 | if options: |
| 275 | options = options.split(",") |
| 276 | for i in options: |
| 277 | if i.startswith("length="): |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 278 | length = int(i[7:]) |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 279 | else: |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 280 | print "%s: unknown option \"%s\"" % (mount_point, i) |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 281 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 282 | d[mount_point] = Partition(mount_point=mount_point, fs_type=pieces[1], |
| 283 | device=pieces[2], length=length, |
| 284 | device2=device2) |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 285 | |
| 286 | elif fstab_version == 2: |
| 287 | d = {} |
| 288 | for line in data.split("\n"): |
| 289 | line = line.strip() |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 290 | if not line or line.startswith("#"): |
| 291 | continue |
| Tao Bao | 548eb76 | 2015-06-10 12:32:41 -0700 | [diff] [blame] | 292 | # <src> <mnt_point> <type> <mnt_flags and options> <fs_mgr_flags> |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 293 | pieces = line.split() |
| 294 | if len(pieces) != 5: |
| 295 | raise ValueError("malformed recovery.fstab line: \"%s\"" % (line,)) |
| 296 | |
| 297 | # Ignore entries that are managed by vold |
| 298 | options = pieces[4] |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 299 | if "voldmanaged=" in options: |
| 300 | continue |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 301 | |
| 302 | # It's a good line, parse it |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 303 | length = 0 |
| Doug Zongker | 086cbb0 | 2011-02-17 15:54:20 -0800 | [diff] [blame] | 304 | options = options.split(",") |
| 305 | for i in options: |
| 306 | if i.startswith("length="): |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 307 | length = int(i[7:]) |
| Doug Zongker | 086cbb0 | 2011-02-17 15:54:20 -0800 | [diff] [blame] | 308 | else: |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 309 | # Ignore all unknown options in the unified fstab |
| 310 | continue |
| Doug Zongker | 086cbb0 | 2011-02-17 15:54:20 -0800 | [diff] [blame] | 311 | |
| Tao Bao | 548eb76 | 2015-06-10 12:32:41 -0700 | [diff] [blame] | 312 | mount_flags = pieces[3] |
| 313 | # Honor the SELinux context if present. |
| 314 | context = None |
| 315 | for i in mount_flags.split(","): |
| 316 | if i.startswith("context="): |
| 317 | context = i |
| 318 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 319 | mount_point = pieces[1] |
| 320 | d[mount_point] = Partition(mount_point=mount_point, fs_type=pieces[2], |
| Tao Bao | 548eb76 | 2015-06-10 12:32:41 -0700 | [diff] [blame] | 321 | device=pieces[0], length=length, |
| 322 | device2=None, context=context) |
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 323 | |
| 324 | else: |
| 325 | raise ValueError("Unknown fstab_version: \"%d\"" % (fstab_version,)) |
| 326 | |
| Daniel Rosenberg | e6853b0 | 2015-06-05 17:59:27 -0700 | [diff] [blame] | 327 | # / is used for the system mount point when the root directory is included in |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 328 | # system. Other areas assume system is always at "/system" so point /system |
| 329 | # at /. |
| Daniel Rosenberg | e6853b0 | 2015-06-05 17:59:27 -0700 | [diff] [blame] | 330 | if system_root_image: |
| 331 | assert not d.has_key("/system") and d.has_key("/") |
| 332 | d["/system"] = d["/"] |
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 333 | return d |
| 334 | |
| 335 | |
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 336 | def DumpInfoDict(d): |
| 337 | for k, v in sorted(d.items()): |
| 338 | print "%-25s = (%s) %s" % (k, type(v).__name__, v) |
| Doug Zongker | c19a8d5 | 2010-07-01 15:30:11 -0700 | [diff] [blame] | 339 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 340 | |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 341 | def _BuildBootableImage(sourcedir, fs_config_file, info_dict=None, |
| 342 | has_ramdisk=False): |
| 343 | """Build a bootable image from the specified sourcedir. |
| Doug Zongker | e1c31ba | 2009-06-23 17:40:35 -0700 | [diff] [blame] | 344 | |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 345 | Take a kernel, cmdline, and optionally a ramdisk directory from the input (in |
| 346 | 'sourcedir'), and turn them into a boot image. Return the image data, or |
| 347 | None if sourcedir does not appear to contains files for building the |
| 348 | requested image.""" |
| 349 | |
| 350 | def make_ramdisk(): |
| 351 | ramdisk_img = tempfile.NamedTemporaryFile() |
| 352 | |
| 353 | if os.access(fs_config_file, os.F_OK): |
| 354 | cmd = ["mkbootfs", "-f", fs_config_file, |
| 355 | os.path.join(sourcedir, "RAMDISK")] |
| 356 | else: |
| 357 | cmd = ["mkbootfs", os.path.join(sourcedir, "RAMDISK")] |
| 358 | p1 = Run(cmd, stdout=subprocess.PIPE) |
| 359 | p2 = Run(["minigzip"], stdin=p1.stdout, stdout=ramdisk_img.file.fileno()) |
| 360 | |
| 361 | p2.wait() |
| 362 | p1.wait() |
| 363 | assert p1.returncode == 0, "mkbootfs of %s ramdisk failed" % (sourcedir,) |
| 364 | assert p2.returncode == 0, "minigzip of %s ramdisk failed" % (sourcedir,) |
| 365 | |
| 366 | return ramdisk_img |
| 367 | |
| 368 | if not os.access(os.path.join(sourcedir, "kernel"), os.F_OK): |
| 369 | return None |
| 370 | |
| 371 | if has_ramdisk and not os.access(os.path.join(sourcedir, "RAMDISK"), os.F_OK): |
| Doug Zongker | e1c31ba | 2009-06-23 17:40:35 -0700 | [diff] [blame] | 372 | return None |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 373 | |
| Doug Zongker | d513160 | 2012-08-02 14:46:42 -0700 | [diff] [blame] | 374 | if info_dict is None: |
| 375 | info_dict = OPTIONS.info_dict |
| 376 | |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 377 | img = tempfile.NamedTemporaryFile() |
| 378 | |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 379 | if has_ramdisk: |
| 380 | ramdisk_img = make_ramdisk() |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 381 | |
| Bjorn Andersson | 612e2cd | 2012-11-25 16:53:44 -0800 | [diff] [blame] | 382 | # use MKBOOTIMG from environ, or "mkbootimg" if empty or not set |
| 383 | mkbootimg = os.getenv('MKBOOTIMG') or "mkbootimg" |
| 384 | |
| 385 | cmd = [mkbootimg, "--kernel", os.path.join(sourcedir, "kernel")] |
| Doug Zongker | 38a649f | 2009-06-17 09:07:09 -0700 | [diff] [blame] | 386 | |
| Benoit Fradin | a45a868 | 2014-07-14 21:00:43 +0200 | [diff] [blame] | 387 | fn = os.path.join(sourcedir, "second") |
| 388 | if os.access(fn, os.F_OK): |
| 389 | cmd.append("--second") |
| 390 | cmd.append(fn) |
| 391 | |
| Doug Zongker | 171f1cd | 2009-06-15 22:36:37 -0700 | [diff] [blame] | 392 | fn = os.path.join(sourcedir, "cmdline") |
| 393 | if os.access(fn, os.F_OK): |
| Doug Zongker | 38a649f | 2009-06-17 09:07:09 -0700 | [diff] [blame] | 394 | cmd.append("--cmdline") |
| 395 | cmd.append(open(fn).read().rstrip("\n")) |
| 396 | |
| 397 | fn = os.path.join(sourcedir, "base") |
| 398 | if os.access(fn, os.F_OK): |
| 399 | cmd.append("--base") |
| 400 | cmd.append(open(fn).read().rstrip("\n")) |
| 401 | |
| Ying Wang | 4de6b5b | 2010-08-25 14:29:34 -0700 | [diff] [blame] | 402 | fn = os.path.join(sourcedir, "pagesize") |
| 403 | if os.access(fn, os.F_OK): |
| 404 | cmd.append("--pagesize") |
| 405 | cmd.append(open(fn).read().rstrip("\n")) |
| 406 | |
| Doug Zongker | d513160 | 2012-08-02 14:46:42 -0700 | [diff] [blame] | 407 | args = info_dict.get("mkbootimg_args", None) |
| 408 | if args and args.strip(): |
| Jianxun Zhang | 0984949 | 2013-04-17 15:19:19 -0700 | [diff] [blame] | 409 | cmd.extend(shlex.split(args)) |
| Doug Zongker | d513160 | 2012-08-02 14:46:42 -0700 | [diff] [blame] | 410 | |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 411 | if has_ramdisk: |
| 412 | cmd.extend(["--ramdisk", ramdisk_img.name]) |
| 413 | |
| Tao Bao | d95e9fd | 2015-03-29 23:07:41 -0700 | [diff] [blame] | 414 | img_unsigned = None |
| 415 | if info_dict.get("vboot", None): |
| 416 | img_unsigned = tempfile.NamedTemporaryFile() |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 417 | cmd.extend(["--output", img_unsigned.name]) |
| Tao Bao | d95e9fd | 2015-03-29 23:07:41 -0700 | [diff] [blame] | 418 | else: |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 419 | cmd.extend(["--output", img.name]) |
| Doug Zongker | 38a649f | 2009-06-17 09:07:09 -0700 | [diff] [blame] | 420 | |
| 421 | p = Run(cmd, stdout=subprocess.PIPE) |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 422 | p.communicate() |
| Doug Zongker | e1c31ba | 2009-06-23 17:40:35 -0700 | [diff] [blame] | 423 | assert p.returncode == 0, "mkbootimg of %s image failed" % ( |
| 424 | os.path.basename(sourcedir),) |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 425 | |
| Sami Tolvanen | 8b3f08b | 2015-04-07 15:08:59 +0100 | [diff] [blame] | 426 | if (info_dict.get("boot_signer", None) == "true" and |
| 427 | info_dict.get("verity_key", None)): |
| Geremy Condra | 95ebe7a | 2014-08-19 17:27:56 -0700 | [diff] [blame] | 428 | path = "/" + os.path.basename(sourcedir).lower() |
| Baligh Uddin | 601ddea | 2015-06-09 15:48:14 -0700 | [diff] [blame] | 429 | cmd = [OPTIONS.boot_signer_path] |
| 430 | cmd.extend(OPTIONS.boot_signer_args) |
| 431 | cmd.extend([path, img.name, |
| 432 | info_dict["verity_key"] + ".pk8", |
| 433 | info_dict["verity_key"] + ".x509.pem", img.name]) |
| Geremy Condra | 95ebe7a | 2014-08-19 17:27:56 -0700 | [diff] [blame] | 434 | p = Run(cmd, stdout=subprocess.PIPE) |
| 435 | p.communicate() |
| 436 | assert p.returncode == 0, "boot_signer of %s image failed" % path |
| 437 | |
| Tao Bao | d95e9fd | 2015-03-29 23:07:41 -0700 | [diff] [blame] | 438 | # Sign the image if vboot is non-empty. |
| 439 | elif info_dict.get("vboot", None): |
| 440 | path = "/" + os.path.basename(sourcedir).lower() |
| 441 | img_keyblock = tempfile.NamedTemporaryFile() |
| 442 | cmd = [info_dict["vboot_signer_cmd"], info_dict["futility"], |
| 443 | img_unsigned.name, info_dict["vboot_key"] + ".vbpubk", |
| Furquan Shaikh | 852b8de | 2015-08-10 11:43:45 -0700 | [diff] [blame] | 444 | info_dict["vboot_key"] + ".vbprivk", |
| 445 | info_dict["vboot_subkey"] + ".vbprivk", |
| 446 | img_keyblock.name, |
| Tao Bao | d95e9fd | 2015-03-29 23:07:41 -0700 | [diff] [blame] | 447 | img.name] |
| 448 | p = Run(cmd, stdout=subprocess.PIPE) |
| 449 | p.communicate() |
| 450 | assert p.returncode == 0, "vboot_signer of %s image failed" % path |
| 451 | |
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 452 | # Clean up the temp files. |
| 453 | img_unsigned.close() |
| 454 | img_keyblock.close() |
| 455 | |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 456 | img.seek(os.SEEK_SET, 0) |
| 457 | data = img.read() |
| 458 | |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 459 | if has_ramdisk: |
| 460 | ramdisk_img.close() |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 461 | img.close() |
| 462 | |
| 463 | return data |
| 464 | |
| 465 | |
| Doug Zongker | d513160 | 2012-08-02 14:46:42 -0700 | [diff] [blame] | 466 | def GetBootableImage(name, prebuilt_name, unpack_dir, tree_subdir, |
| 467 | info_dict=None): |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 468 | """Return a File object with the desired bootable image. |
| 469 | |
| 470 | Look for it in 'unpack_dir'/BOOTABLE_IMAGES under the name 'prebuilt_name', |
| 471 | otherwise look for it under 'unpack_dir'/IMAGES, otherwise construct it from |
| 472 | the source files in 'unpack_dir'/'tree_subdir'.""" |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 473 | |
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 474 | prebuilt_path = os.path.join(unpack_dir, "BOOTABLE_IMAGES", prebuilt_name) |
| 475 | if os.path.exists(prebuilt_path): |
| Doug Zongker | 6f1d031 | 2014-08-22 08:07:12 -0700 | [diff] [blame] | 476 | print "using prebuilt %s from BOOTABLE_IMAGES..." % (prebuilt_name,) |
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 477 | return File.FromLocalFile(name, prebuilt_path) |
| Doug Zongker | 6f1d031 | 2014-08-22 08:07:12 -0700 | [diff] [blame] | 478 | |
| 479 | prebuilt_path = os.path.join(unpack_dir, "IMAGES", prebuilt_name) |
| 480 | if os.path.exists(prebuilt_path): |
| 481 | print "using prebuilt %s from IMAGES..." % (prebuilt_name,) |
| 482 | return File.FromLocalFile(name, prebuilt_path) |
| 483 | |
| 484 | print "building image from target_files %s..." % (tree_subdir,) |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 485 | |
| 486 | if info_dict is None: |
| 487 | info_dict = OPTIONS.info_dict |
| 488 | |
| 489 | # With system_root_image == "true", we don't pack ramdisk into the boot image. |
| 490 | has_ramdisk = (info_dict.get("system_root_image", None) != "true" or |
| 491 | prebuilt_name != "boot.img") |
| 492 | |
| Doug Zongker | 6f1d031 | 2014-08-22 08:07:12 -0700 | [diff] [blame] | 493 | fs_config = "META/" + tree_subdir.lower() + "_filesystem_config.txt" |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 494 | data = _BuildBootableImage(os.path.join(unpack_dir, tree_subdir), |
| 495 | os.path.join(unpack_dir, fs_config), |
| 496 | info_dict, has_ramdisk) |
| Doug Zongker | 6f1d031 | 2014-08-22 08:07:12 -0700 | [diff] [blame] | 497 | if data: |
| 498 | return File(name, data) |
| 499 | return None |
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 500 | |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 501 | |
| Doug Zongker | 75f1736 | 2009-12-08 13:46:44 -0800 | [diff] [blame] | 502 | def UnzipTemp(filename, pattern=None): |
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 503 | """Unzip the given archive into a temporary directory and return the name. |
| 504 | |
| 505 | If filename is of the form "foo.zip+bar.zip", unzip foo.zip into a |
| 506 | temp dir, then unzip bar.zip into that_dir/BOOTABLE_IMAGES. |
| 507 | |
| 508 | Returns (tempdir, zipobj) where zipobj is a zipfile.ZipFile (of the |
| 509 | main file), open for reading. |
| 510 | """ |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 511 | |
| 512 | tmp = tempfile.mkdtemp(prefix="targetfiles-") |
| 513 | OPTIONS.tempfiles.append(tmp) |
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 514 | |
| 515 | def unzip_to_dir(filename, dirname): |
| 516 | cmd = ["unzip", "-o", "-q", filename, "-d", dirname] |
| 517 | if pattern is not None: |
| 518 | cmd.append(pattern) |
| 519 | p = Run(cmd, stdout=subprocess.PIPE) |
| 520 | p.communicate() |
| 521 | if p.returncode != 0: |
| 522 | raise ExternalError("failed to unzip input target-files \"%s\"" % |
| 523 | (filename,)) |
| 524 | |
| 525 | m = re.match(r"^(.*[.]zip)\+(.*[.]zip)$", filename, re.IGNORECASE) |
| 526 | if m: |
| 527 | unzip_to_dir(m.group(1), tmp) |
| 528 | unzip_to_dir(m.group(2), os.path.join(tmp, "BOOTABLE_IMAGES")) |
| 529 | filename = m.group(1) |
| 530 | else: |
| 531 | unzip_to_dir(filename, tmp) |
| 532 | |
| 533 | return tmp, zipfile.ZipFile(filename, "r") |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 534 | |
| 535 | |
| 536 | def GetKeyPasswords(keylist): |
| 537 | """Given a list of keys, prompt the user to enter passwords for |
| 538 | those which require them. Return a {key: password} dict. password |
| 539 | will be None if the key has no password.""" |
| 540 | |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 541 | no_passwords = [] |
| 542 | need_passwords = [] |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 543 | key_passwords = {} |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 544 | devnull = open("/dev/null", "w+b") |
| 545 | for k in sorted(keylist): |
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 546 | # We don't need a password for things that aren't really keys. |
| 547 | if k in SPECIAL_CERT_STRINGS: |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 548 | no_passwords.append(k) |
| Doug Zongker | 43874f8 | 2009-04-14 14:05:15 -0700 | [diff] [blame] | 549 | continue |
| 550 | |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 551 | p = Run(["openssl", "pkcs8", "-in", k+OPTIONS.private_key_suffix, |
| Doug Zongker | 602a84e | 2009-06-18 08:35:12 -0700 | [diff] [blame] | 552 | "-inform", "DER", "-nocrypt"], |
| 553 | stdin=devnull.fileno(), |
| 554 | stdout=devnull.fileno(), |
| 555 | stderr=subprocess.STDOUT) |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 556 | p.communicate() |
| 557 | if p.returncode == 0: |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 558 | # Definitely an unencrypted key. |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 559 | no_passwords.append(k) |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 560 | else: |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 561 | p = Run(["openssl", "pkcs8", "-in", k+OPTIONS.private_key_suffix, |
| 562 | "-inform", "DER", "-passin", "pass:"], |
| 563 | stdin=devnull.fileno(), |
| 564 | stdout=devnull.fileno(), |
| 565 | stderr=subprocess.PIPE) |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 566 | _, stderr = p.communicate() |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 567 | if p.returncode == 0: |
| 568 | # Encrypted key with empty string as password. |
| 569 | key_passwords[k] = '' |
| 570 | elif stderr.startswith('Error decrypting key'): |
| 571 | # Definitely encrypted key. |
| 572 | # It would have said "Error reading key" if it didn't parse correctly. |
| 573 | need_passwords.append(k) |
| 574 | else: |
| 575 | # Potentially, a type of key that openssl doesn't understand. |
| 576 | # We'll let the routines in signapk.jar handle it. |
| 577 | no_passwords.append(k) |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 578 | devnull.close() |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 579 | |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 580 | key_passwords.update(PasswordManager().GetPasswords(need_passwords)) |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 581 | key_passwords.update(dict.fromkeys(no_passwords, None)) |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 582 | return key_passwords |
| 583 | |
| 584 | |
| Doug Zongker | 951495f | 2009-08-14 12:44:19 -0700 | [diff] [blame] | 585 | def SignFile(input_name, output_name, key, password, align=None, |
| 586 | whole_file=False): |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 587 | """Sign the input_name zip/jar/apk, producing output_name. Use the |
| 588 | given key and password (the latter may be None if the key does not |
| 589 | have a password. |
| 590 | |
| 591 | If align is an integer > 1, zipalign is run to align stored files in |
| 592 | the output zip on 'align'-byte boundaries. |
| Doug Zongker | 951495f | 2009-08-14 12:44:19 -0700 | [diff] [blame] | 593 | |
| 594 | If whole_file is true, use the "-w" option to SignApk to embed a |
| 595 | signature that covers the whole file in the archive comment of the |
| 596 | zip file. |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 597 | """ |
| Doug Zongker | 951495f | 2009-08-14 12:44:19 -0700 | [diff] [blame] | 598 | |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 599 | if align == 0 or align == 1: |
| 600 | align = None |
| 601 | |
| 602 | if align: |
| 603 | temp = tempfile.NamedTemporaryFile() |
| 604 | sign_name = temp.name |
| 605 | else: |
| 606 | sign_name = output_name |
| 607 | |
| Baligh Uddin | 339ee49 | 2014-09-05 11:18:07 -0700 | [diff] [blame] | 608 | cmd = [OPTIONS.java_path, OPTIONS.java_args, "-jar", |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 609 | os.path.join(OPTIONS.search_path, OPTIONS.signapk_path)] |
| 610 | cmd.extend(OPTIONS.extra_signapk_args) |
| Doug Zongker | 951495f | 2009-08-14 12:44:19 -0700 | [diff] [blame] | 611 | if whole_file: |
| 612 | cmd.append("-w") |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 613 | cmd.extend([key + OPTIONS.public_key_suffix, |
| 614 | key + OPTIONS.private_key_suffix, |
| Doug Zongker | 951495f | 2009-08-14 12:44:19 -0700 | [diff] [blame] | 615 | input_name, sign_name]) |
| 616 | |
| 617 | p = Run(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 618 | if password is not None: |
| 619 | password += "\n" |
| 620 | p.communicate(password) |
| 621 | if p.returncode != 0: |
| 622 | raise ExternalError("signapk.jar failed: return code %s" % (p.returncode,)) |
| 623 | |
| 624 | if align: |
| Brian Carlstrom | 903186f | 2015-05-22 15:51:19 -0700 | [diff] [blame] | 625 | p = Run(["zipalign", "-f", "-p", str(align), sign_name, output_name]) |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 626 | p.communicate() |
| 627 | if p.returncode != 0: |
| 628 | raise ExternalError("zipalign failed: return code %s" % (p.returncode,)) |
| 629 | temp.close() |
| 630 | |
| 631 | |
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 632 | def CheckSize(data, target, info_dict): |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 633 | """Check the data string passed against the max size limit, if |
| 634 | any, for the given target. Raise exception if the data is too big. |
| 635 | Print a warning if the data is nearing the maximum size.""" |
| Doug Zongker | c77a9ad | 2010-09-16 11:28:43 -0700 | [diff] [blame] | 636 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 637 | if target.endswith(".img"): |
| 638 | target = target[:-4] |
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 639 | mount_point = "/" + target |
| 640 | |
| Ying Wang | f8824af | 2014-06-03 14:07:27 -0700 | [diff] [blame] | 641 | fs_type = None |
| 642 | limit = None |
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 643 | if info_dict["fstab"]: |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 644 | if mount_point == "/userdata": |
| 645 | mount_point = "/data" |
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 646 | p = info_dict["fstab"][mount_point] |
| 647 | fs_type = p.fs_type |
| Andrew Boie | 0f9aec8 | 2012-02-14 09:32:52 -0800 | [diff] [blame] | 648 | device = p.device |
| 649 | if "/" in device: |
| 650 | device = device[device.rfind("/")+1:] |
| 651 | limit = info_dict.get(device + "_size", None) |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 652 | if not fs_type or not limit: |
| 653 | return |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 654 | |
| Doug Zongker | c77a9ad | 2010-09-16 11:28:43 -0700 | [diff] [blame] | 655 | if fs_type == "yaffs2": |
| 656 | # image size should be increased by 1/64th to account for the |
| 657 | # spare area (64 bytes per 2k page) |
| 658 | limit = limit / 2048 * (2048+64) |
| Andrew Boie | 0f9aec8 | 2012-02-14 09:32:52 -0800 | [diff] [blame] | 659 | size = len(data) |
| 660 | pct = float(size) * 100.0 / limit |
| 661 | msg = "%s size (%d) is %.2f%% of limit (%d)" % (target, size, pct, limit) |
| 662 | if pct >= 99.0: |
| 663 | raise ExternalError(msg) |
| 664 | elif pct >= 95.0: |
| 665 | print |
| 666 | print " WARNING: ", msg |
| 667 | print |
| 668 | elif OPTIONS.verbose: |
| 669 | print " ", msg |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 670 | |
| 671 | |
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 672 | def ReadApkCerts(tf_zip): |
| 673 | """Given a target_files ZipFile, parse the META/apkcerts.txt file |
| 674 | and return a {package: cert} dict.""" |
| 675 | certmap = {} |
| 676 | for line in tf_zip.read("META/apkcerts.txt").split("\n"): |
| 677 | line = line.strip() |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 678 | if not line: |
| 679 | continue |
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 680 | m = re.match(r'^name="(.*)"\s+certificate="(.*)"\s+' |
| 681 | r'private_key="(.*)"$', line) |
| 682 | if m: |
| 683 | name, cert, privkey = m.groups() |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 684 | public_key_suffix_len = len(OPTIONS.public_key_suffix) |
| 685 | private_key_suffix_len = len(OPTIONS.private_key_suffix) |
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 686 | if cert in SPECIAL_CERT_STRINGS and not privkey: |
| 687 | certmap[name] = cert |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 688 | elif (cert.endswith(OPTIONS.public_key_suffix) and |
| 689 | privkey.endswith(OPTIONS.private_key_suffix) and |
| 690 | cert[:-public_key_suffix_len] == privkey[:-private_key_suffix_len]): |
| 691 | certmap[name] = cert[:-public_key_suffix_len] |
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 692 | else: |
| 693 | raise ValueError("failed to parse line from apkcerts.txt:\n" + line) |
| 694 | return certmap |
| 695 | |
| 696 | |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 697 | COMMON_DOCSTRING = """ |
| 698 | -p (--path) <dir> |
| Doug Zongker | 602a84e | 2009-06-18 08:35:12 -0700 | [diff] [blame] | 699 | Prepend <dir>/bin to the list of places to search for binaries |
| 700 | run by this script, and expect to find jars in <dir>/framework. |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 701 | |
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 702 | -s (--device_specific) <file> |
| 703 | Path to the python module containing device-specific |
| 704 | releasetools code. |
| 705 | |
| Doug Zongker | 8bec09e | 2009-11-30 15:37:14 -0800 | [diff] [blame] | 706 | -x (--extra) <key=value> |
| 707 | Add a key/value pair to the 'extras' dict, which device-specific |
| 708 | extension code may look at. |
| 709 | |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 710 | -v (--verbose) |
| 711 | Show command lines being executed. |
| 712 | |
| 713 | -h (--help) |
| 714 | Display this usage message and exit. |
| 715 | """ |
| 716 | |
| 717 | def Usage(docstring): |
| 718 | print docstring.rstrip("\n") |
| 719 | print COMMON_DOCSTRING |
| 720 | |
| 721 | |
| 722 | def ParseOptions(argv, |
| 723 | docstring, |
| 724 | extra_opts="", extra_long_opts=(), |
| 725 | extra_option_handler=None): |
| 726 | """Parse the options in argv and return any arguments that aren't |
| 727 | flags. docstring is the calling module's docstring, to be displayed |
| 728 | for errors and -h. extra_opts and extra_long_opts are for flags |
| 729 | defined by the caller, which are processed by passing them to |
| 730 | extra_option_handler.""" |
| 731 | |
| 732 | try: |
| 733 | opts, args = getopt.getopt( |
| Doug Zongker | 8bec09e | 2009-11-30 15:37:14 -0800 | [diff] [blame] | 734 | argv, "hvp:s:x:" + extra_opts, |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 735 | ["help", "verbose", "path=", "signapk_path=", "extra_signapk_args=", |
| Baligh Uddin | bdc2e31 | 2014-09-05 17:36:20 -0700 | [diff] [blame] | 736 | "java_path=", "java_args=", "public_key_suffix=", |
| Baligh Uddin | 601ddea | 2015-06-09 15:48:14 -0700 | [diff] [blame] | 737 | "private_key_suffix=", "boot_signer_path=", "boot_signer_args=", |
| 738 | "verity_signer_path=", "verity_signer_args=", "device_specific=", |
| Baligh Uddin | e204868 | 2014-11-20 09:52:05 -0800 | [diff] [blame] | 739 | "extra="] + |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 740 | list(extra_long_opts)) |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 741 | except getopt.GetoptError as err: |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 742 | Usage(docstring) |
| 743 | print "**", str(err), "**" |
| 744 | sys.exit(2) |
| 745 | |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 746 | for o, a in opts: |
| 747 | if o in ("-h", "--help"): |
| 748 | Usage(docstring) |
| 749 | sys.exit() |
| 750 | elif o in ("-v", "--verbose"): |
| 751 | OPTIONS.verbose = True |
| 752 | elif o in ("-p", "--path"): |
| Doug Zongker | 602a84e | 2009-06-18 08:35:12 -0700 | [diff] [blame] | 753 | OPTIONS.search_path = a |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 754 | elif o in ("--signapk_path",): |
| 755 | OPTIONS.signapk_path = a |
| 756 | elif o in ("--extra_signapk_args",): |
| 757 | OPTIONS.extra_signapk_args = shlex.split(a) |
| 758 | elif o in ("--java_path",): |
| 759 | OPTIONS.java_path = a |
| Baligh Uddin | 339ee49 | 2014-09-05 11:18:07 -0700 | [diff] [blame] | 760 | elif o in ("--java_args",): |
| 761 | OPTIONS.java_args = a |
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 762 | elif o in ("--public_key_suffix",): |
| 763 | OPTIONS.public_key_suffix = a |
| 764 | elif o in ("--private_key_suffix",): |
| 765 | OPTIONS.private_key_suffix = a |
| Baligh Uddin | e204868 | 2014-11-20 09:52:05 -0800 | [diff] [blame] | 766 | elif o in ("--boot_signer_path",): |
| 767 | OPTIONS.boot_signer_path = a |
| Baligh Uddin | 601ddea | 2015-06-09 15:48:14 -0700 | [diff] [blame] | 768 | elif o in ("--boot_signer_args",): |
| 769 | OPTIONS.boot_signer_args = shlex.split(a) |
| 770 | elif o in ("--verity_signer_path",): |
| 771 | OPTIONS.verity_signer_path = a |
| 772 | elif o in ("--verity_signer_args",): |
| 773 | OPTIONS.verity_signer_args = shlex.split(a) |
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 774 | elif o in ("-s", "--device_specific"): |
| 775 | OPTIONS.device_specific = a |
| Doug Zongker | 5ecba70 | 2009-12-03 16:36:20 -0800 | [diff] [blame] | 776 | elif o in ("-x", "--extra"): |
| Doug Zongker | 8bec09e | 2009-11-30 15:37:14 -0800 | [diff] [blame] | 777 | key, value = a.split("=", 1) |
| 778 | OPTIONS.extras[key] = value |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 779 | else: |
| 780 | if extra_option_handler is None or not extra_option_handler(o, a): |
| 781 | assert False, "unknown option \"%s\"" % (o,) |
| 782 | |
| Doug Zongker | 8544877 | 2014-09-09 14:59:20 -0700 | [diff] [blame] | 783 | if OPTIONS.search_path: |
| 784 | os.environ["PATH"] = (os.path.join(OPTIONS.search_path, "bin") + |
| 785 | os.pathsep + os.environ["PATH"]) |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 786 | |
| 787 | return args |
| 788 | |
| 789 | |
| Doug Zongker | fc44a51 | 2014-08-26 13:10:25 -0700 | [diff] [blame] | 790 | def MakeTempFile(prefix=None, suffix=None): |
| 791 | """Make a temp file and add it to the list of things to be deleted |
| 792 | when Cleanup() is called. Return the filename.""" |
| 793 | fd, fn = tempfile.mkstemp(prefix=prefix, suffix=suffix) |
| 794 | os.close(fd) |
| 795 | OPTIONS.tempfiles.append(fn) |
| 796 | return fn |
| 797 | |
| 798 | |
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 799 | def Cleanup(): |
| 800 | for i in OPTIONS.tempfiles: |
| 801 | if os.path.isdir(i): |
| 802 | shutil.rmtree(i) |
| 803 | else: |
| 804 | os.remove(i) |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 805 | |
| 806 | |
| 807 | class PasswordManager(object): |
| 808 | def __init__(self): |
| 809 | self.editor = os.getenv("EDITOR", None) |
| 810 | self.pwfile = os.getenv("ANDROID_PW_FILE", None) |
| 811 | |
| 812 | def GetPasswords(self, items): |
| 813 | """Get passwords corresponding to each string in 'items', |
| 814 | returning a dict. (The dict may have keys in addition to the |
| 815 | values in 'items'.) |
| 816 | |
| 817 | Uses the passwords in $ANDROID_PW_FILE if available, letting the |
| 818 | user edit that file to add more needed passwords. If no editor is |
| 819 | available, or $ANDROID_PW_FILE isn't define, prompts the user |
| 820 | interactively in the ordinary way. |
| 821 | """ |
| 822 | |
| 823 | current = self.ReadFile() |
| 824 | |
| 825 | first = True |
| 826 | while True: |
| 827 | missing = [] |
| 828 | for i in items: |
| 829 | if i not in current or not current[i]: |
| 830 | missing.append(i) |
| 831 | # Are all the passwords already in the file? |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 832 | if not missing: |
| 833 | return current |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 834 | |
| 835 | for i in missing: |
| 836 | current[i] = "" |
| 837 | |
| 838 | if not first: |
| 839 | print "key file %s still missing some passwords." % (self.pwfile,) |
| 840 | answer = raw_input("try to edit again? [y]> ").strip() |
| 841 | if answer and answer[0] not in 'yY': |
| 842 | raise RuntimeError("key passwords unavailable") |
| 843 | first = False |
| 844 | |
| 845 | current = self.UpdateAndReadFile(current) |
| 846 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 847 | def PromptResult(self, current): # pylint: disable=no-self-use |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 848 | """Prompt the user to enter a value (password) for each key in |
| 849 | 'current' whose value is fales. Returns a new dict with all the |
| 850 | values. |
| 851 | """ |
| 852 | result = {} |
| 853 | for k, v in sorted(current.iteritems()): |
| 854 | if v: |
| 855 | result[k] = v |
| 856 | else: |
| 857 | while True: |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 858 | result[k] = getpass.getpass( |
| 859 | "Enter password for %s key> " % k).strip() |
| 860 | if result[k]: |
| 861 | break |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 862 | return result |
| 863 | |
| 864 | def UpdateAndReadFile(self, current): |
| 865 | if not self.editor or not self.pwfile: |
| 866 | return self.PromptResult(current) |
| 867 | |
| 868 | f = open(self.pwfile, "w") |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 869 | os.chmod(self.pwfile, 0o600) |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 870 | f.write("# Enter key passwords between the [[[ ]]] brackets.\n") |
| 871 | f.write("# (Additional spaces are harmless.)\n\n") |
| 872 | |
| 873 | first_line = None |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 874 | sorted_list = sorted([(not v, k, v) for (k, v) in current.iteritems()]) |
| 875 | for i, (_, k, v) in enumerate(sorted_list): |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 876 | f.write("[[[ %s ]]] %s\n" % (v, k)) |
| 877 | if not v and first_line is None: |
| 878 | # position cursor on first line with no password. |
| 879 | first_line = i + 4 |
| 880 | f.close() |
| 881 | |
| 882 | p = Run([self.editor, "+%d" % (first_line,), self.pwfile]) |
| 883 | _, _ = p.communicate() |
| 884 | |
| 885 | return self.ReadFile() |
| 886 | |
| 887 | def ReadFile(self): |
| 888 | result = {} |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 889 | if self.pwfile is None: |
| 890 | return result |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 891 | try: |
| 892 | f = open(self.pwfile, "r") |
| 893 | for line in f: |
| 894 | line = line.strip() |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 895 | if not line or line[0] == '#': |
| 896 | continue |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 897 | m = re.match(r"^\[\[\[\s*(.*?)\s*\]\]\]\s*(\S+)$", line) |
| 898 | if not m: |
| 899 | print "failed to parse password file: ", line |
| 900 | else: |
| 901 | result[m.group(2)] = m.group(1) |
| 902 | f.close() |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 903 | except IOError as e: |
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 904 | if e.errno != errno.ENOENT: |
| 905 | print "error reading password file: ", str(e) |
| 906 | return result |
| Doug Zongker | 048e7ca | 2009-06-15 14:31:53 -0700 | [diff] [blame] | 907 | |
| 908 | |
| Dan Albert | 8e0178d | 2015-01-27 15:53:15 -0800 | [diff] [blame] | 909 | def ZipWrite(zip_file, filename, arcname=None, perms=0o644, |
| 910 | compress_type=None): |
| 911 | import datetime |
| 912 | |
| 913 | # http://b/18015246 |
| 914 | # Python 2.7's zipfile implementation wrongly thinks that zip64 is required |
| 915 | # for files larger than 2GiB. We can work around this by adjusting their |
| 916 | # limit. Note that `zipfile.writestr()` will not work for strings larger than |
| 917 | # 2GiB. The Python interpreter sometimes rejects strings that large (though |
| 918 | # it isn't clear to me exactly what circumstances cause this). |
| 919 | # `zipfile.write()` must be used directly to work around this. |
| 920 | # |
| 921 | # This mess can be avoided if we port to python3. |
| 922 | saved_zip64_limit = zipfile.ZIP64_LIMIT |
| 923 | zipfile.ZIP64_LIMIT = (1 << 32) - 1 |
| 924 | |
| 925 | if compress_type is None: |
| 926 | compress_type = zip_file.compression |
| 927 | if arcname is None: |
| 928 | arcname = filename |
| 929 | |
| 930 | saved_stat = os.stat(filename) |
| 931 | |
| 932 | try: |
| 933 | # `zipfile.write()` doesn't allow us to pass ZipInfo, so just modify the |
| 934 | # file to be zipped and reset it when we're done. |
| 935 | os.chmod(filename, perms) |
| 936 | |
| 937 | # Use a fixed timestamp so the output is repeatable. |
| 938 | epoch = datetime.datetime.fromtimestamp(0) |
| 939 | timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds() |
| 940 | os.utime(filename, (timestamp, timestamp)) |
| 941 | |
| 942 | zip_file.write(filename, arcname=arcname, compress_type=compress_type) |
| 943 | finally: |
| 944 | os.chmod(filename, saved_stat.st_mode) |
| 945 | os.utime(filename, (saved_stat.st_atime, saved_stat.st_mtime)) |
| 946 | zipfile.ZIP64_LIMIT = saved_zip64_limit |
| 947 | |
| 948 | |
| Tao Bao | 58c1b96 | 2015-05-20 09:32:18 -0700 | [diff] [blame] | 949 | def ZipWriteStr(zip_file, zinfo_or_arcname, data, perms=None, |
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 950 | compress_type=None): |
| 951 | """Wrap zipfile.writestr() function to work around the zip64 limit. |
| 952 | |
| 953 | Even with the ZIP64_LIMIT workaround, it won't allow writing a string |
| 954 | longer than 2GiB. It gives 'OverflowError: size does not fit in an int' |
| 955 | when calling crc32(bytes). |
| 956 | |
| 957 | But it still works fine to write a shorter string into a large zip file. |
| 958 | We should use ZipWrite() whenever possible, and only use ZipWriteStr() |
| 959 | when we know the string won't be too long. |
| 960 | """ |
| 961 | |
| 962 | saved_zip64_limit = zipfile.ZIP64_LIMIT |
| 963 | zipfile.ZIP64_LIMIT = (1 << 32) - 1 |
| 964 | |
| 965 | if not isinstance(zinfo_or_arcname, zipfile.ZipInfo): |
| 966 | zinfo = zipfile.ZipInfo(filename=zinfo_or_arcname) |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 967 | zinfo.compress_type = zip_file.compression |
| Tao Bao | 58c1b96 | 2015-05-20 09:32:18 -0700 | [diff] [blame] | 968 | if perms is None: |
| Tao Bao | 2a41058 | 2015-07-10 17:18:23 -0700 | [diff] [blame] | 969 | perms = 0o100644 |
| Geremy Condra | 36bd365 | 2014-02-06 19:45:10 -0800 | [diff] [blame] | 970 | else: |
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 971 | zinfo = zinfo_or_arcname |
| 972 | |
| 973 | # If compress_type is given, it overrides the value in zinfo. |
| 974 | if compress_type is not None: |
| 975 | zinfo.compress_type = compress_type |
| 976 | |
| Tao Bao | 58c1b96 | 2015-05-20 09:32:18 -0700 | [diff] [blame] | 977 | # If perms is given, it has a priority. |
| 978 | if perms is not None: |
| Tao Bao | 2a41058 | 2015-07-10 17:18:23 -0700 | [diff] [blame] | 979 | # If perms doesn't set the file type, mark it as a regular file. |
| 980 | if perms & 0o770000 == 0: |
| 981 | perms |= 0o100000 |
| Tao Bao | 58c1b96 | 2015-05-20 09:32:18 -0700 | [diff] [blame] | 982 | zinfo.external_attr = perms << 16 |
| 983 | |
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 984 | # Use a fixed timestamp so the output is repeatable. |
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 985 | zinfo.date_time = (2009, 1, 1, 0, 0, 0) |
| 986 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 987 | zip_file.writestr(zinfo, data) |
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 988 | zipfile.ZIP64_LIMIT = saved_zip64_limit |
| 989 | |
| 990 | |
| 991 | def ZipClose(zip_file): |
| 992 | # http://b/18015246 |
| 993 | # zipfile also refers to ZIP64_LIMIT during close() when it writes out the |
| 994 | # central directory. |
| 995 | saved_zip64_limit = zipfile.ZIP64_LIMIT |
| 996 | zipfile.ZIP64_LIMIT = (1 << 32) - 1 |
| 997 | |
| 998 | zip_file.close() |
| 999 | |
| 1000 | zipfile.ZIP64_LIMIT = saved_zip64_limit |
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1001 | |
| 1002 | |
| 1003 | class DeviceSpecificParams(object): |
| 1004 | module = None |
| 1005 | def __init__(self, **kwargs): |
| 1006 | """Keyword arguments to the constructor become attributes of this |
| 1007 | object, which is passed to all functions in the device-specific |
| 1008 | module.""" |
| 1009 | for k, v in kwargs.iteritems(): |
| 1010 | setattr(self, k, v) |
| Doug Zongker | 8bec09e | 2009-11-30 15:37:14 -0800 | [diff] [blame] | 1011 | self.extras = OPTIONS.extras |
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1012 | |
| 1013 | if self.module is None: |
| 1014 | path = OPTIONS.device_specific |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1015 | if not path: |
| 1016 | return |
| Doug Zongker | 8e2f2b9 | 2009-06-24 14:34:57 -0700 | [diff] [blame] | 1017 | try: |
| 1018 | if os.path.isdir(path): |
| 1019 | info = imp.find_module("releasetools", [path]) |
| 1020 | else: |
| 1021 | d, f = os.path.split(path) |
| 1022 | b, x = os.path.splitext(f) |
| 1023 | if x == ".py": |
| 1024 | f = b |
| 1025 | info = imp.find_module(f, [d]) |
| Doug Zongker | eb0a78a | 2014-01-27 10:01:06 -0800 | [diff] [blame] | 1026 | print "loaded device-specific extensions from", path |
| Doug Zongker | 8e2f2b9 | 2009-06-24 14:34:57 -0700 | [diff] [blame] | 1027 | self.module = imp.load_module("device_specific", *info) |
| 1028 | except ImportError: |
| 1029 | print "unable to load device-specific module; assuming none" |
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1030 | |
| 1031 | def _DoCall(self, function_name, *args, **kwargs): |
| 1032 | """Call the named function in the device-specific module, passing |
| 1033 | the given args and kwargs. The first argument to the call will be |
| 1034 | the DeviceSpecific object itself. If there is no module, or the |
| 1035 | module does not define the function, return the value of the |
| 1036 | 'default' kwarg (which itself defaults to None).""" |
| 1037 | if self.module is None or not hasattr(self.module, function_name): |
| 1038 | return kwargs.get("default", None) |
| 1039 | return getattr(self.module, function_name)(*((self,) + args), **kwargs) |
| 1040 | |
| 1041 | def FullOTA_Assertions(self): |
| 1042 | """Called after emitting the block of assertions at the top of a |
| 1043 | full OTA package. Implementations can add whatever additional |
| 1044 | assertions they like.""" |
| 1045 | return self._DoCall("FullOTA_Assertions") |
| 1046 | |
| Doug Zongker | e5ff590 | 2012-01-17 10:55:37 -0800 | [diff] [blame] | 1047 | def FullOTA_InstallBegin(self): |
| 1048 | """Called at the start of full OTA installation.""" |
| 1049 | return self._DoCall("FullOTA_InstallBegin") |
| 1050 | |
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1051 | def FullOTA_InstallEnd(self): |
| 1052 | """Called at the end of full OTA installation; typically this is |
| 1053 | used to install the image for the device's baseband processor.""" |
| 1054 | return self._DoCall("FullOTA_InstallEnd") |
| 1055 | |
| 1056 | def IncrementalOTA_Assertions(self): |
| 1057 | """Called after emitting the block of assertions at the top of an |
| 1058 | incremental OTA package. Implementations can add whatever |
| 1059 | additional assertions they like.""" |
| 1060 | return self._DoCall("IncrementalOTA_Assertions") |
| 1061 | |
| Doug Zongker | e5ff590 | 2012-01-17 10:55:37 -0800 | [diff] [blame] | 1062 | def IncrementalOTA_VerifyBegin(self): |
| 1063 | """Called at the start of the verification phase of incremental |
| 1064 | OTA installation; additional checks can be placed here to abort |
| 1065 | the script before any changes are made.""" |
| 1066 | return self._DoCall("IncrementalOTA_VerifyBegin") |
| 1067 | |
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1068 | def IncrementalOTA_VerifyEnd(self): |
| 1069 | """Called at the end of the verification phase of incremental OTA |
| 1070 | installation; additional checks can be placed here to abort the |
| 1071 | script before any changes are made.""" |
| 1072 | return self._DoCall("IncrementalOTA_VerifyEnd") |
| 1073 | |
| Doug Zongker | e5ff590 | 2012-01-17 10:55:37 -0800 | [diff] [blame] | 1074 | def IncrementalOTA_InstallBegin(self): |
| 1075 | """Called at the start of incremental OTA installation (after |
| 1076 | verification is complete).""" |
| 1077 | return self._DoCall("IncrementalOTA_InstallBegin") |
| 1078 | |
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1079 | def IncrementalOTA_InstallEnd(self): |
| 1080 | """Called at the end of incremental OTA installation; typically |
| 1081 | this is used to install the image for the device's baseband |
| 1082 | processor.""" |
| 1083 | return self._DoCall("IncrementalOTA_InstallEnd") |
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1084 | |
| 1085 | class File(object): |
| 1086 | def __init__(self, name, data): |
| 1087 | self.name = name |
| 1088 | self.data = data |
| 1089 | self.size = len(data) |
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 1090 | self.sha1 = sha1(data).hexdigest() |
| 1091 | |
| 1092 | @classmethod |
| 1093 | def FromLocalFile(cls, name, diskname): |
| 1094 | f = open(diskname, "rb") |
| 1095 | data = f.read() |
| 1096 | f.close() |
| 1097 | return File(name, data) |
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1098 | |
| 1099 | def WriteToTemp(self): |
| 1100 | t = tempfile.NamedTemporaryFile() |
| 1101 | t.write(self.data) |
| 1102 | t.flush() |
| 1103 | return t |
| 1104 | |
| Geremy Condra | 36bd365 | 2014-02-06 19:45:10 -0800 | [diff] [blame] | 1105 | def AddToZip(self, z, compression=None): |
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 1106 | ZipWriteStr(z, self.name, self.data, compress_type=compression) |
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1107 | |
| 1108 | DIFF_PROGRAM_BY_EXT = { |
| 1109 | ".gz" : "imgdiff", |
| 1110 | ".zip" : ["imgdiff", "-z"], |
| 1111 | ".jar" : ["imgdiff", "-z"], |
| 1112 | ".apk" : ["imgdiff", "-z"], |
| 1113 | ".img" : "imgdiff", |
| 1114 | } |
| 1115 | |
| 1116 | class Difference(object): |
| Doug Zongker | 24cd280 | 2012-08-14 16:36:15 -0700 | [diff] [blame] | 1117 | def __init__(self, tf, sf, diff_program=None): |
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1118 | self.tf = tf |
| 1119 | self.sf = sf |
| 1120 | self.patch = None |
| Doug Zongker | 24cd280 | 2012-08-14 16:36:15 -0700 | [diff] [blame] | 1121 | self.diff_program = diff_program |
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1122 | |
| 1123 | def ComputePatch(self): |
| 1124 | """Compute the patch (as a string of data) needed to turn sf into |
| 1125 | tf. Returns the same tuple as GetPatch().""" |
| 1126 | |
| 1127 | tf = self.tf |
| 1128 | sf = self.sf |
| 1129 | |
| Doug Zongker | 24cd280 | 2012-08-14 16:36:15 -0700 | [diff] [blame] | 1130 | if self.diff_program: |
| 1131 | diff_program = self.diff_program |
| 1132 | else: |
| 1133 | ext = os.path.splitext(tf.name)[1] |
| 1134 | diff_program = DIFF_PROGRAM_BY_EXT.get(ext, "bsdiff") |
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1135 | |
| 1136 | ttemp = tf.WriteToTemp() |
| 1137 | stemp = sf.WriteToTemp() |
| 1138 | |
| 1139 | ext = os.path.splitext(tf.name)[1] |
| 1140 | |
| 1141 | try: |
| 1142 | ptemp = tempfile.NamedTemporaryFile() |
| 1143 | if isinstance(diff_program, list): |
| 1144 | cmd = copy.copy(diff_program) |
| 1145 | else: |
| 1146 | cmd = [diff_program] |
| 1147 | cmd.append(stemp.name) |
| 1148 | cmd.append(ttemp.name) |
| 1149 | cmd.append(ptemp.name) |
| 1150 | p = Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| Doug Zongker | f834008 | 2014-08-05 10:39:37 -0700 | [diff] [blame] | 1151 | err = [] |
| 1152 | def run(): |
| 1153 | _, e = p.communicate() |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1154 | if e: |
| 1155 | err.append(e) |
| Doug Zongker | f834008 | 2014-08-05 10:39:37 -0700 | [diff] [blame] | 1156 | th = threading.Thread(target=run) |
| 1157 | th.start() |
| 1158 | th.join(timeout=300) # 5 mins |
| 1159 | if th.is_alive(): |
| 1160 | print "WARNING: diff command timed out" |
| 1161 | p.terminate() |
| 1162 | th.join(5) |
| 1163 | if th.is_alive(): |
| 1164 | p.kill() |
| 1165 | th.join() |
| 1166 | |
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1167 | if err or p.returncode != 0: |
| Doug Zongker | f834008 | 2014-08-05 10:39:37 -0700 | [diff] [blame] | 1168 | print "WARNING: failure running %s:\n%s\n" % ( |
| 1169 | diff_program, "".join(err)) |
| 1170 | self.patch = None |
| 1171 | return None, None, None |
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1172 | diff = ptemp.read() |
| 1173 | finally: |
| 1174 | ptemp.close() |
| 1175 | stemp.close() |
| 1176 | ttemp.close() |
| 1177 | |
| 1178 | self.patch = diff |
| 1179 | return self.tf, self.sf, self.patch |
| 1180 | |
| 1181 | |
| 1182 | def GetPatch(self): |
| 1183 | """Return a tuple (target_file, source_file, patch_data). |
| 1184 | patch_data may be None if ComputePatch hasn't been called, or if |
| 1185 | computing the patch failed.""" |
| 1186 | return self.tf, self.sf, self.patch |
| 1187 | |
| 1188 | |
| 1189 | def ComputeDifferences(diffs): |
| 1190 | """Call ComputePatch on all the Difference objects in 'diffs'.""" |
| 1191 | print len(diffs), "diffs to compute" |
| 1192 | |
| 1193 | # Do the largest files first, to try and reduce the long-pole effect. |
| 1194 | by_size = [(i.tf.size, i) for i in diffs] |
| 1195 | by_size.sort(reverse=True) |
| 1196 | by_size = [i[1] for i in by_size] |
| 1197 | |
| 1198 | lock = threading.Lock() |
| 1199 | diff_iter = iter(by_size) # accessed under lock |
| 1200 | |
| 1201 | def worker(): |
| 1202 | try: |
| 1203 | lock.acquire() |
| 1204 | for d in diff_iter: |
| 1205 | lock.release() |
| 1206 | start = time.time() |
| 1207 | d.ComputePatch() |
| 1208 | dur = time.time() - start |
| 1209 | lock.acquire() |
| 1210 | |
| 1211 | tf, sf, patch = d.GetPatch() |
| 1212 | if sf.name == tf.name: |
| 1213 | name = tf.name |
| 1214 | else: |
| 1215 | name = "%s (%s)" % (tf.name, sf.name) |
| 1216 | if patch is None: |
| 1217 | print "patching failed! %s" % (name,) |
| 1218 | else: |
| 1219 | print "%8.2f sec %8d / %8d bytes (%6.2f%%) %s" % ( |
| 1220 | dur, len(patch), tf.size, 100.0 * len(patch) / tf.size, name) |
| 1221 | lock.release() |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1222 | except Exception as e: |
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1223 | print e |
| 1224 | raise |
| 1225 | |
| 1226 | # start worker threads; wait for them all to finish. |
| 1227 | threads = [threading.Thread(target=worker) |
| 1228 | for i in range(OPTIONS.worker_threads)] |
| 1229 | for th in threads: |
| 1230 | th.start() |
| 1231 | while threads: |
| 1232 | threads.pop().join() |
| Doug Zongker | 96a57e7 | 2010-09-26 14:57:41 -0700 | [diff] [blame] | 1233 | |
| 1234 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1235 | class BlockDifference(object): |
| 1236 | def __init__(self, partition, tgt, src=None, check_first_block=False, |
| 1237 | version=None): |
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1238 | self.tgt = tgt |
| 1239 | self.src = src |
| 1240 | self.partition = partition |
| Doug Zongker | b34fcce | 2014-09-11 09:34:56 -0700 | [diff] [blame] | 1241 | self.check_first_block = check_first_block |
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1242 | |
| Tao Bao | 5ece99d | 2015-05-12 11:42:31 -0700 | [diff] [blame] | 1243 | # Due to http://b/20939131, check_first_block is disabled temporarily. |
| 1244 | assert not self.check_first_block |
| 1245 | |
| Tao Bao | dd2a589 | 2015-03-12 12:32:37 -0700 | [diff] [blame] | 1246 | if version is None: |
| 1247 | version = 1 |
| 1248 | if OPTIONS.info_dict: |
| 1249 | version = max( |
| 1250 | int(i) for i in |
| 1251 | OPTIONS.info_dict.get("blockimgdiff_versions", "1").split(",")) |
| 1252 | self.version = version |
| Doug Zongker | 6233818 | 2014-09-08 08:29:55 -0700 | [diff] [blame] | 1253 | |
| 1254 | b = blockimgdiff.BlockImageDiff(tgt, src, threads=OPTIONS.worker_threads, |
| Michael Runge | 910b005 | 2015-02-11 19:28:08 -0800 | [diff] [blame] | 1255 | version=self.version) |
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1256 | tmpdir = tempfile.mkdtemp() |
| 1257 | OPTIONS.tempfiles.append(tmpdir) |
| 1258 | self.path = os.path.join(tmpdir, partition) |
| 1259 | b.Compute(self.path) |
| 1260 | |
| 1261 | _, self.device = GetTypeAndDevice("/" + partition, OPTIONS.info_dict) |
| 1262 | |
| 1263 | def WriteScript(self, script, output_zip, progress=None): |
| 1264 | if not self.src: |
| 1265 | # write the output unconditionally |
| Jesse Zhao | 75bcea0 | 2015-01-06 10:59:53 -0800 | [diff] [blame] | 1266 | script.Print("Patching %s image unconditionally..." % (self.partition,)) |
| 1267 | else: |
| 1268 | script.Print("Patching %s image after verification." % (self.partition,)) |
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1269 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1270 | if progress: |
| 1271 | script.ShowProgress(progress, 0) |
| Jesse Zhao | 75bcea0 | 2015-01-06 10:59:53 -0800 | [diff] [blame] | 1272 | self._WriteUpdate(script, output_zip) |
| Tao Bao | 5fcaaef | 2015-06-01 13:40:49 -0700 | [diff] [blame] | 1273 | self._WritePostInstallVerifyScript(script) |
| Jesse Zhao | 75bcea0 | 2015-01-06 10:59:53 -0800 | [diff] [blame] | 1274 | |
| 1275 | def WriteVerifyScript(self, script): |
| Sami Tolvanen | dd67a29 | 2014-12-09 16:40:34 +0000 | [diff] [blame] | 1276 | partition = self.partition |
| Jesse Zhao | 75bcea0 | 2015-01-06 10:59:53 -0800 | [diff] [blame] | 1277 | if not self.src: |
| Sami Tolvanen | dd67a29 | 2014-12-09 16:40:34 +0000 | [diff] [blame] | 1278 | script.Print("Image %s will be patched unconditionally." % (partition,)) |
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1279 | else: |
| Tao Bao | 5ece99d | 2015-05-12 11:42:31 -0700 | [diff] [blame] | 1280 | ranges = self.src.care_map.subtract(self.src.clobbered_blocks) |
| 1281 | ranges_str = ranges.to_string_raw() |
| Michael Runge | 910b005 | 2015-02-11 19:28:08 -0800 | [diff] [blame] | 1282 | if self.version >= 3: |
| Sami Tolvanen | e09d096 | 2015-04-24 11:54:01 +0100 | [diff] [blame] | 1283 | script.AppendExtra(('if (range_sha1("%s", "%s") == "%s" || ' |
| 1284 | 'block_image_verify("%s", ' |
| Michael Runge | 910b005 | 2015-02-11 19:28:08 -0800 | [diff] [blame] | 1285 | 'package_extract_file("%s.transfer.list"), ' |
| Sami Tolvanen | e09d096 | 2015-04-24 11:54:01 +0100 | [diff] [blame] | 1286 | '"%s.new.dat", "%s.patch.dat")) then') % ( |
| Tao Bao | 5ece99d | 2015-05-12 11:42:31 -0700 | [diff] [blame] | 1287 | self.device, ranges_str, self.src.TotalSha1(), |
| Sami Tolvanen | e09d096 | 2015-04-24 11:54:01 +0100 | [diff] [blame] | 1288 | self.device, partition, partition, partition)) |
| Michael Runge | 910b005 | 2015-02-11 19:28:08 -0800 | [diff] [blame] | 1289 | else: |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1290 | script.AppendExtra('if range_sha1("%s", "%s") == "%s" then' % ( |
| Tao Bao | 5ece99d | 2015-05-12 11:42:31 -0700 | [diff] [blame] | 1291 | self.device, ranges_str, self.src.TotalSha1())) |
| Tao Bao | dd2a589 | 2015-03-12 12:32:37 -0700 | [diff] [blame] | 1292 | script.Print('Verified %s image...' % (partition,)) |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1293 | script.AppendExtra('else') |
| Sami Tolvanen | dd67a29 | 2014-12-09 16:40:34 +0000 | [diff] [blame] | 1294 | |
| Tao Bao | dd2a589 | 2015-03-12 12:32:37 -0700 | [diff] [blame] | 1295 | # When generating incrementals for the system and vendor partitions, |
| 1296 | # explicitly check the first block (which contains the superblock) of |
| 1297 | # the partition to see if it's what we expect. If this check fails, |
| 1298 | # give an explicit log message about the partition having been |
| 1299 | # remounted R/W (the most likely explanation) and the need to flash to |
| 1300 | # get OTAs working again. |
| Doug Zongker | b34fcce | 2014-09-11 09:34:56 -0700 | [diff] [blame] | 1301 | if self.check_first_block: |
| 1302 | self._CheckFirstBlock(script) |
| 1303 | |
| Tao Bao | dd2a589 | 2015-03-12 12:32:37 -0700 | [diff] [blame] | 1304 | # Abort the OTA update. Note that the incremental OTA cannot be applied |
| 1305 | # even if it may match the checksum of the target partition. |
| 1306 | # a) If version < 3, operations like move and erase will make changes |
| 1307 | # unconditionally and damage the partition. |
| 1308 | # b) If version >= 3, it won't even reach here. |
| 1309 | script.AppendExtra(('abort("%s partition has unexpected contents");\n' |
| 1310 | 'endif;') % (partition,)) |
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1311 | |
| Tao Bao | 5fcaaef | 2015-06-01 13:40:49 -0700 | [diff] [blame] | 1312 | def _WritePostInstallVerifyScript(self, script): |
| 1313 | partition = self.partition |
| 1314 | script.Print('Verifying the updated %s image...' % (partition,)) |
| 1315 | # Unlike pre-install verification, clobbered_blocks should not be ignored. |
| 1316 | ranges = self.tgt.care_map |
| 1317 | ranges_str = ranges.to_string_raw() |
| 1318 | script.AppendExtra('if range_sha1("%s", "%s") == "%s" then' % ( |
| 1319 | self.device, ranges_str, |
| 1320 | self.tgt.TotalSha1(include_clobbered_blocks=True))) |
| Tao Bao | e9b6191 | 2015-07-09 17:37:49 -0700 | [diff] [blame] | 1321 | |
| 1322 | # Bug: 20881595 |
| 1323 | # Verify that extended blocks are really zeroed out. |
| 1324 | if self.tgt.extended: |
| 1325 | ranges_str = self.tgt.extended.to_string_raw() |
| 1326 | script.AppendExtra('if range_sha1("%s", "%s") == "%s" then' % ( |
| 1327 | self.device, ranges_str, |
| 1328 | self._HashZeroBlocks(self.tgt.extended.size()))) |
| 1329 | script.Print('Verified the updated %s image.' % (partition,)) |
| 1330 | script.AppendExtra( |
| 1331 | 'else\n' |
| 1332 | ' abort("%s partition has unexpected non-zero contents after OTA ' |
| 1333 | 'update");\n' |
| 1334 | 'endif;' % (partition,)) |
| 1335 | else: |
| 1336 | script.Print('Verified the updated %s image.' % (partition,)) |
| 1337 | |
| Tao Bao | 5fcaaef | 2015-06-01 13:40:49 -0700 | [diff] [blame] | 1338 | script.AppendExtra( |
| 1339 | 'else\n' |
| 1340 | ' abort("%s partition has unexpected contents after OTA update");\n' |
| 1341 | 'endif;' % (partition,)) |
| 1342 | |
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1343 | def _WriteUpdate(self, script, output_zip): |
| Dan Albert | 8e0178d | 2015-01-27 15:53:15 -0800 | [diff] [blame] | 1344 | ZipWrite(output_zip, |
| 1345 | '{}.transfer.list'.format(self.path), |
| 1346 | '{}.transfer.list'.format(self.partition)) |
| 1347 | ZipWrite(output_zip, |
| 1348 | '{}.new.dat'.format(self.path), |
| 1349 | '{}.new.dat'.format(self.partition)) |
| 1350 | ZipWrite(output_zip, |
| 1351 | '{}.patch.dat'.format(self.path), |
| 1352 | '{}.patch.dat'.format(self.partition), |
| 1353 | compress_type=zipfile.ZIP_STORED) |
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1354 | |
| Dan Albert | 8e0178d | 2015-01-27 15:53:15 -0800 | [diff] [blame] | 1355 | call = ('block_image_update("{device}", ' |
| 1356 | 'package_extract_file("{partition}.transfer.list"), ' |
| 1357 | '"{partition}.new.dat", "{partition}.patch.dat");\n'.format( |
| 1358 | device=self.device, partition=self.partition)) |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1359 | script.AppendExtra(script.WordWrap(call)) |
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1360 | |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1361 | def _HashBlocks(self, source, ranges): # pylint: disable=no-self-use |
| Sami Tolvanen | dd67a29 | 2014-12-09 16:40:34 +0000 | [diff] [blame] | 1362 | data = source.ReadRangeSet(ranges) |
| 1363 | ctx = sha1() |
| 1364 | |
| 1365 | for p in data: |
| 1366 | ctx.update(p) |
| 1367 | |
| 1368 | return ctx.hexdigest() |
| 1369 | |
| Tao Bao | e9b6191 | 2015-07-09 17:37:49 -0700 | [diff] [blame] | 1370 | def _HashZeroBlocks(self, num_blocks): # pylint: disable=no-self-use |
| 1371 | """Return the hash value for all zero blocks.""" |
| 1372 | zero_block = '\x00' * 4096 |
| 1373 | ctx = sha1() |
| 1374 | for _ in range(num_blocks): |
| 1375 | ctx.update(zero_block) |
| 1376 | |
| 1377 | return ctx.hexdigest() |
| 1378 | |
| Tao Bao | 5ece99d | 2015-05-12 11:42:31 -0700 | [diff] [blame] | 1379 | # TODO(tbao): Due to http://b/20939131, block 0 may be changed without |
| 1380 | # remounting R/W. Will change the checking to a finer-grained way to |
| 1381 | # mask off those bits. |
| Doug Zongker | b34fcce | 2014-09-11 09:34:56 -0700 | [diff] [blame] | 1382 | def _CheckFirstBlock(self, script): |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1383 | r = rangelib.RangeSet((0, 1)) |
| 1384 | srchash = self._HashBlocks(self.src, r) |
| Doug Zongker | b34fcce | 2014-09-11 09:34:56 -0700 | [diff] [blame] | 1385 | |
| 1386 | script.AppendExtra(('(range_sha1("%s", "%s") == "%s") || ' |
| 1387 | 'abort("%s has been remounted R/W; ' |
| 1388 | 'reflash device to reenable OTA updates");') |
| Sami Tolvanen | dd67a29 | 2014-12-09 16:40:34 +0000 | [diff] [blame] | 1389 | % (self.device, r.to_string_raw(), srchash, |
| Sami Tolvanen | dd67a29 | 2014-12-09 16:40:34 +0000 | [diff] [blame] | 1390 | self.device)) |
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1391 | |
| 1392 | DataImage = blockimgdiff.DataImage |
| 1393 | |
| 1394 | |
| Doug Zongker | 96a57e7 | 2010-09-26 14:57:41 -0700 | [diff] [blame] | 1395 | # map recovery.fstab's fs_types to mount/format "partition types" |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1396 | PARTITION_TYPES = { |
| 1397 | "yaffs2": "MTD", |
| 1398 | "mtd": "MTD", |
| 1399 | "ext4": "EMMC", |
| 1400 | "emmc": "EMMC", |
| Mohamad Ayyash | 95e74c1 | 2015-05-01 15:39:36 -0700 | [diff] [blame] | 1401 | "f2fs": "EMMC", |
| 1402 | "squashfs": "EMMC" |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1403 | } |
| Doug Zongker | 96a57e7 | 2010-09-26 14:57:41 -0700 | [diff] [blame] | 1404 | |
| 1405 | def GetTypeAndDevice(mount_point, info): |
| 1406 | fstab = info["fstab"] |
| 1407 | if fstab: |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1408 | return (PARTITION_TYPES[fstab[mount_point].fs_type], |
| 1409 | fstab[mount_point].device) |
| Doug Zongker | 96a57e7 | 2010-09-26 14:57:41 -0700 | [diff] [blame] | 1410 | else: |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1411 | raise KeyError |
| Baligh Uddin | beb6afd | 2013-11-13 00:22:34 +0000 | [diff] [blame] | 1412 | |
| 1413 | |
| 1414 | def ParseCertificate(data): |
| 1415 | """Parse a PEM-format certificate.""" |
| 1416 | cert = [] |
| 1417 | save = False |
| 1418 | for line in data.split("\n"): |
| 1419 | if "--END CERTIFICATE--" in line: |
| 1420 | break |
| 1421 | if save: |
| 1422 | cert.append(line) |
| 1423 | if "--BEGIN CERTIFICATE--" in line: |
| 1424 | save = True |
| 1425 | cert = "".join(cert).decode('base64') |
| 1426 | return cert |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 1427 | |
| Doug Zongker | 412c02f | 2014-02-13 10:58:24 -0800 | [diff] [blame] | 1428 | def MakeRecoveryPatch(input_dir, output_sink, recovery_img, boot_img, |
| 1429 | info_dict=None): |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 1430 | """Generate a binary patch that creates the recovery image starting |
| 1431 | with the boot image. (Most of the space in these images is just the |
| 1432 | kernel, which is identical for the two, so the resulting patch |
| 1433 | should be efficient.) Add it to the output zip, along with a shell |
| 1434 | script that is run from init.rc on first boot to actually do the |
| 1435 | patching and install the new recovery image. |
| 1436 | |
| 1437 | recovery_img and boot_img should be File objects for the |
| 1438 | corresponding images. info should be the dictionary returned by |
| 1439 | common.LoadInfoDict() on the input target_files. |
| 1440 | """ |
| 1441 | |
| Doug Zongker | 412c02f | 2014-02-13 10:58:24 -0800 | [diff] [blame] | 1442 | if info_dict is None: |
| 1443 | info_dict = OPTIONS.info_dict |
| 1444 | |
| Tao Bao | f2cffbd | 2015-07-22 12:33:18 -0700 | [diff] [blame] | 1445 | full_recovery_image = info_dict.get("full_recovery_image", None) == "true" |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 1446 | system_root_image = info_dict.get("system_root_image", None) == "true" |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 1447 | |
| Tao Bao | f2cffbd | 2015-07-22 12:33:18 -0700 | [diff] [blame] | 1448 | if full_recovery_image: |
| 1449 | output_sink("etc/recovery.img", recovery_img.data) |
| 1450 | |
| 1451 | else: |
| 1452 | diff_program = ["imgdiff"] |
| 1453 | path = os.path.join(input_dir, "SYSTEM", "etc", "recovery-resource.dat") |
| 1454 | if os.path.exists(path): |
| 1455 | diff_program.append("-b") |
| 1456 | diff_program.append(path) |
| 1457 | bonus_args = "-b /system/etc/recovery-resource.dat" |
| 1458 | else: |
| 1459 | bonus_args = "" |
| 1460 | |
| 1461 | d = Difference(recovery_img, boot_img, diff_program=diff_program) |
| 1462 | _, _, patch = d.ComputePatch() |
| 1463 | output_sink("recovery-from-boot.p", patch) |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 1464 | |
| Dan Albert | ebb19aa | 2015-03-27 19:11:53 -0700 | [diff] [blame] | 1465 | try: |
| 1466 | boot_type, boot_device = GetTypeAndDevice("/boot", info_dict) |
| 1467 | recovery_type, recovery_device = GetTypeAndDevice("/recovery", info_dict) |
| 1468 | except KeyError: |
| Ying Wang | a961a09 | 2014-07-29 11:42:37 -0700 | [diff] [blame] | 1469 | return |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 1470 | |
| Tao Bao | f2cffbd | 2015-07-22 12:33:18 -0700 | [diff] [blame] | 1471 | if full_recovery_image: |
| 1472 | sh = """#!/system/bin/sh |
| 1473 | if ! applypatch -c %(type)s:%(device)s:%(size)d:%(sha1)s; then |
| 1474 | applypatch /system/etc/recovery.img %(type)s:%(device)s %(sha1)s %(size)d && log -t recovery "Installing new recovery image: succeeded" || log -t recovery "Installing new recovery image: failed" |
| 1475 | else |
| 1476 | log -t recovery "Recovery image already installed" |
| 1477 | fi |
| 1478 | """ % {'type': recovery_type, |
| 1479 | 'device': recovery_device, |
| 1480 | 'sha1': recovery_img.sha1, |
| 1481 | 'size': recovery_img.size} |
| 1482 | else: |
| 1483 | sh = """#!/system/bin/sh |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 1484 | if ! applypatch -c %(recovery_type)s:%(recovery_device)s:%(recovery_size)d:%(recovery_sha1)s; then |
| 1485 | applypatch %(bonus_args)s %(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 && log -t recovery "Installing new recovery image: succeeded" || log -t recovery "Installing new recovery image: failed" |
| 1486 | else |
| 1487 | log -t recovery "Recovery image already installed" |
| 1488 | fi |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1489 | """ % {'boot_size': boot_img.size, |
| 1490 | 'boot_sha1': boot_img.sha1, |
| 1491 | 'recovery_size': recovery_img.size, |
| 1492 | 'recovery_sha1': recovery_img.sha1, |
| 1493 | 'boot_type': boot_type, |
| 1494 | 'boot_device': boot_device, |
| 1495 | 'recovery_type': recovery_type, |
| 1496 | 'recovery_device': recovery_device, |
| 1497 | 'bonus_args': bonus_args} |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 1498 | |
| 1499 | # The install script location moved from /system/etc to /system/bin |
| Tao Bao | 9f0c8df | 2015-07-07 18:31:47 -0700 | [diff] [blame] | 1500 | # in the L release. Parse init.*.rc files to find out where the |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 1501 | # target-files expects it to be, and put it there. |
| 1502 | sh_location = "etc/install-recovery.sh" |
| Tao Bao | 9f0c8df | 2015-07-07 18:31:47 -0700 | [diff] [blame] | 1503 | found = False |
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 1504 | if system_root_image: |
| 1505 | init_rc_dir = os.path.join(input_dir, "ROOT") |
| 1506 | else: |
| 1507 | init_rc_dir = os.path.join(input_dir, "BOOT", "RAMDISK") |
| Tao Bao | 9f0c8df | 2015-07-07 18:31:47 -0700 | [diff] [blame] | 1508 | init_rc_files = os.listdir(init_rc_dir) |
| 1509 | for init_rc_file in init_rc_files: |
| 1510 | if (not init_rc_file.startswith('init.') or |
| 1511 | not init_rc_file.endswith('.rc')): |
| 1512 | continue |
| 1513 | |
| 1514 | with open(os.path.join(init_rc_dir, init_rc_file)) as f: |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 1515 | for line in f: |
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1516 | m = re.match(r"^service flash_recovery /system/(\S+)\s*$", line) |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 1517 | if m: |
| 1518 | sh_location = m.group(1) |
| Tao Bao | 9f0c8df | 2015-07-07 18:31:47 -0700 | [diff] [blame] | 1519 | found = True |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 1520 | break |
| Tao Bao | 9f0c8df | 2015-07-07 18:31:47 -0700 | [diff] [blame] | 1521 | |
| 1522 | if found: |
| 1523 | break |
| 1524 | |
| 1525 | print "putting script in", sh_location |
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 1526 | |
| 1527 | output_sink(sh_location, sh) |