| 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 |  | 
| Tao Bao | 89fbb0f | 2017-01-10 10:47:58 -0800 | [diff] [blame] | 15 | from __future__ import print_function | 
|  | 16 |  | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 17 | import collections | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 18 | import copy | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 19 | import errno | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 20 | import getopt | 
|  | 21 | import getpass | 
| Narayan Kamath | a07bf04 | 2017-08-14 14:49:21 +0100 | [diff] [blame] | 22 | import gzip | 
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 23 | import imp | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 24 | import json | 
|  | 25 | import logging | 
|  | 26 | import logging.config | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 27 | import os | 
| Ying Wang | 7e6d4e4 | 2010-12-13 16:25:36 -0800 | [diff] [blame] | 28 | import platform | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 29 | import re | 
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 30 | import shlex | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 31 | import shutil | 
| Tao Bao | c765cca | 2018-01-31 17:32:40 -0800 | [diff] [blame] | 32 | import string | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 33 | import subprocess | 
|  | 34 | import sys | 
|  | 35 | import tempfile | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 36 | import threading | 
|  | 37 | import time | 
| Doug Zongker | 048e7ca | 2009-06-15 14:31:53 -0700 | [diff] [blame] | 38 | import zipfile | 
| Tao Bao | 12d87fc | 2018-01-31 12:18:52 -0800 | [diff] [blame] | 39 | from hashlib import sha1, sha256 | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 40 |  | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 41 | import blockimgdiff | 
| Tao Bao | c765cca | 2018-01-31 17:32:40 -0800 | [diff] [blame] | 42 | import sparse_img | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 43 |  | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 44 | logger = logging.getLogger(__name__) | 
|  | 45 |  | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 46 |  | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 47 | class Options(object): | 
|  | 48 | def __init__(self): | 
|  | 49 | platform_search_path = { | 
|  | 50 | "linux2": "out/host/linux-x86", | 
|  | 51 | "darwin": "out/host/darwin-x86", | 
| Doug Zongker | 8544877 | 2014-09-09 14:59:20 -0700 | [diff] [blame] | 52 | } | 
| Doug Zongker | 8544877 | 2014-09-09 14:59:20 -0700 | [diff] [blame] | 53 |  | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 54 | self.search_path = platform_search_path.get(sys.platform) | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 55 | self.signapk_path = "framework/signapk.jar"  # Relative to search_path | 
| Alex Klyubin | 9667b18 | 2015-12-10 13:38:50 -0800 | [diff] [blame] | 56 | self.signapk_shared_library_path = "lib64"   # Relative to search_path | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 57 | self.extra_signapk_args = [] | 
|  | 58 | self.java_path = "java"  # Use the one on the path by default. | 
| Tao Bao | e95540e | 2016-11-08 12:08:53 -0800 | [diff] [blame] | 59 | self.java_args = ["-Xmx2048m"]  # The default JVM args. | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 60 | self.public_key_suffix = ".x509.pem" | 
|  | 61 | self.private_key_suffix = ".pk8" | 
| Dan Albert | cd9ecc0 | 2015-03-27 16:37:23 -0700 | [diff] [blame] | 62 | # use otatools built boot_signer by default | 
|  | 63 | self.boot_signer_path = "boot_signer" | 
| Baligh Uddin | 601ddea | 2015-06-09 15:48:14 -0700 | [diff] [blame] | 64 | self.boot_signer_args = [] | 
|  | 65 | self.verity_signer_path = None | 
|  | 66 | self.verity_signer_args = [] | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 67 | self.verbose = False | 
|  | 68 | self.tempfiles = [] | 
|  | 69 | self.device_specific = None | 
|  | 70 | self.extras = {} | 
|  | 71 | self.info_dict = None | 
| Tao Bao | 6f0b219 | 2015-10-13 16:37:12 -0700 | [diff] [blame] | 72 | self.source_info_dict = None | 
|  | 73 | self.target_info_dict = None | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 74 | self.worker_threads = None | 
| Tao Bao | 575d68a | 2015-08-07 19:49:45 -0700 | [diff] [blame] | 75 | # Stash size cannot exceed cache_size * threshold. | 
|  | 76 | self.cache_size = None | 
|  | 77 | self.stash_threshold = 0.8 | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 78 |  | 
|  | 79 |  | 
|  | 80 | OPTIONS = Options() | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 81 |  | 
| Tao Bao | 7119751 | 2018-10-11 14:08:45 -0700 | [diff] [blame] | 82 | # The block size that's used across the releasetools scripts. | 
|  | 83 | BLOCK_SIZE = 4096 | 
|  | 84 |  | 
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 85 | # Values for "certificate" in apkcerts that mean special things. | 
|  | 86 | SPECIAL_CERT_STRINGS = ("PRESIGNED", "EXTERNAL") | 
|  | 87 |  | 
| Tao Bao | 9dd909e | 2017-11-14 11:27:32 -0800 | [diff] [blame] | 88 | # The partitions allowed to be signed by AVB (Android verified boot 2.0). | 
| Dario Freni | 5f681e1 | 2018-05-29 13:09:01 +0100 | [diff] [blame] | 89 | AVB_PARTITIONS = ('boot', 'recovery', 'system', 'vendor', 'product', | 
| Dario Freni | 924af7d | 2018-08-17 00:56:14 +0100 | [diff] [blame] | 90 | 'product_services', 'dtbo', 'odm') | 
| Tao Bao | 9dd909e | 2017-11-14 11:27:32 -0800 | [diff] [blame] | 91 |  | 
| Tianjie Xu | 861f413 | 2018-09-12 11:49:33 -0700 | [diff] [blame] | 92 | # Partitions that should have their care_map added to META/care_map.pb | 
|  | 93 | PARTITIONS_WITH_CARE_MAP = ('system', 'vendor', 'product', 'product_services', | 
|  | 94 | 'odm') | 
|  | 95 |  | 
|  | 96 |  | 
| Tianjie Xu | 209db46 | 2016-05-24 17:34:52 -0700 | [diff] [blame] | 97 | class ErrorCode(object): | 
|  | 98 | """Define error_codes for failures that happen during the actual | 
|  | 99 | update package installation. | 
|  | 100 |  | 
|  | 101 | Error codes 0-999 are reserved for failures before the package | 
|  | 102 | installation (i.e. low battery, package verification failure). | 
|  | 103 | Detailed code in 'bootable/recovery/error_code.h' """ | 
|  | 104 |  | 
|  | 105 | SYSTEM_VERIFICATION_FAILURE = 1000 | 
|  | 106 | SYSTEM_UPDATE_FAILURE = 1001 | 
|  | 107 | SYSTEM_UNEXPECTED_CONTENTS = 1002 | 
|  | 108 | SYSTEM_NONZERO_CONTENTS = 1003 | 
|  | 109 | SYSTEM_RECOVER_FAILURE = 1004 | 
|  | 110 | VENDOR_VERIFICATION_FAILURE = 2000 | 
|  | 111 | VENDOR_UPDATE_FAILURE = 2001 | 
|  | 112 | VENDOR_UNEXPECTED_CONTENTS = 2002 | 
|  | 113 | VENDOR_NONZERO_CONTENTS = 2003 | 
|  | 114 | VENDOR_RECOVER_FAILURE = 2004 | 
|  | 115 | OEM_PROP_MISMATCH = 3000 | 
|  | 116 | FINGERPRINT_MISMATCH = 3001 | 
|  | 117 | THUMBPRINT_MISMATCH = 3002 | 
|  | 118 | OLDER_BUILD = 3003 | 
|  | 119 | DEVICE_MISMATCH = 3004 | 
|  | 120 | BAD_PATCH_FILE = 3005 | 
|  | 121 | INSUFFICIENT_CACHE_SPACE = 3006 | 
|  | 122 | TUNE_PARTITION_FAILURE = 3007 | 
|  | 123 | APPLY_PATCH_FAILURE = 3008 | 
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 124 |  | 
| Tao Bao | 8092198 | 2018-03-21 21:02:19 -0700 | [diff] [blame] | 125 |  | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 126 | class ExternalError(RuntimeError): | 
|  | 127 | pass | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 128 |  | 
|  | 129 |  | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 130 | def InitLogging(): | 
|  | 131 | DEFAULT_LOGGING_CONFIG = { | 
|  | 132 | 'version': 1, | 
|  | 133 | 'disable_existing_loggers': False, | 
|  | 134 | 'formatters': { | 
|  | 135 | 'standard': { | 
|  | 136 | 'format': | 
|  | 137 | '%(asctime)s - %(filename)s - %(levelname)-8s: %(message)s', | 
|  | 138 | 'datefmt': '%Y-%m-%d %H:%M:%S', | 
|  | 139 | }, | 
|  | 140 | }, | 
|  | 141 | 'handlers': { | 
|  | 142 | 'default': { | 
|  | 143 | 'class': 'logging.StreamHandler', | 
|  | 144 | 'formatter': 'standard', | 
|  | 145 | }, | 
|  | 146 | }, | 
|  | 147 | 'loggers': { | 
|  | 148 | '': { | 
|  | 149 | 'handlers': ['default'], | 
|  | 150 | 'level': 'WARNING', | 
|  | 151 | 'propagate': True, | 
|  | 152 | } | 
|  | 153 | } | 
|  | 154 | } | 
|  | 155 | env_config = os.getenv('LOGGING_CONFIG') | 
|  | 156 | if env_config: | 
|  | 157 | with open(env_config) as f: | 
|  | 158 | config = json.load(f) | 
|  | 159 | else: | 
|  | 160 | config = DEFAULT_LOGGING_CONFIG | 
|  | 161 |  | 
|  | 162 | # Increase the logging level for verbose mode. | 
|  | 163 | if OPTIONS.verbose: | 
|  | 164 | config = copy.deepcopy(DEFAULT_LOGGING_CONFIG) | 
|  | 165 | config['loggers']['']['level'] = 'INFO' | 
|  | 166 |  | 
|  | 167 | logging.config.dictConfig(config) | 
|  | 168 |  | 
|  | 169 |  | 
| Tao Bao | 3945158 | 2017-05-04 11:10:47 -0700 | [diff] [blame] | 170 | def Run(args, verbose=None, **kwargs): | 
| Tao Bao | 73dd4f4 | 2018-10-04 16:25:33 -0700 | [diff] [blame] | 171 | """Creates and returns a subprocess.Popen object. | 
| Tao Bao | 3945158 | 2017-05-04 11:10:47 -0700 | [diff] [blame] | 172 |  | 
| Tao Bao | 73dd4f4 | 2018-10-04 16:25:33 -0700 | [diff] [blame] | 173 | Args: | 
|  | 174 | args: The command represented as a list of strings. | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 175 | verbose: Whether the commands should be shown. Default to the global | 
|  | 176 | verbosity if unspecified. | 
| Tao Bao | 73dd4f4 | 2018-10-04 16:25:33 -0700 | [diff] [blame] | 177 | kwargs: Any additional args to be passed to subprocess.Popen(), such as env, | 
|  | 178 | stdin, etc. stdout and stderr will default to subprocess.PIPE and | 
|  | 179 | subprocess.STDOUT respectively unless caller specifies any of them. | 
|  | 180 |  | 
|  | 181 | Returns: | 
|  | 182 | A subprocess.Popen object. | 
| Tao Bao | 3945158 | 2017-05-04 11:10:47 -0700 | [diff] [blame] | 183 | """ | 
| Tao Bao | 73dd4f4 | 2018-10-04 16:25:33 -0700 | [diff] [blame] | 184 | if 'stdout' not in kwargs and 'stderr' not in kwargs: | 
|  | 185 | kwargs['stdout'] = subprocess.PIPE | 
|  | 186 | kwargs['stderr'] = subprocess.STDOUT | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 187 | # Don't log any if caller explicitly says so. | 
|  | 188 | if verbose != False: | 
|  | 189 | logger.info("  Running: \"%s\"", " ".join(args)) | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 190 | return subprocess.Popen(args, **kwargs) | 
|  | 191 |  | 
|  | 192 |  | 
| Bill Peckham | e9eb5f9 | 2019-02-01 15:52:10 -0800 | [diff] [blame] | 193 | def RunAndWait(args, verbose=None, **kwargs): | 
| Bill Peckham | 889b0c6 | 2019-02-21 18:53:37 -0800 | [diff] [blame] | 194 | """Runs the given command waiting for it to complete. | 
| Bill Peckham | e9eb5f9 | 2019-02-01 15:52:10 -0800 | [diff] [blame] | 195 |  | 
|  | 196 | Args: | 
|  | 197 | args: The command represented as a list of strings. | 
|  | 198 | verbose: Whether the commands should be shown. Default to the global | 
|  | 199 | verbosity if unspecified. | 
|  | 200 | kwargs: Any additional args to be passed to subprocess.Popen(), such as env, | 
|  | 201 | stdin, etc. stdout and stderr will default to subprocess.PIPE and | 
|  | 202 | subprocess.STDOUT respectively unless caller specifies any of them. | 
|  | 203 |  | 
| Bill Peckham | 889b0c6 | 2019-02-21 18:53:37 -0800 | [diff] [blame] | 204 | Raises: | 
|  | 205 | ExternalError: On non-zero exit from the command. | 
| Bill Peckham | e9eb5f9 | 2019-02-01 15:52:10 -0800 | [diff] [blame] | 206 | """ | 
|  | 207 | proc = Run(args, verbose=verbose, **kwargs) | 
|  | 208 | proc.wait() | 
| Bill Peckham | 889b0c6 | 2019-02-21 18:53:37 -0800 | [diff] [blame] | 209 |  | 
|  | 210 | if proc.returncode != 0: | 
|  | 211 | raise ExternalError( | 
|  | 212 | "Failed to run command '{}' (exit code {})".format( | 
|  | 213 | args, proc.returncode)) | 
| Bill Peckham | e9eb5f9 | 2019-02-01 15:52:10 -0800 | [diff] [blame] | 214 |  | 
|  | 215 |  | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 216 | def RunAndCheckOutput(args, verbose=None, **kwargs): | 
|  | 217 | """Runs the given command and returns the output. | 
|  | 218 |  | 
|  | 219 | Args: | 
|  | 220 | args: The command represented as a list of strings. | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 221 | verbose: Whether the commands should be shown. Default to the global | 
|  | 222 | verbosity if unspecified. | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 223 | kwargs: Any additional args to be passed to subprocess.Popen(), such as env, | 
|  | 224 | stdin, etc. stdout and stderr will default to subprocess.PIPE and | 
|  | 225 | subprocess.STDOUT respectively unless caller specifies any of them. | 
|  | 226 |  | 
|  | 227 | Returns: | 
|  | 228 | The output string. | 
|  | 229 |  | 
|  | 230 | Raises: | 
|  | 231 | ExternalError: On non-zero exit from the command. | 
|  | 232 | """ | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 233 | proc = Run(args, verbose=verbose, **kwargs) | 
|  | 234 | output, _ = proc.communicate() | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 235 | # Don't log any if caller explicitly says so. | 
|  | 236 | if verbose != False: | 
|  | 237 | logger.info("%s", output.rstrip()) | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 238 | if proc.returncode != 0: | 
|  | 239 | raise ExternalError( | 
|  | 240 | "Failed to run command '{}' (exit code {}):\n{}".format( | 
|  | 241 | args, proc.returncode, output)) | 
|  | 242 | return output | 
|  | 243 |  | 
|  | 244 |  | 
| Tao Bao | c765cca | 2018-01-31 17:32:40 -0800 | [diff] [blame] | 245 | def RoundUpTo4K(value): | 
|  | 246 | rounded_up = value + 4095 | 
|  | 247 | return rounded_up - (rounded_up % 4096) | 
|  | 248 |  | 
|  | 249 |  | 
| Ying Wang | 7e6d4e4 | 2010-12-13 16:25:36 -0800 | [diff] [blame] | 250 | def CloseInheritedPipes(): | 
|  | 251 | """ Gmake in MAC OS has file descriptor (PIPE) leak. We close those fds | 
|  | 252 | before doing other work.""" | 
|  | 253 | if platform.system() != "Darwin": | 
|  | 254 | return | 
|  | 255 | for d in range(3, 1025): | 
|  | 256 | try: | 
|  | 257 | stat = os.fstat(d) | 
|  | 258 | if stat is not None: | 
|  | 259 | pipebit = stat[0] & 0x1000 | 
|  | 260 | if pipebit != 0: | 
|  | 261 | os.close(d) | 
|  | 262 | except OSError: | 
|  | 263 | pass | 
|  | 264 |  | 
|  | 265 |  | 
| Tao Bao | 410ad8b | 2018-08-24 12:08:38 -0700 | [diff] [blame] | 266 | def LoadInfoDict(input_file, repacking=False): | 
|  | 267 | """Loads the key/value pairs from the given input target_files. | 
|  | 268 |  | 
|  | 269 | It reads `META/misc_info.txt` file in the target_files input, does sanity | 
|  | 270 | checks and returns the parsed key/value pairs for to the given build. It's | 
|  | 271 | usually called early when working on input target_files files, e.g. when | 
|  | 272 | generating OTAs, or signing builds. Note that the function may be called | 
|  | 273 | against an old target_files file (i.e. from past dessert releases). So the | 
|  | 274 | property parsing needs to be backward compatible. | 
|  | 275 |  | 
|  | 276 | In a `META/misc_info.txt`, a few properties are stored as links to the files | 
|  | 277 | in the PRODUCT_OUT directory. It works fine with the build system. However, | 
|  | 278 | they are no longer available when (re)generating images from target_files zip. | 
|  | 279 | When `repacking` is True, redirect these properties to the actual files in the | 
|  | 280 | unzipped directory. | 
|  | 281 |  | 
|  | 282 | Args: | 
|  | 283 | input_file: The input target_files file, which could be an open | 
|  | 284 | zipfile.ZipFile instance, or a str for the dir that contains the files | 
|  | 285 | unzipped from a target_files file. | 
|  | 286 | repacking: Whether it's trying repack an target_files file after loading the | 
|  | 287 | info dict (default: False). If so, it will rewrite a few loaded | 
|  | 288 | properties (e.g. selinux_fc, root_dir) to point to the actual files in | 
|  | 289 | target_files file. When doing repacking, `input_file` must be a dir. | 
|  | 290 |  | 
|  | 291 | Returns: | 
|  | 292 | A dict that contains the parsed key/value pairs. | 
|  | 293 |  | 
|  | 294 | Raises: | 
|  | 295 | AssertionError: On invalid input arguments. | 
|  | 296 | ValueError: On malformed input values. | 
|  | 297 | """ | 
|  | 298 | if repacking: | 
|  | 299 | assert isinstance(input_file, str), \ | 
|  | 300 | "input_file must be a path str when doing repacking" | 
| Doug Zongker | c19a8d5 | 2010-07-01 15:30:11 -0700 | [diff] [blame] | 301 |  | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 302 | def read_helper(fn): | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 303 | if isinstance(input_file, zipfile.ZipFile): | 
|  | 304 | return input_file.read(fn) | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 305 | else: | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 306 | path = os.path.join(input_file, *fn.split("/")) | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 307 | try: | 
|  | 308 | with open(path) as f: | 
|  | 309 | return f.read() | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 310 | except IOError as e: | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 311 | if e.errno == errno.ENOENT: | 
|  | 312 | raise KeyError(fn) | 
| Tao Bao | 6cd5473 | 2017-02-27 15:12:05 -0800 | [diff] [blame] | 313 |  | 
| Doug Zongker | c19a8d5 | 2010-07-01 15:30:11 -0700 | [diff] [blame] | 314 | try: | 
| Michael Runge | 6e83611 | 2014-04-15 17:40:21 -0700 | [diff] [blame] | 315 | d = LoadDictionaryFromLines(read_helper("META/misc_info.txt").split("\n")) | 
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 316 | except KeyError: | 
| Tao Bao | 410ad8b | 2018-08-24 12:08:38 -0700 | [diff] [blame] | 317 | raise ValueError("Failed to find META/misc_info.txt in input target-files") | 
| Doug Zongker | c19a8d5 | 2010-07-01 15:30:11 -0700 | [diff] [blame] | 318 |  | 
| Tao Bao | 410ad8b | 2018-08-24 12:08:38 -0700 | [diff] [blame] | 319 | if "recovery_api_version" not in d: | 
|  | 320 | raise ValueError("Failed to find 'recovery_api_version'") | 
|  | 321 | if "fstab_version" not in d: | 
|  | 322 | raise ValueError("Failed to find 'fstab_version'") | 
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 323 |  | 
| Tao Bao | 410ad8b | 2018-08-24 12:08:38 -0700 | [diff] [blame] | 324 | if repacking: | 
|  | 325 | # We carry a copy of file_contexts.bin under META/. If not available, search | 
|  | 326 | # BOOT/RAMDISK/. Note that sometimes we may need a different file to build | 
|  | 327 | # images than the one running on device, in that case, we must have the one | 
|  | 328 | # for image generation copied to META/. | 
| Tao Bao | 79735a6 | 2015-08-28 10:52:03 -0700 | [diff] [blame] | 329 | fc_basename = os.path.basename(d.get("selinux_fc", "file_contexts")) | 
| Tao Bao | 410ad8b | 2018-08-24 12:08:38 -0700 | [diff] [blame] | 330 | fc_config = os.path.join(input_file, "META", fc_basename) | 
| Tom Cherry | d14b895 | 2018-08-09 14:26:00 -0700 | [diff] [blame] | 331 | assert os.path.exists(fc_config) | 
| Tao Bao | 2c15d9e | 2015-07-09 11:51:16 -0700 | [diff] [blame] | 332 |  | 
| Tom Cherry | d14b895 | 2018-08-09 14:26:00 -0700 | [diff] [blame] | 333 | d["selinux_fc"] = fc_config | 
| Tao Bao | 2c15d9e | 2015-07-09 11:51:16 -0700 | [diff] [blame] | 334 |  | 
| Tom Cherry | d14b895 | 2018-08-09 14:26:00 -0700 | [diff] [blame] | 335 | # Similarly we need to redirect "root_dir", and "root_fs_config". | 
| Tao Bao | 410ad8b | 2018-08-24 12:08:38 -0700 | [diff] [blame] | 336 | d["root_dir"] = os.path.join(input_file, "ROOT") | 
| Tom Cherry | d14b895 | 2018-08-09 14:26:00 -0700 | [diff] [blame] | 337 | d["root_fs_config"] = os.path.join( | 
| Tao Bao | 410ad8b | 2018-08-24 12:08:38 -0700 | [diff] [blame] | 338 | input_file, "META", "root_filesystem_config.txt") | 
| Tao Bao | 84e7568 | 2015-07-19 02:38:53 -0700 | [diff] [blame] | 339 |  | 
| Tao Bao | f54216f | 2016-03-29 15:12:37 -0700 | [diff] [blame] | 340 | # Redirect {system,vendor}_base_fs_file. | 
|  | 341 | if "system_base_fs_file" in d: | 
|  | 342 | basename = os.path.basename(d["system_base_fs_file"]) | 
| Tao Bao | 410ad8b | 2018-08-24 12:08:38 -0700 | [diff] [blame] | 343 | system_base_fs_file = os.path.join(input_file, "META", basename) | 
| Tao Bao | b079b50 | 2016-05-03 08:01:19 -0700 | [diff] [blame] | 344 | if os.path.exists(system_base_fs_file): | 
|  | 345 | d["system_base_fs_file"] = system_base_fs_file | 
|  | 346 | else: | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 347 | logger.warning( | 
|  | 348 | "Failed to find system base fs file: %s", system_base_fs_file) | 
| Tao Bao | b079b50 | 2016-05-03 08:01:19 -0700 | [diff] [blame] | 349 | del d["system_base_fs_file"] | 
| Tao Bao | f54216f | 2016-03-29 15:12:37 -0700 | [diff] [blame] | 350 |  | 
|  | 351 | if "vendor_base_fs_file" in d: | 
|  | 352 | basename = os.path.basename(d["vendor_base_fs_file"]) | 
| Tao Bao | 410ad8b | 2018-08-24 12:08:38 -0700 | [diff] [blame] | 353 | vendor_base_fs_file = os.path.join(input_file, "META", basename) | 
| Tao Bao | b079b50 | 2016-05-03 08:01:19 -0700 | [diff] [blame] | 354 | if os.path.exists(vendor_base_fs_file): | 
|  | 355 | d["vendor_base_fs_file"] = vendor_base_fs_file | 
|  | 356 | else: | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 357 | logger.warning( | 
|  | 358 | "Failed to find vendor base fs file: %s", vendor_base_fs_file) | 
| Tao Bao | b079b50 | 2016-05-03 08:01:19 -0700 | [diff] [blame] | 359 | del d["vendor_base_fs_file"] | 
| Tao Bao | f54216f | 2016-03-29 15:12:37 -0700 | [diff] [blame] | 360 |  | 
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 361 | def makeint(key): | 
|  | 362 | if key in d: | 
|  | 363 | d[key] = int(d[key], 0) | 
|  | 364 |  | 
|  | 365 | makeint("recovery_api_version") | 
|  | 366 | makeint("blocksize") | 
|  | 367 | makeint("system_size") | 
| Daniel Rosenberg | f4eabc3 | 2014-07-10 15:42:38 -0700 | [diff] [blame] | 368 | makeint("vendor_size") | 
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 369 | makeint("userdata_size") | 
| Ying Wang | 9f8e8db | 2011-11-04 11:37:01 -0700 | [diff] [blame] | 370 | makeint("cache_size") | 
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 371 | makeint("recovery_size") | 
|  | 372 | makeint("boot_size") | 
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 373 | makeint("fstab_version") | 
| Doug Zongker | c19a8d5 | 2010-07-01 15:30:11 -0700 | [diff] [blame] | 374 |  | 
| Tao Bao | a57ab9f | 2018-08-24 12:08:38 -0700 | [diff] [blame] | 375 | # We changed recovery.fstab path in Q, from ../RAMDISK/etc/recovery.fstab to | 
|  | 376 | # ../RAMDISK/system/etc/recovery.fstab. LoadInfoDict() has to handle both | 
|  | 377 | # cases, since it may load the info_dict from an old build (e.g. when | 
|  | 378 | # generating incremental OTAs from that build). | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 379 | system_root_image = d.get("system_root_image") == "true" | 
|  | 380 | if d.get("no_recovery") != "true": | 
| Tao Bao | 696bb33 | 2018-08-17 16:27:01 -0700 | [diff] [blame] | 381 | recovery_fstab_path = "RECOVERY/RAMDISK/system/etc/recovery.fstab" | 
| Tao Bao | b4adc06 | 2018-08-22 18:27:14 -0700 | [diff] [blame] | 382 | if isinstance(input_file, zipfile.ZipFile): | 
|  | 383 | if recovery_fstab_path not in input_file.namelist(): | 
|  | 384 | recovery_fstab_path = "RECOVERY/RAMDISK/etc/recovery.fstab" | 
|  | 385 | else: | 
|  | 386 | path = os.path.join(input_file, *recovery_fstab_path.split("/")) | 
|  | 387 | if not os.path.exists(path): | 
|  | 388 | recovery_fstab_path = "RECOVERY/RAMDISK/etc/recovery.fstab" | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 389 | d["fstab"] = LoadRecoveryFSTab( | 
|  | 390 | read_helper, d["fstab_version"], recovery_fstab_path, system_root_image) | 
| Tao Bao | b4adc06 | 2018-08-22 18:27:14 -0700 | [diff] [blame] | 391 |  | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 392 | elif d.get("recovery_as_boot") == "true": | 
| Tao Bao | 696bb33 | 2018-08-17 16:27:01 -0700 | [diff] [blame] | 393 | recovery_fstab_path = "BOOT/RAMDISK/system/etc/recovery.fstab" | 
| Tao Bao | b4adc06 | 2018-08-22 18:27:14 -0700 | [diff] [blame] | 394 | if isinstance(input_file, zipfile.ZipFile): | 
|  | 395 | if recovery_fstab_path not in input_file.namelist(): | 
|  | 396 | recovery_fstab_path = "BOOT/RAMDISK/etc/recovery.fstab" | 
|  | 397 | else: | 
|  | 398 | path = os.path.join(input_file, *recovery_fstab_path.split("/")) | 
|  | 399 | if not os.path.exists(path): | 
|  | 400 | recovery_fstab_path = "BOOT/RAMDISK/etc/recovery.fstab" | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 401 | d["fstab"] = LoadRecoveryFSTab( | 
|  | 402 | read_helper, d["fstab_version"], recovery_fstab_path, system_root_image) | 
| Tao Bao | b4adc06 | 2018-08-22 18:27:14 -0700 | [diff] [blame] | 403 |  | 
| Tianjie Xu | cfa8622 | 2016-03-07 16:31:19 -0800 | [diff] [blame] | 404 | else: | 
|  | 405 | d["fstab"] = None | 
|  | 406 |  | 
| Tianjie Xu | 861f413 | 2018-09-12 11:49:33 -0700 | [diff] [blame] | 407 | # Tries to load the build props for all partitions with care_map, including | 
|  | 408 | # system and vendor. | 
|  | 409 | for partition in PARTITIONS_WITH_CARE_MAP: | 
|  | 410 | d["{}.build.prop".format(partition)] = LoadBuildProp( | 
|  | 411 | read_helper, "{}/build.prop".format(partition.upper())) | 
|  | 412 | d["build.prop"] = d["system.build.prop"] | 
| Tao Bao | 12d87fc | 2018-01-31 12:18:52 -0800 | [diff] [blame] | 413 |  | 
|  | 414 | # Set up the salt (based on fingerprint or thumbprint) that will be used when | 
|  | 415 | # adding AVB footer. | 
|  | 416 | if d.get("avb_enable") == "true": | 
|  | 417 | fp = None | 
|  | 418 | if "build.prop" in d: | 
|  | 419 | build_prop = d["build.prop"] | 
|  | 420 | if "ro.build.fingerprint" in build_prop: | 
|  | 421 | fp = build_prop["ro.build.fingerprint"] | 
|  | 422 | elif "ro.build.thumbprint" in build_prop: | 
|  | 423 | fp = build_prop["ro.build.thumbprint"] | 
|  | 424 | if fp: | 
|  | 425 | d["avb_salt"] = sha256(fp).hexdigest() | 
|  | 426 |  | 
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 427 | return d | 
|  | 428 |  | 
| Tao Bao | d1de6f3 | 2017-03-01 16:38:48 -0800 | [diff] [blame] | 429 |  | 
| Tao Bao | bcd1d16 | 2017-08-26 13:10:26 -0700 | [diff] [blame] | 430 | def LoadBuildProp(read_helper, prop_file): | 
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 431 | try: | 
| Tao Bao | bcd1d16 | 2017-08-26 13:10:26 -0700 | [diff] [blame] | 432 | data = read_helper(prop_file) | 
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 433 | except KeyError: | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 434 | logger.warning("Failed to read %s", prop_file) | 
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 435 | data = "" | 
| Michael Runge | 6e83611 | 2014-04-15 17:40:21 -0700 | [diff] [blame] | 436 | return LoadDictionaryFromLines(data.split("\n")) | 
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 437 |  | 
| Tao Bao | d1de6f3 | 2017-03-01 16:38:48 -0800 | [diff] [blame] | 438 |  | 
| Michael Runge | 6e83611 | 2014-04-15 17:40:21 -0700 | [diff] [blame] | 439 | def LoadDictionaryFromLines(lines): | 
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 440 | d = {} | 
| Michael Runge | 6e83611 | 2014-04-15 17:40:21 -0700 | [diff] [blame] | 441 | for line in lines: | 
| Doug Zongker | 1eb74dd | 2012-08-16 16:19:00 -0700 | [diff] [blame] | 442 | line = line.strip() | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 443 | if not line or line.startswith("#"): | 
|  | 444 | continue | 
| Ying Wang | 114b46f | 2014-04-15 11:24:00 -0700 | [diff] [blame] | 445 | if "=" in line: | 
|  | 446 | name, value = line.split("=", 1) | 
|  | 447 | d[name] = value | 
| Doug Zongker | c19a8d5 | 2010-07-01 15:30:11 -0700 | [diff] [blame] | 448 | return d | 
|  | 449 |  | 
| Tao Bao | d1de6f3 | 2017-03-01 16:38:48 -0800 | [diff] [blame] | 450 |  | 
| Tianjie Xu | cfa8622 | 2016-03-07 16:31:19 -0800 | [diff] [blame] | 451 | def LoadRecoveryFSTab(read_helper, fstab_version, recovery_fstab_path, | 
|  | 452 | system_root_image=False): | 
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 453 | class Partition(object): | 
| Tao Bao | d1de6f3 | 2017-03-01 16:38:48 -0800 | [diff] [blame] | 454 | def __init__(self, mount_point, fs_type, device, length, context): | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 455 | self.mount_point = mount_point | 
|  | 456 | self.fs_type = fs_type | 
|  | 457 | self.device = device | 
|  | 458 | self.length = length | 
| Tao Bao | 548eb76 | 2015-06-10 12:32:41 -0700 | [diff] [blame] | 459 | self.context = context | 
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 460 |  | 
|  | 461 | try: | 
| Tianjie Xu | cfa8622 | 2016-03-07 16:31:19 -0800 | [diff] [blame] | 462 | data = read_helper(recovery_fstab_path) | 
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 463 | except KeyError: | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 464 | logger.warning("Failed to find %s", recovery_fstab_path) | 
| Jeff Davidson | 033fbe2 | 2011-10-26 18:08:09 -0700 | [diff] [blame] | 465 | data = "" | 
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 466 |  | 
| Tao Bao | d1de6f3 | 2017-03-01 16:38:48 -0800 | [diff] [blame] | 467 | assert fstab_version == 2 | 
|  | 468 |  | 
|  | 469 | d = {} | 
|  | 470 | for line in data.split("\n"): | 
|  | 471 | line = line.strip() | 
|  | 472 | if not line or line.startswith("#"): | 
|  | 473 | continue | 
|  | 474 |  | 
|  | 475 | # <src> <mnt_point> <type> <mnt_flags and options> <fs_mgr_flags> | 
|  | 476 | pieces = line.split() | 
|  | 477 | if len(pieces) != 5: | 
|  | 478 | raise ValueError("malformed recovery.fstab line: \"%s\"" % (line,)) | 
|  | 479 |  | 
|  | 480 | # Ignore entries that are managed by vold. | 
|  | 481 | options = pieces[4] | 
|  | 482 | if "voldmanaged=" in options: | 
|  | 483 | continue | 
|  | 484 |  | 
|  | 485 | # It's a good line, parse it. | 
|  | 486 | length = 0 | 
|  | 487 | options = options.split(",") | 
|  | 488 | for i in options: | 
|  | 489 | if i.startswith("length="): | 
|  | 490 | length = int(i[7:]) | 
| Doug Zongker | 086cbb0 | 2011-02-17 15:54:20 -0800 | [diff] [blame] | 491 | else: | 
| Tao Bao | d1de6f3 | 2017-03-01 16:38:48 -0800 | [diff] [blame] | 492 | # Ignore all unknown options in the unified fstab. | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 493 | continue | 
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 494 |  | 
| Tao Bao | d1de6f3 | 2017-03-01 16:38:48 -0800 | [diff] [blame] | 495 | mount_flags = pieces[3] | 
|  | 496 | # Honor the SELinux context if present. | 
|  | 497 | context = None | 
|  | 498 | for i in mount_flags.split(","): | 
|  | 499 | if i.startswith("context="): | 
|  | 500 | context = i | 
| Doug Zongker | 086cbb0 | 2011-02-17 15:54:20 -0800 | [diff] [blame] | 501 |  | 
| Tao Bao | d1de6f3 | 2017-03-01 16:38:48 -0800 | [diff] [blame] | 502 | mount_point = pieces[1] | 
|  | 503 | d[mount_point] = Partition(mount_point=mount_point, fs_type=pieces[2], | 
|  | 504 | device=pieces[0], length=length, context=context) | 
| Ken Sumrall | 3b07cf1 | 2013-02-19 17:35:29 -0800 | [diff] [blame] | 505 |  | 
| Daniel Rosenberg | e6853b0 | 2015-06-05 17:59:27 -0700 | [diff] [blame] | 506 | # / 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] | 507 | # system. Other areas assume system is always at "/system" so point /system | 
|  | 508 | # at /. | 
| Daniel Rosenberg | e6853b0 | 2015-06-05 17:59:27 -0700 | [diff] [blame] | 509 | if system_root_image: | 
|  | 510 | assert not d.has_key("/system") and d.has_key("/") | 
|  | 511 | d["/system"] = d["/"] | 
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 512 | return d | 
|  | 513 |  | 
|  | 514 |  | 
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 515 | def DumpInfoDict(d): | 
|  | 516 | for k, v in sorted(d.items()): | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 517 | logger.info("%-25s = (%s) %s", k, type(v).__name__, v) | 
| Doug Zongker | c19a8d5 | 2010-07-01 15:30:11 -0700 | [diff] [blame] | 518 |  | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 519 |  | 
| Bowgo Tsai | 3e599ea | 2017-05-26 18:30:04 +0800 | [diff] [blame] | 520 | def AppendAVBSigningArgs(cmd, partition): | 
|  | 521 | """Append signing arguments for avbtool.""" | 
|  | 522 | # e.g., "--key path/to/signing_key --algorithm SHA256_RSA4096" | 
|  | 523 | key_path = OPTIONS.info_dict.get("avb_" + partition + "_key_path") | 
|  | 524 | algorithm = OPTIONS.info_dict.get("avb_" + partition + "_algorithm") | 
|  | 525 | if key_path and algorithm: | 
|  | 526 | cmd.extend(["--key", key_path, "--algorithm", algorithm]) | 
| Tao Bao | 2b6dfd6 | 2017-09-27 17:17:43 -0700 | [diff] [blame] | 527 | avb_salt = OPTIONS.info_dict.get("avb_salt") | 
|  | 528 | # make_vbmeta_image doesn't like "--salt" (and it's not needed). | 
| Tao Bao | 744c4c7 | 2018-08-20 21:09:07 -0700 | [diff] [blame] | 529 | if avb_salt and not partition.startswith("vbmeta"): | 
| Tao Bao | 2b6dfd6 | 2017-09-27 17:17:43 -0700 | [diff] [blame] | 530 | cmd.extend(["--salt", avb_salt]) | 
| Bowgo Tsai | 3e599ea | 2017-05-26 18:30:04 +0800 | [diff] [blame] | 531 |  | 
|  | 532 |  | 
| Tao Bao | 02a0859 | 2018-07-22 12:40:45 -0700 | [diff] [blame] | 533 | def GetAvbChainedPartitionArg(partition, info_dict, key=None): | 
|  | 534 | """Constructs and returns the arg to build or verify a chained partition. | 
|  | 535 |  | 
|  | 536 | Args: | 
|  | 537 | partition: The partition name. | 
|  | 538 | info_dict: The info dict to look up the key info and rollback index | 
|  | 539 | location. | 
|  | 540 | key: The key to be used for building or verifying the partition. Defaults to | 
|  | 541 | the key listed in info_dict. | 
|  | 542 |  | 
|  | 543 | Returns: | 
|  | 544 | A string of form "partition:rollback_index_location:key" that can be used to | 
|  | 545 | build or verify vbmeta image. | 
| Tao Bao | 02a0859 | 2018-07-22 12:40:45 -0700 | [diff] [blame] | 546 | """ | 
|  | 547 | if key is None: | 
|  | 548 | key = info_dict["avb_" + partition + "_key_path"] | 
|  | 549 | avbtool = os.getenv('AVBTOOL') or info_dict["avb_avbtool"] | 
|  | 550 | pubkey_path = MakeTempFile(prefix="avb-", suffix=".pubkey") | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 551 | RunAndCheckOutput( | 
| Tao Bao | 73dd4f4 | 2018-10-04 16:25:33 -0700 | [diff] [blame] | 552 | [avbtool, "extract_public_key", "--key", key, "--output", pubkey_path]) | 
| Tao Bao | 02a0859 | 2018-07-22 12:40:45 -0700 | [diff] [blame] | 553 |  | 
|  | 554 | rollback_index_location = info_dict[ | 
|  | 555 | "avb_" + partition + "_rollback_index_location"] | 
|  | 556 | return "{}:{}:{}".format(partition, rollback_index_location, pubkey_path) | 
|  | 557 |  | 
|  | 558 |  | 
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 559 | def _BuildBootableImage(sourcedir, fs_config_file, info_dict=None, | 
| Tao Bao | d42e97e | 2016-11-30 12:11:57 -0800 | [diff] [blame] | 560 | has_ramdisk=False, two_step_image=False): | 
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 561 | """Build a bootable image from the specified sourcedir. | 
| Doug Zongker | e1c31ba | 2009-06-23 17:40:35 -0700 | [diff] [blame] | 562 |  | 
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 563 | Take a kernel, cmdline, and optionally a ramdisk directory from the input (in | 
| Tao Bao | d42e97e | 2016-11-30 12:11:57 -0800 | [diff] [blame] | 564 | 'sourcedir'), and turn them into a boot image. 'two_step_image' indicates if | 
|  | 565 | we are building a two-step special image (i.e. building a recovery image to | 
|  | 566 | be loaded into /boot in two-step OTAs). | 
|  | 567 |  | 
|  | 568 | Return the image data, or None if sourcedir does not appear to contains files | 
|  | 569 | for building the requested image. | 
|  | 570 | """ | 
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 571 |  | 
|  | 572 | def make_ramdisk(): | 
|  | 573 | ramdisk_img = tempfile.NamedTemporaryFile() | 
|  | 574 |  | 
|  | 575 | if os.access(fs_config_file, os.F_OK): | 
|  | 576 | cmd = ["mkbootfs", "-f", fs_config_file, | 
|  | 577 | os.path.join(sourcedir, "RAMDISK")] | 
|  | 578 | else: | 
|  | 579 | cmd = ["mkbootfs", os.path.join(sourcedir, "RAMDISK")] | 
|  | 580 | p1 = Run(cmd, stdout=subprocess.PIPE) | 
|  | 581 | p2 = Run(["minigzip"], stdin=p1.stdout, stdout=ramdisk_img.file.fileno()) | 
|  | 582 |  | 
|  | 583 | p2.wait() | 
|  | 584 | p1.wait() | 
|  | 585 | assert p1.returncode == 0, "mkbootfs of %s ramdisk failed" % (sourcedir,) | 
|  | 586 | assert p2.returncode == 0, "minigzip of %s ramdisk failed" % (sourcedir,) | 
|  | 587 |  | 
|  | 588 | return ramdisk_img | 
|  | 589 |  | 
|  | 590 | if not os.access(os.path.join(sourcedir, "kernel"), os.F_OK): | 
|  | 591 | return None | 
|  | 592 |  | 
|  | 593 | 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] | 594 | return None | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 595 |  | 
| Doug Zongker | d513160 | 2012-08-02 14:46:42 -0700 | [diff] [blame] | 596 | if info_dict is None: | 
|  | 597 | info_dict = OPTIONS.info_dict | 
|  | 598 |  | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 599 | img = tempfile.NamedTemporaryFile() | 
|  | 600 |  | 
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 601 | if has_ramdisk: | 
|  | 602 | ramdisk_img = make_ramdisk() | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 603 |  | 
| Bjorn Andersson | 612e2cd | 2012-11-25 16:53:44 -0800 | [diff] [blame] | 604 | # use MKBOOTIMG from environ, or "mkbootimg" if empty or not set | 
|  | 605 | mkbootimg = os.getenv('MKBOOTIMG') or "mkbootimg" | 
|  | 606 |  | 
|  | 607 | cmd = [mkbootimg, "--kernel", os.path.join(sourcedir, "kernel")] | 
| Doug Zongker | 38a649f | 2009-06-17 09:07:09 -0700 | [diff] [blame] | 608 |  | 
| Benoit Fradin | a45a868 | 2014-07-14 21:00:43 +0200 | [diff] [blame] | 609 | fn = os.path.join(sourcedir, "second") | 
|  | 610 | if os.access(fn, os.F_OK): | 
|  | 611 | cmd.append("--second") | 
|  | 612 | cmd.append(fn) | 
|  | 613 |  | 
| Hridya Valsaraju | 9683b2f | 2019-01-22 18:08:59 -0800 | [diff] [blame] | 614 | fn = os.path.join(sourcedir, "dtb") | 
|  | 615 | if os.access(fn, os.F_OK): | 
|  | 616 | cmd.append("--dtb") | 
|  | 617 | cmd.append(fn) | 
|  | 618 |  | 
| Doug Zongker | 171f1cd | 2009-06-15 22:36:37 -0700 | [diff] [blame] | 619 | fn = os.path.join(sourcedir, "cmdline") | 
|  | 620 | if os.access(fn, os.F_OK): | 
| Doug Zongker | 38a649f | 2009-06-17 09:07:09 -0700 | [diff] [blame] | 621 | cmd.append("--cmdline") | 
|  | 622 | cmd.append(open(fn).read().rstrip("\n")) | 
|  | 623 |  | 
|  | 624 | fn = os.path.join(sourcedir, "base") | 
|  | 625 | if os.access(fn, os.F_OK): | 
|  | 626 | cmd.append("--base") | 
|  | 627 | cmd.append(open(fn).read().rstrip("\n")) | 
|  | 628 |  | 
| Ying Wang | 4de6b5b | 2010-08-25 14:29:34 -0700 | [diff] [blame] | 629 | fn = os.path.join(sourcedir, "pagesize") | 
|  | 630 | if os.access(fn, os.F_OK): | 
|  | 631 | cmd.append("--pagesize") | 
|  | 632 | cmd.append(open(fn).read().rstrip("\n")) | 
|  | 633 |  | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 634 | args = info_dict.get("mkbootimg_args") | 
| Doug Zongker | d513160 | 2012-08-02 14:46:42 -0700 | [diff] [blame] | 635 | if args and args.strip(): | 
| Jianxun Zhang | 0984949 | 2013-04-17 15:19:19 -0700 | [diff] [blame] | 636 | cmd.extend(shlex.split(args)) | 
| Doug Zongker | d513160 | 2012-08-02 14:46:42 -0700 | [diff] [blame] | 637 |  | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 638 | args = info_dict.get("mkbootimg_version_args") | 
| Sami Tolvanen | 3303d90 | 2016-03-15 16:49:30 +0000 | [diff] [blame] | 639 | if args and args.strip(): | 
|  | 640 | cmd.extend(shlex.split(args)) | 
|  | 641 |  | 
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 642 | if has_ramdisk: | 
|  | 643 | cmd.extend(["--ramdisk", ramdisk_img.name]) | 
|  | 644 |  | 
| Tao Bao | d95e9fd | 2015-03-29 23:07:41 -0700 | [diff] [blame] | 645 | img_unsigned = None | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 646 | if info_dict.get("vboot"): | 
| Tao Bao | d95e9fd | 2015-03-29 23:07:41 -0700 | [diff] [blame] | 647 | img_unsigned = tempfile.NamedTemporaryFile() | 
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 648 | cmd.extend(["--output", img_unsigned.name]) | 
| Tao Bao | d95e9fd | 2015-03-29 23:07:41 -0700 | [diff] [blame] | 649 | else: | 
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 650 | cmd.extend(["--output", img.name]) | 
| Doug Zongker | 38a649f | 2009-06-17 09:07:09 -0700 | [diff] [blame] | 651 |  | 
| Tao Bao | bf70c31 | 2017-07-11 17:27:55 -0700 | [diff] [blame] | 652 | # "boot" or "recovery", without extension. | 
|  | 653 | partition_name = os.path.basename(sourcedir).lower() | 
|  | 654 |  | 
| Chen, ZhiminX | 752439b | 2018-09-23 22:10:47 +0800 | [diff] [blame] | 655 | if partition_name == "recovery": | 
|  | 656 | if info_dict.get("include_recovery_dtbo") == "true": | 
|  | 657 | fn = os.path.join(sourcedir, "recovery_dtbo") | 
|  | 658 | cmd.extend(["--recovery_dtbo", fn]) | 
|  | 659 | if info_dict.get("include_recovery_acpio") == "true": | 
|  | 660 | fn = os.path.join(sourcedir, "recovery_acpio") | 
|  | 661 | cmd.extend(["--recovery_acpio", fn]) | 
| Hridya Valsaraju | e74a38b | 2018-03-21 12:15:11 -0700 | [diff] [blame] | 662 |  | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 663 | RunAndCheckOutput(cmd) | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 664 |  | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 665 | if (info_dict.get("boot_signer") == "true" and | 
|  | 666 | info_dict.get("verity_key")): | 
| Tao Bao | d42e97e | 2016-11-30 12:11:57 -0800 | [diff] [blame] | 667 | # Hard-code the path as "/boot" for two-step special recovery image (which | 
|  | 668 | # will be loaded into /boot during the two-step OTA). | 
|  | 669 | if two_step_image: | 
|  | 670 | path = "/boot" | 
|  | 671 | else: | 
| Tao Bao | bf70c31 | 2017-07-11 17:27:55 -0700 | [diff] [blame] | 672 | path = "/" + partition_name | 
| Baligh Uddin | 601ddea | 2015-06-09 15:48:14 -0700 | [diff] [blame] | 673 | cmd = [OPTIONS.boot_signer_path] | 
|  | 674 | cmd.extend(OPTIONS.boot_signer_args) | 
|  | 675 | cmd.extend([path, img.name, | 
|  | 676 | info_dict["verity_key"] + ".pk8", | 
|  | 677 | info_dict["verity_key"] + ".x509.pem", img.name]) | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 678 | RunAndCheckOutput(cmd) | 
| Geremy Condra | 95ebe7a | 2014-08-19 17:27:56 -0700 | [diff] [blame] | 679 |  | 
| Tao Bao | d95e9fd | 2015-03-29 23:07:41 -0700 | [diff] [blame] | 680 | # Sign the image if vboot is non-empty. | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 681 | elif info_dict.get("vboot"): | 
| Tao Bao | bf70c31 | 2017-07-11 17:27:55 -0700 | [diff] [blame] | 682 | path = "/" + partition_name | 
| Tao Bao | d95e9fd | 2015-03-29 23:07:41 -0700 | [diff] [blame] | 683 | img_keyblock = tempfile.NamedTemporaryFile() | 
| Tao Bao | 4f104d1 | 2017-02-17 23:21:31 -0800 | [diff] [blame] | 684 | # We have switched from the prebuilt futility binary to using the tool | 
|  | 685 | # (futility-host) built from the source. Override the setting in the old | 
|  | 686 | # TF.zip. | 
|  | 687 | futility = info_dict["futility"] | 
|  | 688 | if futility.startswith("prebuilts/"): | 
|  | 689 | futility = "futility-host" | 
|  | 690 | cmd = [info_dict["vboot_signer_cmd"], futility, | 
| Tao Bao | d95e9fd | 2015-03-29 23:07:41 -0700 | [diff] [blame] | 691 | img_unsigned.name, info_dict["vboot_key"] + ".vbpubk", | 
| Furquan Shaikh | 852b8de | 2015-08-10 11:43:45 -0700 | [diff] [blame] | 692 | info_dict["vboot_key"] + ".vbprivk", | 
|  | 693 | info_dict["vboot_subkey"] + ".vbprivk", | 
|  | 694 | img_keyblock.name, | 
| Tao Bao | d95e9fd | 2015-03-29 23:07:41 -0700 | [diff] [blame] | 695 | img.name] | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 696 | RunAndCheckOutput(cmd) | 
| Tao Bao | d95e9fd | 2015-03-29 23:07:41 -0700 | [diff] [blame] | 697 |  | 
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 698 | # Clean up the temp files. | 
|  | 699 | img_unsigned.close() | 
|  | 700 | img_keyblock.close() | 
|  | 701 |  | 
| David Zeuthen | 8fecb28 | 2017-12-01 16:24:01 -0500 | [diff] [blame] | 702 | # AVB: if enabled, calculate and add hash to boot.img or recovery.img. | 
| Bowgo Tsai | 3e599ea | 2017-05-26 18:30:04 +0800 | [diff] [blame] | 703 | if info_dict.get("avb_enable") == "true": | 
| Tao Bao | 3ebfdde | 2017-05-23 23:06:55 -0700 | [diff] [blame] | 704 | avbtool = os.getenv('AVBTOOL') or info_dict["avb_avbtool"] | 
| David Zeuthen | 8fecb28 | 2017-12-01 16:24:01 -0500 | [diff] [blame] | 705 | part_size = info_dict[partition_name + "_size"] | 
| David Zeuthen | 2ce63ed | 2016-09-15 13:43:54 -0400 | [diff] [blame] | 706 | cmd = [avbtool, "add_hash_footer", "--image", img.name, | 
| Tao Bao | bf70c31 | 2017-07-11 17:27:55 -0700 | [diff] [blame] | 707 | "--partition_size", str(part_size), "--partition_name", | 
|  | 708 | partition_name] | 
|  | 709 | AppendAVBSigningArgs(cmd, partition_name) | 
| David Zeuthen | 8fecb28 | 2017-12-01 16:24:01 -0500 | [diff] [blame] | 710 | args = info_dict.get("avb_" + partition_name + "_add_hash_footer_args") | 
| David Zeuthen | 2ce63ed | 2016-09-15 13:43:54 -0400 | [diff] [blame] | 711 | if args and args.strip(): | 
|  | 712 | cmd.extend(shlex.split(args)) | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 713 | RunAndCheckOutput(cmd) | 
| David Zeuthen | d995f4b | 2016-01-29 16:59:17 -0500 | [diff] [blame] | 714 |  | 
|  | 715 | img.seek(os.SEEK_SET, 0) | 
|  | 716 | data = img.read() | 
|  | 717 |  | 
|  | 718 | if has_ramdisk: | 
|  | 719 | ramdisk_img.close() | 
|  | 720 | img.close() | 
|  | 721 |  | 
|  | 722 | return data | 
|  | 723 |  | 
|  | 724 |  | 
| Doug Zongker | d513160 | 2012-08-02 14:46:42 -0700 | [diff] [blame] | 725 | def GetBootableImage(name, prebuilt_name, unpack_dir, tree_subdir, | 
| Tao Bao | d42e97e | 2016-11-30 12:11:57 -0800 | [diff] [blame] | 726 | info_dict=None, two_step_image=False): | 
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 727 | """Return a File object with the desired bootable image. | 
|  | 728 |  | 
|  | 729 | Look for it in 'unpack_dir'/BOOTABLE_IMAGES under the name 'prebuilt_name', | 
|  | 730 | otherwise look for it under 'unpack_dir'/IMAGES, otherwise construct it from | 
|  | 731 | the source files in 'unpack_dir'/'tree_subdir'.""" | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 732 |  | 
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 733 | prebuilt_path = os.path.join(unpack_dir, "BOOTABLE_IMAGES", prebuilt_name) | 
|  | 734 | if os.path.exists(prebuilt_path): | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 735 | logger.info("using prebuilt %s from BOOTABLE_IMAGES...", prebuilt_name) | 
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 736 | return File.FromLocalFile(name, prebuilt_path) | 
| Doug Zongker | 6f1d031 | 2014-08-22 08:07:12 -0700 | [diff] [blame] | 737 |  | 
|  | 738 | prebuilt_path = os.path.join(unpack_dir, "IMAGES", prebuilt_name) | 
|  | 739 | if os.path.exists(prebuilt_path): | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 740 | logger.info("using prebuilt %s from IMAGES...", prebuilt_name) | 
| Doug Zongker | 6f1d031 | 2014-08-22 08:07:12 -0700 | [diff] [blame] | 741 | return File.FromLocalFile(name, prebuilt_path) | 
|  | 742 |  | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 743 | logger.info("building image from target_files %s...", tree_subdir) | 
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 744 |  | 
|  | 745 | if info_dict is None: | 
|  | 746 | info_dict = OPTIONS.info_dict | 
|  | 747 |  | 
|  | 748 | # With system_root_image == "true", we don't pack ramdisk into the boot image. | 
| Daniel Rosenberg | 40ef35b | 2015-11-10 19:21:34 -0800 | [diff] [blame] | 749 | # Unless "recovery_as_boot" is specified, in which case we carry the ramdisk | 
|  | 750 | # for recovery. | 
|  | 751 | has_ramdisk = (info_dict.get("system_root_image") != "true" or | 
|  | 752 | prebuilt_name != "boot.img" or | 
|  | 753 | info_dict.get("recovery_as_boot") == "true") | 
| Tao Bao | 7a5bf8a | 2015-07-21 18:01:20 -0700 | [diff] [blame] | 754 |  | 
| Doug Zongker | 6f1d031 | 2014-08-22 08:07:12 -0700 | [diff] [blame] | 755 | fs_config = "META/" + tree_subdir.lower() + "_filesystem_config.txt" | 
| David Zeuthen | 2ce63ed | 2016-09-15 13:43:54 -0400 | [diff] [blame] | 756 | data = _BuildBootableImage(os.path.join(unpack_dir, tree_subdir), | 
|  | 757 | os.path.join(unpack_dir, fs_config), | 
| Tao Bao | d42e97e | 2016-11-30 12:11:57 -0800 | [diff] [blame] | 758 | info_dict, has_ramdisk, two_step_image) | 
| Doug Zongker | 6f1d031 | 2014-08-22 08:07:12 -0700 | [diff] [blame] | 759 | if data: | 
|  | 760 | return File(name, data) | 
|  | 761 | return None | 
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 762 |  | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 763 |  | 
| Narayan Kamath | a07bf04 | 2017-08-14 14:49:21 +0100 | [diff] [blame] | 764 | def Gunzip(in_filename, out_filename): | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 765 | """Gunzips the given gzip compressed file to a given output file.""" | 
|  | 766 | with gzip.open(in_filename, "rb") as in_file, \ | 
|  | 767 | open(out_filename, "wb") as out_file: | 
| Narayan Kamath | a07bf04 | 2017-08-14 14:49:21 +0100 | [diff] [blame] | 768 | shutil.copyfileobj(in_file, out_file) | 
|  | 769 |  | 
|  | 770 |  | 
| Doug Zongker | 75f1736 | 2009-12-08 13:46:44 -0800 | [diff] [blame] | 771 | def UnzipTemp(filename, pattern=None): | 
| Tao Bao | 1c830bf | 2017-12-25 10:43:47 -0800 | [diff] [blame] | 772 | """Unzips the given archive into a temporary directory and returns the name. | 
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 773 |  | 
| Tao Bao | 1c830bf | 2017-12-25 10:43:47 -0800 | [diff] [blame] | 774 | If filename is of the form "foo.zip+bar.zip", unzip foo.zip into a temp dir, | 
|  | 775 | then unzip bar.zip into that_dir/BOOTABLE_IMAGES. | 
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 776 |  | 
| Tao Bao | 1c830bf | 2017-12-25 10:43:47 -0800 | [diff] [blame] | 777 | Returns: | 
| Tao Bao | dba59ee | 2018-01-09 13:21:02 -0800 | [diff] [blame] | 778 | The name of the temporary directory. | 
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 779 | """ | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 780 |  | 
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 781 | def unzip_to_dir(filename, dirname): | 
|  | 782 | cmd = ["unzip", "-o", "-q", filename, "-d", dirname] | 
|  | 783 | if pattern is not None: | 
| Tao Bao | 6b0b2f9 | 2017-03-05 11:38:11 -0800 | [diff] [blame] | 784 | cmd.extend(pattern) | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 785 | RunAndCheckOutput(cmd) | 
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 786 |  | 
| Tao Bao | 1c830bf | 2017-12-25 10:43:47 -0800 | [diff] [blame] | 787 | tmp = MakeTempDir(prefix="targetfiles-") | 
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 788 | m = re.match(r"^(.*[.]zip)\+(.*[.]zip)$", filename, re.IGNORECASE) | 
|  | 789 | if m: | 
|  | 790 | unzip_to_dir(m.group(1), tmp) | 
|  | 791 | unzip_to_dir(m.group(2), os.path.join(tmp, "BOOTABLE_IMAGES")) | 
|  | 792 | filename = m.group(1) | 
|  | 793 | else: | 
|  | 794 | unzip_to_dir(filename, tmp) | 
|  | 795 |  | 
| Tao Bao | dba59ee | 2018-01-09 13:21:02 -0800 | [diff] [blame] | 796 | return tmp | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 797 |  | 
|  | 798 |  | 
| Tianjie Xu | 67c7cbb | 2018-08-30 00:32:07 -0700 | [diff] [blame] | 799 | def GetSparseImage(which, tmpdir, input_zip, allow_shared_blocks, | 
|  | 800 | hashtree_info_generator=None): | 
| Tao Bao | c765cca | 2018-01-31 17:32:40 -0800 | [diff] [blame] | 801 | """Returns a SparseImage object suitable for passing to BlockImageDiff. | 
|  | 802 |  | 
|  | 803 | This function loads the specified sparse image from the given path, and | 
|  | 804 | performs additional processing for OTA purpose. For example, it always adds | 
|  | 805 | block 0 to clobbered blocks list. It also detects files that cannot be | 
|  | 806 | reconstructed from the block list, for whom we should avoid applying imgdiff. | 
|  | 807 |  | 
|  | 808 | Args: | 
|  | 809 | which: The partition name, which must be "system" or "vendor". | 
|  | 810 | tmpdir: The directory that contains the prebuilt image and block map file. | 
|  | 811 | input_zip: The target-files ZIP archive. | 
| Tao Bao | e709b09 | 2018-02-07 12:40:00 -0800 | [diff] [blame] | 812 | allow_shared_blocks: Whether having shared blocks is allowed. | 
| Tianjie Xu | 67c7cbb | 2018-08-30 00:32:07 -0700 | [diff] [blame] | 813 | hashtree_info_generator: If present, generates the hashtree_info for this | 
|  | 814 | sparse image. | 
| Tao Bao | c765cca | 2018-01-31 17:32:40 -0800 | [diff] [blame] | 815 | Returns: | 
|  | 816 | A SparseImage object, with file_map info loaded. | 
|  | 817 | """ | 
|  | 818 | assert which in ("system", "vendor") | 
|  | 819 |  | 
|  | 820 | path = os.path.join(tmpdir, "IMAGES", which + ".img") | 
|  | 821 | mappath = os.path.join(tmpdir, "IMAGES", which + ".map") | 
|  | 822 |  | 
|  | 823 | # The image and map files must have been created prior to calling | 
|  | 824 | # ota_from_target_files.py (since LMP). | 
|  | 825 | assert os.path.exists(path) and os.path.exists(mappath) | 
|  | 826 |  | 
|  | 827 | # In ext4 filesystems, block 0 might be changed even being mounted R/O. We add | 
|  | 828 | # it to clobbered_blocks so that it will be written to the target | 
|  | 829 | # unconditionally. Note that they are still part of care_map. (Bug: 20939131) | 
|  | 830 | clobbered_blocks = "0" | 
|  | 831 |  | 
| Tianjie Xu | 67c7cbb | 2018-08-30 00:32:07 -0700 | [diff] [blame] | 832 | image = sparse_img.SparseImage( | 
|  | 833 | path, mappath, clobbered_blocks, allow_shared_blocks=allow_shared_blocks, | 
|  | 834 | hashtree_info_generator=hashtree_info_generator) | 
| Tao Bao | c765cca | 2018-01-31 17:32:40 -0800 | [diff] [blame] | 835 |  | 
|  | 836 | # block.map may contain less blocks, because mke2fs may skip allocating blocks | 
|  | 837 | # if they contain all zeros. We can't reconstruct such a file from its block | 
|  | 838 | # list. Tag such entries accordingly. (Bug: 65213616) | 
|  | 839 | for entry in image.file_map: | 
| Tao Bao | c765cca | 2018-01-31 17:32:40 -0800 | [diff] [blame] | 840 | # Skip artificial names, such as "__ZERO", "__NONZERO-1". | 
| Tao Bao | d3554e6 | 2018-07-10 15:31:22 -0700 | [diff] [blame] | 841 | if not entry.startswith('/'): | 
| Tao Bao | c765cca | 2018-01-31 17:32:40 -0800 | [diff] [blame] | 842 | continue | 
|  | 843 |  | 
| Tom Cherry | d14b895 | 2018-08-09 14:26:00 -0700 | [diff] [blame] | 844 | # "/system/framework/am.jar" => "SYSTEM/framework/am.jar". Note that the | 
|  | 845 | # filename listed in system.map may contain an additional leading slash | 
|  | 846 | # (i.e. "//system/framework/am.jar"). Using lstrip to get consistent | 
|  | 847 | # results. | 
| Tao Bao | d3554e6 | 2018-07-10 15:31:22 -0700 | [diff] [blame] | 848 | arcname = string.replace(entry, which, which.upper(), 1).lstrip('/') | 
|  | 849 |  | 
| Tom Cherry | d14b895 | 2018-08-09 14:26:00 -0700 | [diff] [blame] | 850 | # Special handling another case, where files not under /system | 
|  | 851 | # (e.g. "/sbin/charger") are packed under ROOT/ in a target_files.zip. | 
| Tao Bao | d3554e6 | 2018-07-10 15:31:22 -0700 | [diff] [blame] | 852 | if which == 'system' and not arcname.startswith('SYSTEM'): | 
|  | 853 | arcname = 'ROOT/' + arcname | 
|  | 854 |  | 
|  | 855 | assert arcname in input_zip.namelist(), \ | 
|  | 856 | "Failed to find the ZIP entry for {}".format(entry) | 
|  | 857 |  | 
| Tao Bao | c765cca | 2018-01-31 17:32:40 -0800 | [diff] [blame] | 858 | info = input_zip.getinfo(arcname) | 
|  | 859 | ranges = image.file_map[entry] | 
| Tao Bao | e709b09 | 2018-02-07 12:40:00 -0800 | [diff] [blame] | 860 |  | 
|  | 861 | # If a RangeSet has been tagged as using shared blocks while loading the | 
| Tao Bao | 2a20f34 | 2018-12-03 15:08:23 -0800 | [diff] [blame] | 862 | # image, check the original block list to determine its completeness. Note | 
|  | 863 | # that the 'incomplete' flag would be tagged to the original RangeSet only. | 
| Tao Bao | e709b09 | 2018-02-07 12:40:00 -0800 | [diff] [blame] | 864 | if ranges.extra.get('uses_shared_blocks'): | 
| Tao Bao | 2a20f34 | 2018-12-03 15:08:23 -0800 | [diff] [blame] | 865 | ranges = ranges.extra['uses_shared_blocks'] | 
| Tao Bao | e709b09 | 2018-02-07 12:40:00 -0800 | [diff] [blame] | 866 |  | 
| Tao Bao | c765cca | 2018-01-31 17:32:40 -0800 | [diff] [blame] | 867 | if RoundUpTo4K(info.file_size) > ranges.size() * 4096: | 
|  | 868 | ranges.extra['incomplete'] = True | 
|  | 869 |  | 
|  | 870 | return image | 
|  | 871 |  | 
|  | 872 |  | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 873 | def GetKeyPasswords(keylist): | 
|  | 874 | """Given a list of keys, prompt the user to enter passwords for | 
|  | 875 | those which require them.  Return a {key: password} dict.  password | 
|  | 876 | will be None if the key has no password.""" | 
|  | 877 |  | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 878 | no_passwords = [] | 
|  | 879 | need_passwords = [] | 
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 880 | key_passwords = {} | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 881 | devnull = open("/dev/null", "w+b") | 
|  | 882 | for k in sorted(keylist): | 
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 883 | # We don't need a password for things that aren't really keys. | 
|  | 884 | if k in SPECIAL_CERT_STRINGS: | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 885 | no_passwords.append(k) | 
| Doug Zongker | 43874f8 | 2009-04-14 14:05:15 -0700 | [diff] [blame] | 886 | continue | 
|  | 887 |  | 
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 888 | p = Run(["openssl", "pkcs8", "-in", k+OPTIONS.private_key_suffix, | 
| Doug Zongker | 602a84e | 2009-06-18 08:35:12 -0700 | [diff] [blame] | 889 | "-inform", "DER", "-nocrypt"], | 
|  | 890 | stdin=devnull.fileno(), | 
|  | 891 | stdout=devnull.fileno(), | 
|  | 892 | stderr=subprocess.STDOUT) | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 893 | p.communicate() | 
|  | 894 | if p.returncode == 0: | 
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 895 | # Definitely an unencrypted key. | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 896 | no_passwords.append(k) | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 897 | else: | 
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 898 | p = Run(["openssl", "pkcs8", "-in", k+OPTIONS.private_key_suffix, | 
|  | 899 | "-inform", "DER", "-passin", "pass:"], | 
|  | 900 | stdin=devnull.fileno(), | 
|  | 901 | stdout=devnull.fileno(), | 
|  | 902 | stderr=subprocess.PIPE) | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 903 | _, stderr = p.communicate() | 
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 904 | if p.returncode == 0: | 
|  | 905 | # Encrypted key with empty string as password. | 
|  | 906 | key_passwords[k] = '' | 
|  | 907 | elif stderr.startswith('Error decrypting key'): | 
|  | 908 | # Definitely encrypted key. | 
|  | 909 | # It would have said "Error reading key" if it didn't parse correctly. | 
|  | 910 | need_passwords.append(k) | 
|  | 911 | else: | 
|  | 912 | # Potentially, a type of key that openssl doesn't understand. | 
|  | 913 | # We'll let the routines in signapk.jar handle it. | 
|  | 914 | no_passwords.append(k) | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 915 | devnull.close() | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 916 |  | 
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 917 | key_passwords.update(PasswordManager().GetPasswords(need_passwords)) | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 918 | key_passwords.update(dict.fromkeys(no_passwords)) | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 919 | return key_passwords | 
|  | 920 |  | 
|  | 921 |  | 
| Alex Klyubin | 2cfd1d1 | 2016-01-13 10:32:47 -0800 | [diff] [blame] | 922 | def GetMinSdkVersion(apk_name): | 
| Tao Bao | f47bf0f | 2018-03-21 23:28:51 -0700 | [diff] [blame] | 923 | """Gets the minSdkVersion declared in the APK. | 
|  | 924 |  | 
|  | 925 | It calls 'aapt' to query the embedded minSdkVersion from the given APK file. | 
|  | 926 | This can be both a decimal number (API Level) or a codename. | 
|  | 927 |  | 
|  | 928 | Args: | 
|  | 929 | apk_name: The APK filename. | 
|  | 930 |  | 
|  | 931 | Returns: | 
|  | 932 | The parsed SDK version string. | 
|  | 933 |  | 
|  | 934 | Raises: | 
|  | 935 | ExternalError: On failing to obtain the min SDK version. | 
| Alex Klyubin | 2cfd1d1 | 2016-01-13 10:32:47 -0800 | [diff] [blame] | 936 | """ | 
| Tao Bao | f47bf0f | 2018-03-21 23:28:51 -0700 | [diff] [blame] | 937 | proc = Run( | 
|  | 938 | ["aapt", "dump", "badging", apk_name], stdout=subprocess.PIPE, | 
|  | 939 | stderr=subprocess.PIPE) | 
|  | 940 | stdoutdata, stderrdata = proc.communicate() | 
|  | 941 | if proc.returncode != 0: | 
|  | 942 | raise ExternalError( | 
|  | 943 | "Failed to obtain minSdkVersion: aapt return code {}:\n{}\n{}".format( | 
|  | 944 | proc.returncode, stdoutdata, stderrdata)) | 
| Alex Klyubin | 2cfd1d1 | 2016-01-13 10:32:47 -0800 | [diff] [blame] | 945 |  | 
| Tao Bao | f47bf0f | 2018-03-21 23:28:51 -0700 | [diff] [blame] | 946 | for line in stdoutdata.split("\n"): | 
|  | 947 | # Looking for lines such as sdkVersion:'23' or sdkVersion:'M'. | 
| Alex Klyubin | 2cfd1d1 | 2016-01-13 10:32:47 -0800 | [diff] [blame] | 948 | m = re.match(r'sdkVersion:\'([^\']*)\'', line) | 
|  | 949 | if m: | 
|  | 950 | return m.group(1) | 
|  | 951 | raise ExternalError("No minSdkVersion returned by aapt") | 
|  | 952 |  | 
|  | 953 |  | 
|  | 954 | def GetMinSdkVersionInt(apk_name, codename_to_api_level_map): | 
| Tao Bao | f47bf0f | 2018-03-21 23:28:51 -0700 | [diff] [blame] | 955 | """Returns the minSdkVersion declared in the APK as a number (API Level). | 
| Alex Klyubin | 2cfd1d1 | 2016-01-13 10:32:47 -0800 | [diff] [blame] | 956 |  | 
| Tao Bao | f47bf0f | 2018-03-21 23:28:51 -0700 | [diff] [blame] | 957 | If minSdkVersion is set to a codename, it is translated to a number using the | 
|  | 958 | provided map. | 
|  | 959 |  | 
|  | 960 | Args: | 
|  | 961 | apk_name: The APK filename. | 
|  | 962 |  | 
|  | 963 | Returns: | 
|  | 964 | The parsed SDK version number. | 
|  | 965 |  | 
|  | 966 | Raises: | 
|  | 967 | ExternalError: On failing to get the min SDK version number. | 
|  | 968 | """ | 
| Alex Klyubin | 2cfd1d1 | 2016-01-13 10:32:47 -0800 | [diff] [blame] | 969 | version = GetMinSdkVersion(apk_name) | 
|  | 970 | try: | 
|  | 971 | return int(version) | 
|  | 972 | except ValueError: | 
|  | 973 | # Not a decimal number. Codename? | 
|  | 974 | if version in codename_to_api_level_map: | 
|  | 975 | return codename_to_api_level_map[version] | 
|  | 976 | else: | 
| Tao Bao | f47bf0f | 2018-03-21 23:28:51 -0700 | [diff] [blame] | 977 | raise ExternalError( | 
|  | 978 | "Unknown minSdkVersion: '{}'. Known codenames: {}".format( | 
|  | 979 | version, codename_to_api_level_map)) | 
| Alex Klyubin | 2cfd1d1 | 2016-01-13 10:32:47 -0800 | [diff] [blame] | 980 |  | 
|  | 981 |  | 
|  | 982 | def SignFile(input_name, output_name, key, password, min_api_level=None, | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 983 | codename_to_api_level_map=None, whole_file=False): | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 984 | """Sign the input_name zip/jar/apk, producing output_name.  Use the | 
|  | 985 | given key and password (the latter may be None if the key does not | 
|  | 986 | have a password. | 
|  | 987 |  | 
| Doug Zongker | 951495f | 2009-08-14 12:44:19 -0700 | [diff] [blame] | 988 | If whole_file is true, use the "-w" option to SignApk to embed a | 
|  | 989 | signature that covers the whole file in the archive comment of the | 
|  | 990 | zip file. | 
| Alex Klyubin | 2cfd1d1 | 2016-01-13 10:32:47 -0800 | [diff] [blame] | 991 |  | 
|  | 992 | min_api_level is the API Level (int) of the oldest platform this file may end | 
|  | 993 | up on. If not specified for an APK, the API Level is obtained by interpreting | 
|  | 994 | the minSdkVersion attribute of the APK's AndroidManifest.xml. | 
|  | 995 |  | 
|  | 996 | codename_to_api_level_map is needed to translate the codename which may be | 
|  | 997 | encountered as the APK's minSdkVersion. | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 998 | """ | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 999 | if codename_to_api_level_map is None: | 
|  | 1000 | codename_to_api_level_map = {} | 
| Doug Zongker | 951495f | 2009-08-14 12:44:19 -0700 | [diff] [blame] | 1001 |  | 
| Alex Klyubin | 9667b18 | 2015-12-10 13:38:50 -0800 | [diff] [blame] | 1002 | java_library_path = os.path.join( | 
|  | 1003 | OPTIONS.search_path, OPTIONS.signapk_shared_library_path) | 
|  | 1004 |  | 
| Tao Bao | e95540e | 2016-11-08 12:08:53 -0800 | [diff] [blame] | 1005 | cmd = ([OPTIONS.java_path] + OPTIONS.java_args + | 
|  | 1006 | ["-Djava.library.path=" + java_library_path, | 
|  | 1007 | "-jar", os.path.join(OPTIONS.search_path, OPTIONS.signapk_path)] + | 
|  | 1008 | OPTIONS.extra_signapk_args) | 
| Doug Zongker | 951495f | 2009-08-14 12:44:19 -0700 | [diff] [blame] | 1009 | if whole_file: | 
|  | 1010 | cmd.append("-w") | 
| Alex Klyubin | 2cfd1d1 | 2016-01-13 10:32:47 -0800 | [diff] [blame] | 1011 |  | 
|  | 1012 | min_sdk_version = min_api_level | 
|  | 1013 | if min_sdk_version is None: | 
|  | 1014 | if not whole_file: | 
|  | 1015 | min_sdk_version = GetMinSdkVersionInt( | 
|  | 1016 | input_name, codename_to_api_level_map) | 
|  | 1017 | if min_sdk_version is not None: | 
|  | 1018 | cmd.extend(["--min-sdk-version", str(min_sdk_version)]) | 
|  | 1019 |  | 
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 1020 | cmd.extend([key + OPTIONS.public_key_suffix, | 
|  | 1021 | key + OPTIONS.private_key_suffix, | 
| Alex Klyubin | eb756d7 | 2015-12-04 09:21:08 -0800 | [diff] [blame] | 1022 | input_name, output_name]) | 
| Doug Zongker | 951495f | 2009-08-14 12:44:19 -0700 | [diff] [blame] | 1023 |  | 
| Tao Bao | 73dd4f4 | 2018-10-04 16:25:33 -0700 | [diff] [blame] | 1024 | proc = Run(cmd, stdin=subprocess.PIPE) | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1025 | if password is not None: | 
|  | 1026 | password += "\n" | 
| Tao Bao | 73dd4f4 | 2018-10-04 16:25:33 -0700 | [diff] [blame] | 1027 | stdoutdata, _ = proc.communicate(password) | 
|  | 1028 | if proc.returncode != 0: | 
| Tao Bao | 8092198 | 2018-03-21 21:02:19 -0700 | [diff] [blame] | 1029 | raise ExternalError( | 
|  | 1030 | "Failed to run signapk.jar: return code {}:\n{}".format( | 
| Tao Bao | 73dd4f4 | 2018-10-04 16:25:33 -0700 | [diff] [blame] | 1031 | proc.returncode, stdoutdata)) | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1032 |  | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1033 |  | 
| Doug Zongker | 3797473 | 2010-09-16 17:44:38 -0700 | [diff] [blame] | 1034 | def CheckSize(data, target, info_dict): | 
| Tao Bao | 9dd909e | 2017-11-14 11:27:32 -0800 | [diff] [blame] | 1035 | """Checks the data string passed against the max size limit. | 
| Doug Zongker | c77a9ad | 2010-09-16 11:28:43 -0700 | [diff] [blame] | 1036 |  | 
| Tao Bao | 9dd909e | 2017-11-14 11:27:32 -0800 | [diff] [blame] | 1037 | For non-AVB images, raise exception if the data is too big. Print a warning | 
|  | 1038 | if the data is nearing the maximum size. | 
|  | 1039 |  | 
|  | 1040 | For AVB images, the actual image size should be identical to the limit. | 
|  | 1041 |  | 
|  | 1042 | Args: | 
|  | 1043 | data: A string that contains all the data for the partition. | 
|  | 1044 | target: The partition name. The ".img" suffix is optional. | 
|  | 1045 | info_dict: The dict to be looked up for relevant info. | 
|  | 1046 | """ | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1047 | if target.endswith(".img"): | 
|  | 1048 | target = target[:-4] | 
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 1049 | mount_point = "/" + target | 
|  | 1050 |  | 
| Ying Wang | f8824af | 2014-06-03 14:07:27 -0700 | [diff] [blame] | 1051 | fs_type = None | 
|  | 1052 | limit = None | 
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 1053 | if info_dict["fstab"]: | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1054 | if mount_point == "/userdata": | 
|  | 1055 | mount_point = "/data" | 
| Doug Zongker | 9ce0fb6 | 2010-09-20 18:04:41 -0700 | [diff] [blame] | 1056 | p = info_dict["fstab"][mount_point] | 
|  | 1057 | fs_type = p.fs_type | 
| Andrew Boie | 0f9aec8 | 2012-02-14 09:32:52 -0800 | [diff] [blame] | 1058 | device = p.device | 
|  | 1059 | if "/" in device: | 
|  | 1060 | device = device[device.rfind("/")+1:] | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1061 | limit = info_dict.get(device + "_size") | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1062 | if not fs_type or not limit: | 
|  | 1063 | return | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1064 |  | 
| Andrew Boie | 0f9aec8 | 2012-02-14 09:32:52 -0800 | [diff] [blame] | 1065 | size = len(data) | 
| Tao Bao | 9dd909e | 2017-11-14 11:27:32 -0800 | [diff] [blame] | 1066 | # target could be 'userdata' or 'cache'. They should follow the non-AVB image | 
|  | 1067 | # path. | 
|  | 1068 | if info_dict.get("avb_enable") == "true" and target in AVB_PARTITIONS: | 
|  | 1069 | if size != limit: | 
|  | 1070 | raise ExternalError( | 
|  | 1071 | "Mismatching image size for %s: expected %d actual %d" % ( | 
|  | 1072 | target, limit, size)) | 
|  | 1073 | else: | 
|  | 1074 | pct = float(size) * 100.0 / limit | 
|  | 1075 | msg = "%s size (%d) is %.2f%% of limit (%d)" % (target, size, pct, limit) | 
|  | 1076 | if pct >= 99.0: | 
|  | 1077 | raise ExternalError(msg) | 
|  | 1078 | elif pct >= 95.0: | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 1079 | logger.warning("\n  WARNING: %s\n", msg) | 
|  | 1080 | else: | 
|  | 1081 | logger.info("  %s", msg) | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1082 |  | 
|  | 1083 |  | 
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 1084 | def ReadApkCerts(tf_zip): | 
| Tao Bao | 818ddf5 | 2018-01-05 11:17:34 -0800 | [diff] [blame] | 1085 | """Parses the APK certs info from a given target-files zip. | 
|  | 1086 |  | 
|  | 1087 | Given a target-files ZipFile, parses the META/apkcerts.txt entry and returns a | 
|  | 1088 | tuple with the following elements: (1) a dictionary that maps packages to | 
|  | 1089 | certs (based on the "certificate" and "private_key" attributes in the file; | 
|  | 1090 | (2) a string representing the extension of compressed APKs in the target files | 
|  | 1091 | (e.g ".gz", ".bro"). | 
|  | 1092 |  | 
|  | 1093 | Args: | 
|  | 1094 | tf_zip: The input target_files ZipFile (already open). | 
|  | 1095 |  | 
|  | 1096 | Returns: | 
|  | 1097 | (certmap, ext): certmap is a dictionary that maps packages to certs; ext is | 
|  | 1098 | the extension string of compressed APKs (e.g. ".gz"), or None if there's | 
|  | 1099 | no compressed APKs. | 
|  | 1100 | """ | 
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 1101 | certmap = {} | 
| Narayan Kamath | a07bf04 | 2017-08-14 14:49:21 +0100 | [diff] [blame] | 1102 | compressed_extension = None | 
|  | 1103 |  | 
| Tao Bao | 0f99033 | 2017-09-08 19:02:54 -0700 | [diff] [blame] | 1104 | # META/apkcerts.txt contains the info for _all_ the packages known at build | 
|  | 1105 | # time. Filter out the ones that are not installed. | 
|  | 1106 | installed_files = set() | 
|  | 1107 | for name in tf_zip.namelist(): | 
|  | 1108 | basename = os.path.basename(name) | 
|  | 1109 | if basename: | 
|  | 1110 | installed_files.add(basename) | 
|  | 1111 |  | 
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 1112 | for line in tf_zip.read("META/apkcerts.txt").split("\n"): | 
|  | 1113 | line = line.strip() | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1114 | if not line: | 
|  | 1115 | continue | 
| Tao Bao | 818ddf5 | 2018-01-05 11:17:34 -0800 | [diff] [blame] | 1116 | m = re.match( | 
|  | 1117 | r'^name="(?P<NAME>.*)"\s+certificate="(?P<CERT>.*)"\s+' | 
|  | 1118 | r'private_key="(?P<PRIVKEY>.*?)"(\s+compressed="(?P<COMPRESSED>.*)")?$', | 
|  | 1119 | line) | 
|  | 1120 | if not m: | 
|  | 1121 | continue | 
| Narayan Kamath | a07bf04 | 2017-08-14 14:49:21 +0100 | [diff] [blame] | 1122 |  | 
| Tao Bao | 818ddf5 | 2018-01-05 11:17:34 -0800 | [diff] [blame] | 1123 | matches = m.groupdict() | 
|  | 1124 | cert = matches["CERT"] | 
|  | 1125 | privkey = matches["PRIVKEY"] | 
|  | 1126 | name = matches["NAME"] | 
|  | 1127 | this_compressed_extension = matches["COMPRESSED"] | 
|  | 1128 |  | 
|  | 1129 | public_key_suffix_len = len(OPTIONS.public_key_suffix) | 
|  | 1130 | private_key_suffix_len = len(OPTIONS.private_key_suffix) | 
|  | 1131 | if cert in SPECIAL_CERT_STRINGS and not privkey: | 
|  | 1132 | certmap[name] = cert | 
|  | 1133 | elif (cert.endswith(OPTIONS.public_key_suffix) and | 
|  | 1134 | privkey.endswith(OPTIONS.private_key_suffix) and | 
|  | 1135 | cert[:-public_key_suffix_len] == privkey[:-private_key_suffix_len]): | 
|  | 1136 | certmap[name] = cert[:-public_key_suffix_len] | 
|  | 1137 | else: | 
|  | 1138 | raise ValueError("Failed to parse line from apkcerts.txt:\n" + line) | 
|  | 1139 |  | 
|  | 1140 | if not this_compressed_extension: | 
|  | 1141 | continue | 
|  | 1142 |  | 
|  | 1143 | # Only count the installed files. | 
|  | 1144 | filename = name + '.' + this_compressed_extension | 
|  | 1145 | if filename not in installed_files: | 
|  | 1146 | continue | 
|  | 1147 |  | 
|  | 1148 | # Make sure that all the values in the compression map have the same | 
|  | 1149 | # extension. We don't support multiple compression methods in the same | 
|  | 1150 | # system image. | 
|  | 1151 | if compressed_extension: | 
|  | 1152 | if this_compressed_extension != compressed_extension: | 
|  | 1153 | raise ValueError( | 
|  | 1154 | "Multiple compressed extensions: {} vs {}".format( | 
|  | 1155 | compressed_extension, this_compressed_extension)) | 
|  | 1156 | else: | 
|  | 1157 | compressed_extension = this_compressed_extension | 
|  | 1158 |  | 
|  | 1159 | return (certmap, | 
|  | 1160 | ("." + compressed_extension) if compressed_extension else None) | 
| Doug Zongker | f6a53aa | 2009-12-15 15:06:55 -0800 | [diff] [blame] | 1161 |  | 
|  | 1162 |  | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1163 | COMMON_DOCSTRING = """ | 
| Tao Bao | 30df8b4 | 2018-04-23 15:32:53 -0700 | [diff] [blame] | 1164 | Global options | 
|  | 1165 |  | 
|  | 1166 | -p  (--path) <dir> | 
|  | 1167 | Prepend <dir>/bin to the list of places to search for binaries run by this | 
|  | 1168 | script, and expect to find jars in <dir>/framework. | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1169 |  | 
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1170 | -s  (--device_specific) <file> | 
| Tao Bao | 30df8b4 | 2018-04-23 15:32:53 -0700 | [diff] [blame] | 1171 | Path to the Python module containing device-specific releasetools code. | 
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1172 |  | 
| Tao Bao | 30df8b4 | 2018-04-23 15:32:53 -0700 | [diff] [blame] | 1173 | -x  (--extra) <key=value> | 
|  | 1174 | Add a key/value pair to the 'extras' dict, which device-specific extension | 
|  | 1175 | code may look at. | 
| Doug Zongker | 8bec09e | 2009-11-30 15:37:14 -0800 | [diff] [blame] | 1176 |  | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1177 | -v  (--verbose) | 
|  | 1178 | Show command lines being executed. | 
|  | 1179 |  | 
|  | 1180 | -h  (--help) | 
|  | 1181 | Display this usage message and exit. | 
|  | 1182 | """ | 
|  | 1183 |  | 
|  | 1184 | def Usage(docstring): | 
| Tao Bao | 89fbb0f | 2017-01-10 10:47:58 -0800 | [diff] [blame] | 1185 | print(docstring.rstrip("\n")) | 
|  | 1186 | print(COMMON_DOCSTRING) | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1187 |  | 
|  | 1188 |  | 
|  | 1189 | def ParseOptions(argv, | 
|  | 1190 | docstring, | 
|  | 1191 | extra_opts="", extra_long_opts=(), | 
|  | 1192 | extra_option_handler=None): | 
|  | 1193 | """Parse the options in argv and return any arguments that aren't | 
|  | 1194 | flags.  docstring is the calling module's docstring, to be displayed | 
|  | 1195 | for errors and -h.  extra_opts and extra_long_opts are for flags | 
|  | 1196 | defined by the caller, which are processed by passing them to | 
|  | 1197 | extra_option_handler.""" | 
|  | 1198 |  | 
|  | 1199 | try: | 
|  | 1200 | opts, args = getopt.getopt( | 
| Doug Zongker | 8bec09e | 2009-11-30 15:37:14 -0800 | [diff] [blame] | 1201 | argv, "hvp:s:x:" + extra_opts, | 
| Alex Klyubin | 9667b18 | 2015-12-10 13:38:50 -0800 | [diff] [blame] | 1202 | ["help", "verbose", "path=", "signapk_path=", | 
|  | 1203 | "signapk_shared_library_path=", "extra_signapk_args=", | 
| Baligh Uddin | bdc2e31 | 2014-09-05 17:36:20 -0700 | [diff] [blame] | 1204 | "java_path=", "java_args=", "public_key_suffix=", | 
| Baligh Uddin | 601ddea | 2015-06-09 15:48:14 -0700 | [diff] [blame] | 1205 | "private_key_suffix=", "boot_signer_path=", "boot_signer_args=", | 
|  | 1206 | "verity_signer_path=", "verity_signer_args=", "device_specific=", | 
| Baligh Uddin | e204868 | 2014-11-20 09:52:05 -0800 | [diff] [blame] | 1207 | "extra="] + | 
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 1208 | list(extra_long_opts)) | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1209 | except getopt.GetoptError as err: | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1210 | Usage(docstring) | 
| Tao Bao | 89fbb0f | 2017-01-10 10:47:58 -0800 | [diff] [blame] | 1211 | print("**", str(err), "**") | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1212 | sys.exit(2) | 
|  | 1213 |  | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1214 | for o, a in opts: | 
|  | 1215 | if o in ("-h", "--help"): | 
|  | 1216 | Usage(docstring) | 
|  | 1217 | sys.exit() | 
|  | 1218 | elif o in ("-v", "--verbose"): | 
|  | 1219 | OPTIONS.verbose = True | 
|  | 1220 | elif o in ("-p", "--path"): | 
| Doug Zongker | 602a84e | 2009-06-18 08:35:12 -0700 | [diff] [blame] | 1221 | OPTIONS.search_path = a | 
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 1222 | elif o in ("--signapk_path",): | 
|  | 1223 | OPTIONS.signapk_path = a | 
| Alex Klyubin | 9667b18 | 2015-12-10 13:38:50 -0800 | [diff] [blame] | 1224 | elif o in ("--signapk_shared_library_path",): | 
|  | 1225 | OPTIONS.signapk_shared_library_path = a | 
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 1226 | elif o in ("--extra_signapk_args",): | 
|  | 1227 | OPTIONS.extra_signapk_args = shlex.split(a) | 
|  | 1228 | elif o in ("--java_path",): | 
|  | 1229 | OPTIONS.java_path = a | 
| Baligh Uddin | 339ee49 | 2014-09-05 11:18:07 -0700 | [diff] [blame] | 1230 | elif o in ("--java_args",): | 
| Tao Bao | e95540e | 2016-11-08 12:08:53 -0800 | [diff] [blame] | 1231 | OPTIONS.java_args = shlex.split(a) | 
| T.R. Fullhart | 37e1052 | 2013-03-18 10:31:26 -0700 | [diff] [blame] | 1232 | elif o in ("--public_key_suffix",): | 
|  | 1233 | OPTIONS.public_key_suffix = a | 
|  | 1234 | elif o in ("--private_key_suffix",): | 
|  | 1235 | OPTIONS.private_key_suffix = a | 
| Baligh Uddin | e204868 | 2014-11-20 09:52:05 -0800 | [diff] [blame] | 1236 | elif o in ("--boot_signer_path",): | 
|  | 1237 | OPTIONS.boot_signer_path = a | 
| Baligh Uddin | 601ddea | 2015-06-09 15:48:14 -0700 | [diff] [blame] | 1238 | elif o in ("--boot_signer_args",): | 
|  | 1239 | OPTIONS.boot_signer_args = shlex.split(a) | 
|  | 1240 | elif o in ("--verity_signer_path",): | 
|  | 1241 | OPTIONS.verity_signer_path = a | 
|  | 1242 | elif o in ("--verity_signer_args",): | 
|  | 1243 | OPTIONS.verity_signer_args = shlex.split(a) | 
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1244 | elif o in ("-s", "--device_specific"): | 
|  | 1245 | OPTIONS.device_specific = a | 
| Doug Zongker | 5ecba70 | 2009-12-03 16:36:20 -0800 | [diff] [blame] | 1246 | elif o in ("-x", "--extra"): | 
| Doug Zongker | 8bec09e | 2009-11-30 15:37:14 -0800 | [diff] [blame] | 1247 | key, value = a.split("=", 1) | 
|  | 1248 | OPTIONS.extras[key] = value | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1249 | else: | 
|  | 1250 | if extra_option_handler is None or not extra_option_handler(o, a): | 
|  | 1251 | assert False, "unknown option \"%s\"" % (o,) | 
|  | 1252 |  | 
| Doug Zongker | 8544877 | 2014-09-09 14:59:20 -0700 | [diff] [blame] | 1253 | if OPTIONS.search_path: | 
|  | 1254 | os.environ["PATH"] = (os.path.join(OPTIONS.search_path, "bin") + | 
|  | 1255 | os.pathsep + os.environ["PATH"]) | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1256 |  | 
|  | 1257 | return args | 
|  | 1258 |  | 
|  | 1259 |  | 
| Tao Bao | 4c851b1 | 2016-09-19 13:54:38 -0700 | [diff] [blame] | 1260 | def MakeTempFile(prefix='tmp', suffix=''): | 
| Doug Zongker | fc44a51 | 2014-08-26 13:10:25 -0700 | [diff] [blame] | 1261 | """Make a temp file and add it to the list of things to be deleted | 
|  | 1262 | when Cleanup() is called.  Return the filename.""" | 
|  | 1263 | fd, fn = tempfile.mkstemp(prefix=prefix, suffix=suffix) | 
|  | 1264 | os.close(fd) | 
|  | 1265 | OPTIONS.tempfiles.append(fn) | 
|  | 1266 | return fn | 
|  | 1267 |  | 
|  | 1268 |  | 
| Tao Bao | 1c830bf | 2017-12-25 10:43:47 -0800 | [diff] [blame] | 1269 | def MakeTempDir(prefix='tmp', suffix=''): | 
|  | 1270 | """Makes a temporary dir that will be cleaned up with a call to Cleanup(). | 
|  | 1271 |  | 
|  | 1272 | Returns: | 
|  | 1273 | The absolute pathname of the new directory. | 
|  | 1274 | """ | 
|  | 1275 | dir_name = tempfile.mkdtemp(suffix=suffix, prefix=prefix) | 
|  | 1276 | OPTIONS.tempfiles.append(dir_name) | 
|  | 1277 | return dir_name | 
|  | 1278 |  | 
|  | 1279 |  | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1280 | def Cleanup(): | 
|  | 1281 | for i in OPTIONS.tempfiles: | 
|  | 1282 | if os.path.isdir(i): | 
| Tao Bao | 1c830bf | 2017-12-25 10:43:47 -0800 | [diff] [blame] | 1283 | shutil.rmtree(i, ignore_errors=True) | 
| Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 1284 | else: | 
|  | 1285 | os.remove(i) | 
| Tao Bao | 1c830bf | 2017-12-25 10:43:47 -0800 | [diff] [blame] | 1286 | del OPTIONS.tempfiles[:] | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1287 |  | 
|  | 1288 |  | 
|  | 1289 | class PasswordManager(object): | 
|  | 1290 | def __init__(self): | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1291 | self.editor = os.getenv("EDITOR") | 
|  | 1292 | self.pwfile = os.getenv("ANDROID_PW_FILE") | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1293 |  | 
|  | 1294 | def GetPasswords(self, items): | 
|  | 1295 | """Get passwords corresponding to each string in 'items', | 
|  | 1296 | returning a dict.  (The dict may have keys in addition to the | 
|  | 1297 | values in 'items'.) | 
|  | 1298 |  | 
|  | 1299 | Uses the passwords in $ANDROID_PW_FILE if available, letting the | 
|  | 1300 | user edit that file to add more needed passwords.  If no editor is | 
|  | 1301 | available, or $ANDROID_PW_FILE isn't define, prompts the user | 
|  | 1302 | interactively in the ordinary way. | 
|  | 1303 | """ | 
|  | 1304 |  | 
|  | 1305 | current = self.ReadFile() | 
|  | 1306 |  | 
|  | 1307 | first = True | 
|  | 1308 | while True: | 
|  | 1309 | missing = [] | 
|  | 1310 | for i in items: | 
|  | 1311 | if i not in current or not current[i]: | 
|  | 1312 | missing.append(i) | 
|  | 1313 | # Are all the passwords already in the file? | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1314 | if not missing: | 
|  | 1315 | return current | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1316 |  | 
|  | 1317 | for i in missing: | 
|  | 1318 | current[i] = "" | 
|  | 1319 |  | 
|  | 1320 | if not first: | 
| Tao Bao | 89fbb0f | 2017-01-10 10:47:58 -0800 | [diff] [blame] | 1321 | print("key file %s still missing some passwords." % (self.pwfile,)) | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1322 | answer = raw_input("try to edit again? [y]> ").strip() | 
|  | 1323 | if answer and answer[0] not in 'yY': | 
|  | 1324 | raise RuntimeError("key passwords unavailable") | 
|  | 1325 | first = False | 
|  | 1326 |  | 
|  | 1327 | current = self.UpdateAndReadFile(current) | 
|  | 1328 |  | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1329 | def PromptResult(self, current): # pylint: disable=no-self-use | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1330 | """Prompt the user to enter a value (password) for each key in | 
|  | 1331 | 'current' whose value is fales.  Returns a new dict with all the | 
|  | 1332 | values. | 
|  | 1333 | """ | 
|  | 1334 | result = {} | 
|  | 1335 | for k, v in sorted(current.iteritems()): | 
|  | 1336 | if v: | 
|  | 1337 | result[k] = v | 
|  | 1338 | else: | 
|  | 1339 | while True: | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1340 | result[k] = getpass.getpass( | 
|  | 1341 | "Enter password for %s key> " % k).strip() | 
|  | 1342 | if result[k]: | 
|  | 1343 | break | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1344 | return result | 
|  | 1345 |  | 
|  | 1346 | def UpdateAndReadFile(self, current): | 
|  | 1347 | if not self.editor or not self.pwfile: | 
|  | 1348 | return self.PromptResult(current) | 
|  | 1349 |  | 
|  | 1350 | f = open(self.pwfile, "w") | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1351 | os.chmod(self.pwfile, 0o600) | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1352 | f.write("# Enter key passwords between the [[[ ]]] brackets.\n") | 
|  | 1353 | f.write("# (Additional spaces are harmless.)\n\n") | 
|  | 1354 |  | 
|  | 1355 | first_line = None | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1356 | sorted_list = sorted([(not v, k, v) for (k, v) in current.iteritems()]) | 
|  | 1357 | for i, (_, k, v) in enumerate(sorted_list): | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1358 | f.write("[[[  %s  ]]] %s\n" % (v, k)) | 
|  | 1359 | if not v and first_line is None: | 
|  | 1360 | # position cursor on first line with no password. | 
|  | 1361 | first_line = i + 4 | 
|  | 1362 | f.close() | 
|  | 1363 |  | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 1364 | RunAndCheckOutput([self.editor, "+%d" % (first_line,), self.pwfile]) | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1365 |  | 
|  | 1366 | return self.ReadFile() | 
|  | 1367 |  | 
|  | 1368 | def ReadFile(self): | 
|  | 1369 | result = {} | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1370 | if self.pwfile is None: | 
|  | 1371 | return result | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1372 | try: | 
|  | 1373 | f = open(self.pwfile, "r") | 
|  | 1374 | for line in f: | 
|  | 1375 | line = line.strip() | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1376 | if not line or line[0] == '#': | 
|  | 1377 | continue | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1378 | m = re.match(r"^\[\[\[\s*(.*?)\s*\]\]\]\s*(\S+)$", line) | 
|  | 1379 | if not m: | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 1380 | logger.warning("Failed to parse password file: %s", line) | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1381 | else: | 
|  | 1382 | result[m.group(2)] = m.group(1) | 
|  | 1383 | f.close() | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1384 | except IOError as e: | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1385 | if e.errno != errno.ENOENT: | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 1386 | logger.exception("Error reading password file:") | 
| Doug Zongker | 8ce7c25 | 2009-05-22 13:34:54 -0700 | [diff] [blame] | 1387 | return result | 
| Doug Zongker | 048e7ca | 2009-06-15 14:31:53 -0700 | [diff] [blame] | 1388 |  | 
|  | 1389 |  | 
| Dan Albert | 8e0178d | 2015-01-27 15:53:15 -0800 | [diff] [blame] | 1390 | def ZipWrite(zip_file, filename, arcname=None, perms=0o644, | 
|  | 1391 | compress_type=None): | 
|  | 1392 | import datetime | 
|  | 1393 |  | 
|  | 1394 | # http://b/18015246 | 
|  | 1395 | # Python 2.7's zipfile implementation wrongly thinks that zip64 is required | 
|  | 1396 | # for files larger than 2GiB. We can work around this by adjusting their | 
|  | 1397 | # limit. Note that `zipfile.writestr()` will not work for strings larger than | 
|  | 1398 | # 2GiB. The Python interpreter sometimes rejects strings that large (though | 
|  | 1399 | # it isn't clear to me exactly what circumstances cause this). | 
|  | 1400 | # `zipfile.write()` must be used directly to work around this. | 
|  | 1401 | # | 
|  | 1402 | # This mess can be avoided if we port to python3. | 
|  | 1403 | saved_zip64_limit = zipfile.ZIP64_LIMIT | 
|  | 1404 | zipfile.ZIP64_LIMIT = (1 << 32) - 1 | 
|  | 1405 |  | 
|  | 1406 | if compress_type is None: | 
|  | 1407 | compress_type = zip_file.compression | 
|  | 1408 | if arcname is None: | 
|  | 1409 | arcname = filename | 
|  | 1410 |  | 
|  | 1411 | saved_stat = os.stat(filename) | 
|  | 1412 |  | 
|  | 1413 | try: | 
|  | 1414 | # `zipfile.write()` doesn't allow us to pass ZipInfo, so just modify the | 
|  | 1415 | # file to be zipped and reset it when we're done. | 
|  | 1416 | os.chmod(filename, perms) | 
|  | 1417 |  | 
|  | 1418 | # Use a fixed timestamp so the output is repeatable. | 
| Bryan Henry | e6d547d | 2018-07-31 18:32:00 -0700 | [diff] [blame] | 1419 | # Note: Use of fromtimestamp rather than utcfromtimestamp here is | 
|  | 1420 | # intentional. zip stores datetimes in local time without a time zone | 
|  | 1421 | # attached, so we need "epoch" but in the local time zone to get 2009/01/01 | 
|  | 1422 | # in the zip archive. | 
|  | 1423 | local_epoch = datetime.datetime.fromtimestamp(0) | 
|  | 1424 | timestamp = (datetime.datetime(2009, 1, 1) - local_epoch).total_seconds() | 
| Dan Albert | 8e0178d | 2015-01-27 15:53:15 -0800 | [diff] [blame] | 1425 | os.utime(filename, (timestamp, timestamp)) | 
|  | 1426 |  | 
|  | 1427 | zip_file.write(filename, arcname=arcname, compress_type=compress_type) | 
|  | 1428 | finally: | 
|  | 1429 | os.chmod(filename, saved_stat.st_mode) | 
|  | 1430 | os.utime(filename, (saved_stat.st_atime, saved_stat.st_mtime)) | 
|  | 1431 | zipfile.ZIP64_LIMIT = saved_zip64_limit | 
|  | 1432 |  | 
|  | 1433 |  | 
| Tao Bao | 58c1b96 | 2015-05-20 09:32:18 -0700 | [diff] [blame] | 1434 | def ZipWriteStr(zip_file, zinfo_or_arcname, data, perms=None, | 
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 1435 | compress_type=None): | 
|  | 1436 | """Wrap zipfile.writestr() function to work around the zip64 limit. | 
|  | 1437 |  | 
|  | 1438 | Even with the ZIP64_LIMIT workaround, it won't allow writing a string | 
|  | 1439 | longer than 2GiB. It gives 'OverflowError: size does not fit in an int' | 
|  | 1440 | when calling crc32(bytes). | 
|  | 1441 |  | 
|  | 1442 | But it still works fine to write a shorter string into a large zip file. | 
|  | 1443 | We should use ZipWrite() whenever possible, and only use ZipWriteStr() | 
|  | 1444 | when we know the string won't be too long. | 
|  | 1445 | """ | 
|  | 1446 |  | 
|  | 1447 | saved_zip64_limit = zipfile.ZIP64_LIMIT | 
|  | 1448 | zipfile.ZIP64_LIMIT = (1 << 32) - 1 | 
|  | 1449 |  | 
|  | 1450 | if not isinstance(zinfo_or_arcname, zipfile.ZipInfo): | 
|  | 1451 | zinfo = zipfile.ZipInfo(filename=zinfo_or_arcname) | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1452 | zinfo.compress_type = zip_file.compression | 
| Tao Bao | 58c1b96 | 2015-05-20 09:32:18 -0700 | [diff] [blame] | 1453 | if perms is None: | 
| Tao Bao | 2a41058 | 2015-07-10 17:18:23 -0700 | [diff] [blame] | 1454 | perms = 0o100644 | 
| Geremy Condra | 36bd365 | 2014-02-06 19:45:10 -0800 | [diff] [blame] | 1455 | else: | 
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 1456 | zinfo = zinfo_or_arcname | 
|  | 1457 |  | 
|  | 1458 | # If compress_type is given, it overrides the value in zinfo. | 
|  | 1459 | if compress_type is not None: | 
|  | 1460 | zinfo.compress_type = compress_type | 
|  | 1461 |  | 
| Tao Bao | 58c1b96 | 2015-05-20 09:32:18 -0700 | [diff] [blame] | 1462 | # If perms is given, it has a priority. | 
|  | 1463 | if perms is not None: | 
| Tao Bao | 2a41058 | 2015-07-10 17:18:23 -0700 | [diff] [blame] | 1464 | # If perms doesn't set the file type, mark it as a regular file. | 
|  | 1465 | if perms & 0o770000 == 0: | 
|  | 1466 | perms |= 0o100000 | 
| Tao Bao | 58c1b96 | 2015-05-20 09:32:18 -0700 | [diff] [blame] | 1467 | zinfo.external_attr = perms << 16 | 
|  | 1468 |  | 
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 1469 | # Use a fixed timestamp so the output is repeatable. | 
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 1470 | zinfo.date_time = (2009, 1, 1, 0, 0, 0) | 
|  | 1471 |  | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1472 | zip_file.writestr(zinfo, data) | 
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 1473 | zipfile.ZIP64_LIMIT = saved_zip64_limit | 
|  | 1474 |  | 
|  | 1475 |  | 
| Tao Bao | 89d7ab2 | 2017-12-14 17:05:33 -0800 | [diff] [blame] | 1476 | def ZipDelete(zip_filename, entries): | 
|  | 1477 | """Deletes entries from a ZIP file. | 
|  | 1478 |  | 
|  | 1479 | Since deleting entries from a ZIP file is not supported, it shells out to | 
|  | 1480 | 'zip -d'. | 
|  | 1481 |  | 
|  | 1482 | Args: | 
|  | 1483 | zip_filename: The name of the ZIP file. | 
|  | 1484 | entries: The name of the entry, or the list of names to be deleted. | 
|  | 1485 |  | 
|  | 1486 | Raises: | 
|  | 1487 | AssertionError: In case of non-zero return from 'zip'. | 
|  | 1488 | """ | 
|  | 1489 | if isinstance(entries, basestring): | 
|  | 1490 | entries = [entries] | 
|  | 1491 | cmd = ["zip", "-d", zip_filename] + entries | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 1492 | RunAndCheckOutput(cmd) | 
| Tao Bao | 89d7ab2 | 2017-12-14 17:05:33 -0800 | [diff] [blame] | 1493 |  | 
|  | 1494 |  | 
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 1495 | def ZipClose(zip_file): | 
|  | 1496 | # http://b/18015246 | 
|  | 1497 | # zipfile also refers to ZIP64_LIMIT during close() when it writes out the | 
|  | 1498 | # central directory. | 
|  | 1499 | saved_zip64_limit = zipfile.ZIP64_LIMIT | 
|  | 1500 | zipfile.ZIP64_LIMIT = (1 << 32) - 1 | 
|  | 1501 |  | 
|  | 1502 | zip_file.close() | 
|  | 1503 |  | 
|  | 1504 | zipfile.ZIP64_LIMIT = saved_zip64_limit | 
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1505 |  | 
|  | 1506 |  | 
|  | 1507 | class DeviceSpecificParams(object): | 
|  | 1508 | module = None | 
|  | 1509 | def __init__(self, **kwargs): | 
|  | 1510 | """Keyword arguments to the constructor become attributes of this | 
|  | 1511 | object, which is passed to all functions in the device-specific | 
|  | 1512 | module.""" | 
|  | 1513 | for k, v in kwargs.iteritems(): | 
|  | 1514 | setattr(self, k, v) | 
| Doug Zongker | 8bec09e | 2009-11-30 15:37:14 -0800 | [diff] [blame] | 1515 | self.extras = OPTIONS.extras | 
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1516 |  | 
|  | 1517 | if self.module is None: | 
|  | 1518 | path = OPTIONS.device_specific | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1519 | if not path: | 
|  | 1520 | return | 
| Doug Zongker | 8e2f2b9 | 2009-06-24 14:34:57 -0700 | [diff] [blame] | 1521 | try: | 
|  | 1522 | if os.path.isdir(path): | 
|  | 1523 | info = imp.find_module("releasetools", [path]) | 
|  | 1524 | else: | 
|  | 1525 | d, f = os.path.split(path) | 
|  | 1526 | b, x = os.path.splitext(f) | 
|  | 1527 | if x == ".py": | 
|  | 1528 | f = b | 
|  | 1529 | info = imp.find_module(f, [d]) | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 1530 | logger.info("loaded device-specific extensions from %s", path) | 
| Doug Zongker | 8e2f2b9 | 2009-06-24 14:34:57 -0700 | [diff] [blame] | 1531 | self.module = imp.load_module("device_specific", *info) | 
|  | 1532 | except ImportError: | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 1533 | logger.info("unable to load device-specific module; assuming none") | 
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1534 |  | 
|  | 1535 | def _DoCall(self, function_name, *args, **kwargs): | 
|  | 1536 | """Call the named function in the device-specific module, passing | 
|  | 1537 | the given args and kwargs.  The first argument to the call will be | 
|  | 1538 | the DeviceSpecific object itself.  If there is no module, or the | 
|  | 1539 | module does not define the function, return the value of the | 
|  | 1540 | 'default' kwarg (which itself defaults to None).""" | 
|  | 1541 | if self.module is None or not hasattr(self.module, function_name): | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1542 | return kwargs.get("default") | 
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1543 | return getattr(self.module, function_name)(*((self,) + args), **kwargs) | 
|  | 1544 |  | 
|  | 1545 | def FullOTA_Assertions(self): | 
|  | 1546 | """Called after emitting the block of assertions at the top of a | 
|  | 1547 | full OTA package.  Implementations can add whatever additional | 
|  | 1548 | assertions they like.""" | 
|  | 1549 | return self._DoCall("FullOTA_Assertions") | 
|  | 1550 |  | 
| Doug Zongker | e5ff590 | 2012-01-17 10:55:37 -0800 | [diff] [blame] | 1551 | def FullOTA_InstallBegin(self): | 
|  | 1552 | """Called at the start of full OTA installation.""" | 
|  | 1553 | return self._DoCall("FullOTA_InstallBegin") | 
|  | 1554 |  | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1555 | def FullOTA_GetBlockDifferences(self): | 
|  | 1556 | """Called during full OTA installation and verification. | 
|  | 1557 | Implementation should return a list of BlockDifference objects describing | 
|  | 1558 | the update on each additional partitions. | 
|  | 1559 | """ | 
|  | 1560 | return self._DoCall("FullOTA_GetBlockDifferences") | 
|  | 1561 |  | 
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1562 | def FullOTA_InstallEnd(self): | 
|  | 1563 | """Called at the end of full OTA installation; typically this is | 
|  | 1564 | used to install the image for the device's baseband processor.""" | 
|  | 1565 | return self._DoCall("FullOTA_InstallEnd") | 
|  | 1566 |  | 
|  | 1567 | def IncrementalOTA_Assertions(self): | 
|  | 1568 | """Called after emitting the block of assertions at the top of an | 
|  | 1569 | incremental OTA package.  Implementations can add whatever | 
|  | 1570 | additional assertions they like.""" | 
|  | 1571 | return self._DoCall("IncrementalOTA_Assertions") | 
|  | 1572 |  | 
| Doug Zongker | e5ff590 | 2012-01-17 10:55:37 -0800 | [diff] [blame] | 1573 | def IncrementalOTA_VerifyBegin(self): | 
|  | 1574 | """Called at the start of the verification phase of incremental | 
|  | 1575 | OTA installation; additional checks can be placed here to abort | 
|  | 1576 | the script before any changes are made.""" | 
|  | 1577 | return self._DoCall("IncrementalOTA_VerifyBegin") | 
|  | 1578 |  | 
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1579 | def IncrementalOTA_VerifyEnd(self): | 
|  | 1580 | """Called at the end of the verification phase of incremental OTA | 
|  | 1581 | installation; additional checks can be placed here to abort the | 
|  | 1582 | script before any changes are made.""" | 
|  | 1583 | return self._DoCall("IncrementalOTA_VerifyEnd") | 
|  | 1584 |  | 
| Doug Zongker | e5ff590 | 2012-01-17 10:55:37 -0800 | [diff] [blame] | 1585 | def IncrementalOTA_InstallBegin(self): | 
|  | 1586 | """Called at the start of incremental OTA installation (after | 
|  | 1587 | verification is complete).""" | 
|  | 1588 | return self._DoCall("IncrementalOTA_InstallBegin") | 
|  | 1589 |  | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1590 | def IncrementalOTA_GetBlockDifferences(self): | 
|  | 1591 | """Called during incremental OTA installation and verification. | 
|  | 1592 | Implementation should return a list of BlockDifference objects describing | 
|  | 1593 | the update on each additional partitions. | 
|  | 1594 | """ | 
|  | 1595 | return self._DoCall("IncrementalOTA_GetBlockDifferences") | 
|  | 1596 |  | 
| Doug Zongker | 05d3dea | 2009-06-22 11:32:31 -0700 | [diff] [blame] | 1597 | def IncrementalOTA_InstallEnd(self): | 
|  | 1598 | """Called at the end of incremental OTA installation; typically | 
|  | 1599 | this is used to install the image for the device's baseband | 
|  | 1600 | processor.""" | 
|  | 1601 | return self._DoCall("IncrementalOTA_InstallEnd") | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1602 |  | 
| Tao Bao | 9bc6bb2 | 2015-11-09 16:58:28 -0800 | [diff] [blame] | 1603 | def VerifyOTA_Assertions(self): | 
|  | 1604 | return self._DoCall("VerifyOTA_Assertions") | 
|  | 1605 |  | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1606 |  | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1607 | class File(object): | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1608 | def __init__(self, name, data, compress_size=None): | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1609 | self.name = name | 
|  | 1610 | self.data = data | 
|  | 1611 | self.size = len(data) | 
| YOUNG HO CHA | ccc5c40 | 2016-10-13 13:40:46 +0900 | [diff] [blame] | 1612 | self.compress_size = compress_size or self.size | 
| Doug Zongker | 55d9328 | 2011-01-25 17:03:34 -0800 | [diff] [blame] | 1613 | self.sha1 = sha1(data).hexdigest() | 
|  | 1614 |  | 
|  | 1615 | @classmethod | 
|  | 1616 | def FromLocalFile(cls, name, diskname): | 
|  | 1617 | f = open(diskname, "rb") | 
|  | 1618 | data = f.read() | 
|  | 1619 | f.close() | 
|  | 1620 | return File(name, data) | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1621 |  | 
|  | 1622 | def WriteToTemp(self): | 
|  | 1623 | t = tempfile.NamedTemporaryFile() | 
|  | 1624 | t.write(self.data) | 
|  | 1625 | t.flush() | 
|  | 1626 | return t | 
|  | 1627 |  | 
| Dan Willemsen | 2ee00d5 | 2017-03-05 19:51:56 -0800 | [diff] [blame] | 1628 | def WriteToDir(self, d): | 
|  | 1629 | with open(os.path.join(d, self.name), "wb") as fp: | 
|  | 1630 | fp.write(self.data) | 
|  | 1631 |  | 
| Geremy Condra | 36bd365 | 2014-02-06 19:45:10 -0800 | [diff] [blame] | 1632 | def AddToZip(self, z, compression=None): | 
| Tao Bao | f3282b4 | 2015-04-01 11:21:55 -0700 | [diff] [blame] | 1633 | ZipWriteStr(z, self.name, self.data, compress_type=compression) | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1634 |  | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1635 |  | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1636 | DIFF_PROGRAM_BY_EXT = { | 
|  | 1637 | ".gz" : "imgdiff", | 
|  | 1638 | ".zip" : ["imgdiff", "-z"], | 
|  | 1639 | ".jar" : ["imgdiff", "-z"], | 
|  | 1640 | ".apk" : ["imgdiff", "-z"], | 
|  | 1641 | ".img" : "imgdiff", | 
|  | 1642 | } | 
|  | 1643 |  | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1644 |  | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1645 | class Difference(object): | 
| Doug Zongker | 24cd280 | 2012-08-14 16:36:15 -0700 | [diff] [blame] | 1646 | def __init__(self, tf, sf, diff_program=None): | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1647 | self.tf = tf | 
|  | 1648 | self.sf = sf | 
|  | 1649 | self.patch = None | 
| Doug Zongker | 24cd280 | 2012-08-14 16:36:15 -0700 | [diff] [blame] | 1650 | self.diff_program = diff_program | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1651 |  | 
|  | 1652 | def ComputePatch(self): | 
|  | 1653 | """Compute the patch (as a string of data) needed to turn sf into | 
|  | 1654 | tf.  Returns the same tuple as GetPatch().""" | 
|  | 1655 |  | 
|  | 1656 | tf = self.tf | 
|  | 1657 | sf = self.sf | 
|  | 1658 |  | 
| Doug Zongker | 24cd280 | 2012-08-14 16:36:15 -0700 | [diff] [blame] | 1659 | if self.diff_program: | 
|  | 1660 | diff_program = self.diff_program | 
|  | 1661 | else: | 
|  | 1662 | ext = os.path.splitext(tf.name)[1] | 
|  | 1663 | diff_program = DIFF_PROGRAM_BY_EXT.get(ext, "bsdiff") | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1664 |  | 
|  | 1665 | ttemp = tf.WriteToTemp() | 
|  | 1666 | stemp = sf.WriteToTemp() | 
|  | 1667 |  | 
|  | 1668 | ext = os.path.splitext(tf.name)[1] | 
|  | 1669 |  | 
|  | 1670 | try: | 
|  | 1671 | ptemp = tempfile.NamedTemporaryFile() | 
|  | 1672 | if isinstance(diff_program, list): | 
|  | 1673 | cmd = copy.copy(diff_program) | 
|  | 1674 | else: | 
|  | 1675 | cmd = [diff_program] | 
|  | 1676 | cmd.append(stemp.name) | 
|  | 1677 | cmd.append(ttemp.name) | 
|  | 1678 | cmd.append(ptemp.name) | 
|  | 1679 | p = Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | 
| Doug Zongker | f834008 | 2014-08-05 10:39:37 -0700 | [diff] [blame] | 1680 | err = [] | 
|  | 1681 | def run(): | 
|  | 1682 | _, e = p.communicate() | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1683 | if e: | 
|  | 1684 | err.append(e) | 
| Doug Zongker | f834008 | 2014-08-05 10:39:37 -0700 | [diff] [blame] | 1685 | th = threading.Thread(target=run) | 
|  | 1686 | th.start() | 
|  | 1687 | th.join(timeout=300)   # 5 mins | 
|  | 1688 | if th.is_alive(): | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 1689 | logger.warning("diff command timed out") | 
| Doug Zongker | f834008 | 2014-08-05 10:39:37 -0700 | [diff] [blame] | 1690 | p.terminate() | 
|  | 1691 | th.join(5) | 
|  | 1692 | if th.is_alive(): | 
|  | 1693 | p.kill() | 
|  | 1694 | th.join() | 
|  | 1695 |  | 
| Tianjie Xu | a2a9f99 | 2018-01-05 15:15:54 -0800 | [diff] [blame] | 1696 | if p.returncode != 0: | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 1697 | logger.warning("Failure running %s:\n%s\n", diff_program, "".join(err)) | 
| Doug Zongker | f834008 | 2014-08-05 10:39:37 -0700 | [diff] [blame] | 1698 | self.patch = None | 
|  | 1699 | return None, None, None | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1700 | diff = ptemp.read() | 
|  | 1701 | finally: | 
|  | 1702 | ptemp.close() | 
|  | 1703 | stemp.close() | 
|  | 1704 | ttemp.close() | 
|  | 1705 |  | 
|  | 1706 | self.patch = diff | 
|  | 1707 | return self.tf, self.sf, self.patch | 
|  | 1708 |  | 
|  | 1709 |  | 
|  | 1710 | def GetPatch(self): | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1711 | """Returns a tuple of (target_file, source_file, patch_data). | 
|  | 1712 |  | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1713 | patch_data may be None if ComputePatch hasn't been called, or if | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1714 | computing the patch failed. | 
|  | 1715 | """ | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1716 | return self.tf, self.sf, self.patch | 
|  | 1717 |  | 
|  | 1718 |  | 
|  | 1719 | def ComputeDifferences(diffs): | 
|  | 1720 | """Call ComputePatch on all the Difference objects in 'diffs'.""" | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 1721 | logger.info("%d diffs to compute", len(diffs)) | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1722 |  | 
|  | 1723 | # Do the largest files first, to try and reduce the long-pole effect. | 
|  | 1724 | by_size = [(i.tf.size, i) for i in diffs] | 
|  | 1725 | by_size.sort(reverse=True) | 
|  | 1726 | by_size = [i[1] for i in by_size] | 
|  | 1727 |  | 
|  | 1728 | lock = threading.Lock() | 
|  | 1729 | diff_iter = iter(by_size)   # accessed under lock | 
|  | 1730 |  | 
|  | 1731 | def worker(): | 
|  | 1732 | try: | 
|  | 1733 | lock.acquire() | 
|  | 1734 | for d in diff_iter: | 
|  | 1735 | lock.release() | 
|  | 1736 | start = time.time() | 
|  | 1737 | d.ComputePatch() | 
|  | 1738 | dur = time.time() - start | 
|  | 1739 | lock.acquire() | 
|  | 1740 |  | 
|  | 1741 | tf, sf, patch = d.GetPatch() | 
|  | 1742 | if sf.name == tf.name: | 
|  | 1743 | name = tf.name | 
|  | 1744 | else: | 
|  | 1745 | name = "%s (%s)" % (tf.name, sf.name) | 
|  | 1746 | if patch is None: | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 1747 | logger.error("patching failed! %40s", name) | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1748 | else: | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 1749 | logger.info( | 
|  | 1750 | "%8.2f sec %8d / %8d bytes (%6.2f%%) %s", dur, len(patch), | 
|  | 1751 | tf.size, 100.0 * len(patch) / tf.size, name) | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1752 | lock.release() | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 1753 | except Exception: | 
|  | 1754 | logger.exception("Failed to compute diff from worker") | 
| Doug Zongker | ea5d7a9 | 2010-09-12 15:26:16 -0700 | [diff] [blame] | 1755 | raise | 
|  | 1756 |  | 
|  | 1757 | # start worker threads; wait for them all to finish. | 
|  | 1758 | threads = [threading.Thread(target=worker) | 
|  | 1759 | for i in range(OPTIONS.worker_threads)] | 
|  | 1760 | for th in threads: | 
|  | 1761 | th.start() | 
|  | 1762 | while threads: | 
|  | 1763 | threads.pop().join() | 
| Doug Zongker | 96a57e7 | 2010-09-26 14:57:41 -0700 | [diff] [blame] | 1764 |  | 
|  | 1765 |  | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1766 | class BlockDifference(object): | 
|  | 1767 | def __init__(self, partition, tgt, src=None, check_first_block=False, | 
| Tao Bao | 293fd13 | 2016-06-11 12:19:23 -0700 | [diff] [blame] | 1768 | version=None, disable_imgdiff=False): | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1769 | self.tgt = tgt | 
|  | 1770 | self.src = src | 
|  | 1771 | self.partition = partition | 
| Doug Zongker | b34fcce | 2014-09-11 09:34:56 -0700 | [diff] [blame] | 1772 | self.check_first_block = check_first_block | 
| Tao Bao | 293fd13 | 2016-06-11 12:19:23 -0700 | [diff] [blame] | 1773 | self.disable_imgdiff = disable_imgdiff | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1774 |  | 
| Tao Bao | dd2a589 | 2015-03-12 12:32:37 -0700 | [diff] [blame] | 1775 | if version is None: | 
| Tao Bao | 0582cb6 | 2017-12-21 11:47:01 -0800 | [diff] [blame] | 1776 | version = max( | 
|  | 1777 | int(i) for i in | 
|  | 1778 | OPTIONS.info_dict.get("blockimgdiff_versions", "1").split(",")) | 
| Tao Bao | 8fad03e | 2017-03-01 14:36:26 -0800 | [diff] [blame] | 1779 | assert version >= 3 | 
| Tao Bao | dd2a589 | 2015-03-12 12:32:37 -0700 | [diff] [blame] | 1780 | self.version = version | 
| Doug Zongker | 6233818 | 2014-09-08 08:29:55 -0700 | [diff] [blame] | 1781 |  | 
|  | 1782 | b = blockimgdiff.BlockImageDiff(tgt, src, threads=OPTIONS.worker_threads, | 
| Tao Bao | 293fd13 | 2016-06-11 12:19:23 -0700 | [diff] [blame] | 1783 | version=self.version, | 
|  | 1784 | disable_imgdiff=self.disable_imgdiff) | 
| Tao Bao | 04bce3a | 2018-02-28 11:11:00 -0800 | [diff] [blame] | 1785 | self.path = os.path.join(MakeTempDir(), partition) | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1786 | b.Compute(self.path) | 
| Tao Bao | d8d14be | 2016-02-04 14:26:02 -0800 | [diff] [blame] | 1787 | self._required_cache = b.max_stashed_size | 
| Tao Bao | d522bdc | 2016-04-12 15:53:16 -0700 | [diff] [blame] | 1788 | self.touched_src_ranges = b.touched_src_ranges | 
|  | 1789 | self.touched_src_sha1 = b.touched_src_sha1 | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1790 |  | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1791 | # On devices with dynamic partitions, for new partitions, | 
|  | 1792 | # src is None but OPTIONS.source_info_dict is not. | 
|  | 1793 | if OPTIONS.source_info_dict is None: | 
|  | 1794 | is_dynamic_build = OPTIONS.info_dict.get( | 
|  | 1795 | "use_dynamic_partitions") == "true" | 
| Yifan Hong | bb2658d | 2019-01-25 12:30:58 -0800 | [diff] [blame] | 1796 | is_dynamic_source = False | 
| Tao Bao | aac4ad5 | 2015-10-16 15:26:34 -0700 | [diff] [blame] | 1797 | else: | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1798 | is_dynamic_build = OPTIONS.source_info_dict.get( | 
|  | 1799 | "use_dynamic_partitions") == "true" | 
| Yifan Hong | bb2658d | 2019-01-25 12:30:58 -0800 | [diff] [blame] | 1800 | is_dynamic_source = partition in shlex.split( | 
|  | 1801 | OPTIONS.source_info_dict.get("dynamic_partition_list", "").strip()) | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1802 |  | 
| Yifan Hong | bb2658d | 2019-01-25 12:30:58 -0800 | [diff] [blame] | 1803 | is_dynamic_target = partition in shlex.split( | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1804 | OPTIONS.info_dict.get("dynamic_partition_list", "").strip()) | 
|  | 1805 |  | 
| Yifan Hong | bb2658d | 2019-01-25 12:30:58 -0800 | [diff] [blame] | 1806 | # For dynamic partitions builds, check partition list in both source | 
|  | 1807 | # and target build because new partitions may be added, and existing | 
|  | 1808 | # partitions may be removed. | 
|  | 1809 | is_dynamic = is_dynamic_build and (is_dynamic_source or is_dynamic_target) | 
|  | 1810 |  | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1811 | if is_dynamic: | 
|  | 1812 | self.device = 'map_partition("%s")' % partition | 
|  | 1813 | else: | 
|  | 1814 | if OPTIONS.source_info_dict is None: | 
|  | 1815 | _, device_path = GetTypeAndDevice("/" + partition, OPTIONS.info_dict) | 
|  | 1816 | else: | 
|  | 1817 | _, device_path = GetTypeAndDevice("/" + partition, | 
|  | 1818 | OPTIONS.source_info_dict) | 
|  | 1819 | self.device = '"%s"' % device_path | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1820 |  | 
| Tao Bao | d8d14be | 2016-02-04 14:26:02 -0800 | [diff] [blame] | 1821 | @property | 
|  | 1822 | def required_cache(self): | 
|  | 1823 | return self._required_cache | 
|  | 1824 |  | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1825 | def WriteScript(self, script, output_zip, progress=None, | 
|  | 1826 | write_verify_script=False): | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1827 | if not self.src: | 
|  | 1828 | # write the output unconditionally | 
| Jesse Zhao | 75bcea0 | 2015-01-06 10:59:53 -0800 | [diff] [blame] | 1829 | script.Print("Patching %s image unconditionally..." % (self.partition,)) | 
|  | 1830 | else: | 
|  | 1831 | script.Print("Patching %s image after verification." % (self.partition,)) | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1832 |  | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1833 | if progress: | 
|  | 1834 | script.ShowProgress(progress, 0) | 
| Jesse Zhao | 75bcea0 | 2015-01-06 10:59:53 -0800 | [diff] [blame] | 1835 | self._WriteUpdate(script, output_zip) | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1836 |  | 
|  | 1837 | if write_verify_script: | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1838 | self.WritePostInstallVerifyScript(script) | 
| Jesse Zhao | 75bcea0 | 2015-01-06 10:59:53 -0800 | [diff] [blame] | 1839 |  | 
| Tao Bao | 9bc6bb2 | 2015-11-09 16:58:28 -0800 | [diff] [blame] | 1840 | def WriteStrictVerifyScript(self, script): | 
|  | 1841 | """Verify all the blocks in the care_map, including clobbered blocks. | 
|  | 1842 |  | 
|  | 1843 | This differs from the WriteVerifyScript() function: a) it prints different | 
|  | 1844 | error messages; b) it doesn't allow half-way updated images to pass the | 
|  | 1845 | verification.""" | 
|  | 1846 |  | 
|  | 1847 | partition = self.partition | 
|  | 1848 | script.Print("Verifying %s..." % (partition,)) | 
|  | 1849 | ranges = self.tgt.care_map | 
|  | 1850 | ranges_str = ranges.to_string_raw() | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1851 | script.AppendExtra( | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1852 | 'range_sha1(%s, "%s") == "%s" && ui_print("    Verified.") || ' | 
|  | 1853 | 'ui_print("%s has unexpected contents.");' % ( | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1854 | self.device, ranges_str, | 
|  | 1855 | self.tgt.TotalSha1(include_clobbered_blocks=True), | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1856 | self.partition)) | 
| Tao Bao | 9bc6bb2 | 2015-11-09 16:58:28 -0800 | [diff] [blame] | 1857 | script.AppendExtra("") | 
|  | 1858 |  | 
| Tao Bao | d522bdc | 2016-04-12 15:53:16 -0700 | [diff] [blame] | 1859 | def WriteVerifyScript(self, script, touched_blocks_only=False): | 
| Sami Tolvanen | dd67a29 | 2014-12-09 16:40:34 +0000 | [diff] [blame] | 1860 | partition = self.partition | 
| Tao Bao | f9efe28 | 2016-04-14 15:58:05 -0700 | [diff] [blame] | 1861 |  | 
|  | 1862 | # full OTA | 
| Jesse Zhao | 75bcea0 | 2015-01-06 10:59:53 -0800 | [diff] [blame] | 1863 | if not self.src: | 
| Sami Tolvanen | dd67a29 | 2014-12-09 16:40:34 +0000 | [diff] [blame] | 1864 | script.Print("Image %s will be patched unconditionally." % (partition,)) | 
| Tao Bao | f9efe28 | 2016-04-14 15:58:05 -0700 | [diff] [blame] | 1865 |  | 
|  | 1866 | # incremental OTA | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1867 | else: | 
| Tao Bao | 8fad03e | 2017-03-01 14:36:26 -0800 | [diff] [blame] | 1868 | if touched_blocks_only: | 
| Tao Bao | d522bdc | 2016-04-12 15:53:16 -0700 | [diff] [blame] | 1869 | ranges = self.touched_src_ranges | 
|  | 1870 | expected_sha1 = self.touched_src_sha1 | 
|  | 1871 | else: | 
|  | 1872 | ranges = self.src.care_map.subtract(self.src.clobbered_blocks) | 
|  | 1873 | expected_sha1 = self.src.TotalSha1() | 
| Tao Bao | f9efe28 | 2016-04-14 15:58:05 -0700 | [diff] [blame] | 1874 |  | 
|  | 1875 | # No blocks to be checked, skipping. | 
|  | 1876 | if not ranges: | 
|  | 1877 | return | 
|  | 1878 |  | 
| Tao Bao | 5ece99d | 2015-05-12 11:42:31 -0700 | [diff] [blame] | 1879 | ranges_str = ranges.to_string_raw() | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1880 | script.AppendExtra( | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1881 | 'if (range_sha1(%s, "%s") == "%s" || block_image_verify(%s, ' | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1882 | 'package_extract_file("%s.transfer.list"), "%s.new.dat", ' | 
|  | 1883 | '"%s.patch.dat")) then' % ( | 
|  | 1884 | self.device, ranges_str, expected_sha1, | 
|  | 1885 | self.device, partition, partition, partition)) | 
| Tao Bao | dd2a589 | 2015-03-12 12:32:37 -0700 | [diff] [blame] | 1886 | script.Print('Verified %s image...' % (partition,)) | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 1887 | script.AppendExtra('else') | 
| Sami Tolvanen | dd67a29 | 2014-12-09 16:40:34 +0000 | [diff] [blame] | 1888 |  | 
| Tianjie Xu | fc3422a | 2015-12-15 11:53:59 -0800 | [diff] [blame] | 1889 | if self.version >= 4: | 
|  | 1890 |  | 
|  | 1891 | # Bug: 21124327 | 
|  | 1892 | # When generating incrementals for the system and vendor partitions in | 
|  | 1893 | # version 4 or newer, explicitly check the first block (which contains | 
|  | 1894 | # the superblock) of the partition to see if it's what we expect. If | 
|  | 1895 | # this check fails, give an explicit log message about the partition | 
|  | 1896 | # having been remounted R/W (the most likely explanation). | 
|  | 1897 | if self.check_first_block: | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1898 | script.AppendExtra('check_first_block(%s);' % (self.device,)) | 
| Tianjie Xu | fc3422a | 2015-12-15 11:53:59 -0800 | [diff] [blame] | 1899 |  | 
|  | 1900 | # If version >= 4, try block recovery before abort update | 
| Tianjie Xu | 209db46 | 2016-05-24 17:34:52 -0700 | [diff] [blame] | 1901 | if partition == "system": | 
|  | 1902 | code = ErrorCode.SYSTEM_RECOVER_FAILURE | 
|  | 1903 | else: | 
|  | 1904 | code = ErrorCode.VENDOR_RECOVER_FAILURE | 
| Tianjie Xu | fc3422a | 2015-12-15 11:53:59 -0800 | [diff] [blame] | 1905 | script.AppendExtra(( | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1906 | 'ifelse (block_image_recover({device}, "{ranges}") && ' | 
|  | 1907 | 'block_image_verify({device}, ' | 
| Tianjie Xu | fc3422a | 2015-12-15 11:53:59 -0800 | [diff] [blame] | 1908 | 'package_extract_file("{partition}.transfer.list"), ' | 
|  | 1909 | '"{partition}.new.dat", "{partition}.patch.dat"), ' | 
|  | 1910 | 'ui_print("{partition} recovered successfully."), ' | 
| Tianjie Xu | 209db46 | 2016-05-24 17:34:52 -0700 | [diff] [blame] | 1911 | 'abort("E{code}: {partition} partition fails to recover"));\n' | 
| Tianjie Xu | fc3422a | 2015-12-15 11:53:59 -0800 | [diff] [blame] | 1912 | 'endif;').format(device=self.device, ranges=ranges_str, | 
| Tianjie Xu | 209db46 | 2016-05-24 17:34:52 -0700 | [diff] [blame] | 1913 | partition=partition, code=code)) | 
| Doug Zongker | b34fcce | 2014-09-11 09:34:56 -0700 | [diff] [blame] | 1914 |  | 
| Tao Bao | dd2a589 | 2015-03-12 12:32:37 -0700 | [diff] [blame] | 1915 | # Abort the OTA update. Note that the incremental OTA cannot be applied | 
|  | 1916 | # even if it may match the checksum of the target partition. | 
|  | 1917 | # a) If version < 3, operations like move and erase will make changes | 
|  | 1918 | #    unconditionally and damage the partition. | 
|  | 1919 | # b) If version >= 3, it won't even reach here. | 
| Tianjie Xu | fc3422a | 2015-12-15 11:53:59 -0800 | [diff] [blame] | 1920 | else: | 
| Tianjie Xu | 209db46 | 2016-05-24 17:34:52 -0700 | [diff] [blame] | 1921 | if partition == "system": | 
|  | 1922 | code = ErrorCode.SYSTEM_VERIFICATION_FAILURE | 
|  | 1923 | else: | 
|  | 1924 | code = ErrorCode.VENDOR_VERIFICATION_FAILURE | 
|  | 1925 | script.AppendExtra(( | 
|  | 1926 | 'abort("E%d: %s partition has unexpected contents");\n' | 
|  | 1927 | 'endif;') % (code, partition)) | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1928 |  | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1929 | def WritePostInstallVerifyScript(self, script): | 
| Tao Bao | 5fcaaef | 2015-06-01 13:40:49 -0700 | [diff] [blame] | 1930 | partition = self.partition | 
|  | 1931 | script.Print('Verifying the updated %s image...' % (partition,)) | 
|  | 1932 | # Unlike pre-install verification, clobbered_blocks should not be ignored. | 
|  | 1933 | ranges = self.tgt.care_map | 
|  | 1934 | ranges_str = ranges.to_string_raw() | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1935 | script.AppendExtra( | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1936 | 'if range_sha1(%s, "%s") == "%s" then' % ( | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1937 | self.device, ranges_str, | 
|  | 1938 | self.tgt.TotalSha1(include_clobbered_blocks=True))) | 
| Tao Bao | e9b6191 | 2015-07-09 17:37:49 -0700 | [diff] [blame] | 1939 |  | 
|  | 1940 | # Bug: 20881595 | 
|  | 1941 | # Verify that extended blocks are really zeroed out. | 
|  | 1942 | if self.tgt.extended: | 
|  | 1943 | ranges_str = self.tgt.extended.to_string_raw() | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1944 | script.AppendExtra( | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 1945 | 'if range_sha1(%s, "%s") == "%s" then' % ( | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1946 | self.device, ranges_str, | 
|  | 1947 | self._HashZeroBlocks(self.tgt.extended.size()))) | 
| Tao Bao | e9b6191 | 2015-07-09 17:37:49 -0700 | [diff] [blame] | 1948 | script.Print('Verified the updated %s image.' % (partition,)) | 
| Tianjie Xu | 209db46 | 2016-05-24 17:34:52 -0700 | [diff] [blame] | 1949 | if partition == "system": | 
|  | 1950 | code = ErrorCode.SYSTEM_NONZERO_CONTENTS | 
|  | 1951 | else: | 
|  | 1952 | code = ErrorCode.VENDOR_NONZERO_CONTENTS | 
| Tao Bao | e9b6191 | 2015-07-09 17:37:49 -0700 | [diff] [blame] | 1953 | script.AppendExtra( | 
|  | 1954 | 'else\n' | 
| Tianjie Xu | 209db46 | 2016-05-24 17:34:52 -0700 | [diff] [blame] | 1955 | '  abort("E%d: %s partition has unexpected non-zero contents after ' | 
|  | 1956 | 'OTA update");\n' | 
|  | 1957 | 'endif;' % (code, partition)) | 
| Tao Bao | e9b6191 | 2015-07-09 17:37:49 -0700 | [diff] [blame] | 1958 | else: | 
|  | 1959 | script.Print('Verified the updated %s image.' % (partition,)) | 
|  | 1960 |  | 
| Tianjie Xu | 209db46 | 2016-05-24 17:34:52 -0700 | [diff] [blame] | 1961 | if partition == "system": | 
|  | 1962 | code = ErrorCode.SYSTEM_UNEXPECTED_CONTENTS | 
|  | 1963 | else: | 
|  | 1964 | code = ErrorCode.VENDOR_UNEXPECTED_CONTENTS | 
|  | 1965 |  | 
| Tao Bao | 5fcaaef | 2015-06-01 13:40:49 -0700 | [diff] [blame] | 1966 | script.AppendExtra( | 
|  | 1967 | 'else\n' | 
| Tianjie Xu | 209db46 | 2016-05-24 17:34:52 -0700 | [diff] [blame] | 1968 | '  abort("E%d: %s partition has unexpected contents after OTA ' | 
|  | 1969 | 'update");\n' | 
|  | 1970 | 'endif;' % (code, partition)) | 
| Tao Bao | 5fcaaef | 2015-06-01 13:40:49 -0700 | [diff] [blame] | 1971 |  | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 1972 | def _WriteUpdate(self, script, output_zip): | 
| Dan Albert | 8e0178d | 2015-01-27 15:53:15 -0800 | [diff] [blame] | 1973 | ZipWrite(output_zip, | 
|  | 1974 | '{}.transfer.list'.format(self.path), | 
|  | 1975 | '{}.transfer.list'.format(self.partition)) | 
| Tianjie Xu | b0a29ad | 2017-07-06 15:13:59 -0700 | [diff] [blame] | 1976 |  | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 1977 | # For full OTA, compress the new.dat with brotli with quality 6 to reduce | 
|  | 1978 | # its size. Quailty 9 almost triples the compression time but doesn't | 
|  | 1979 | # further reduce the size too much. For a typical 1.8G system.new.dat | 
| Tianjie Xu | b0a29ad | 2017-07-06 15:13:59 -0700 | [diff] [blame] | 1980 | #                       zip  | brotli(quality 6)  | brotli(quality 9) | 
|  | 1981 | #   compressed_size:    942M | 869M (~8% reduced) | 854M | 
|  | 1982 | #   compression_time:   75s  | 265s               | 719s | 
|  | 1983 | #   decompression_time: 15s  | 25s                | 25s | 
|  | 1984 |  | 
|  | 1985 | if not self.src: | 
| Alex Deymo | b10e07a | 2017-11-09 23:53:42 +0100 | [diff] [blame] | 1986 | brotli_cmd = ['brotli', '--quality=6', | 
|  | 1987 | '--output={}.new.dat.br'.format(self.path), | 
|  | 1988 | '{}.new.dat'.format(self.path)] | 
| Tianjie Xu | b0a29ad | 2017-07-06 15:13:59 -0700 | [diff] [blame] | 1989 | print("Compressing {}.new.dat with brotli".format(self.partition)) | 
| Tao Bao | 986ee86 | 2018-10-04 15:46:16 -0700 | [diff] [blame] | 1990 | RunAndCheckOutput(brotli_cmd) | 
| Tianjie Xu | b0a29ad | 2017-07-06 15:13:59 -0700 | [diff] [blame] | 1991 |  | 
|  | 1992 | new_data_name = '{}.new.dat.br'.format(self.partition) | 
|  | 1993 | ZipWrite(output_zip, | 
|  | 1994 | '{}.new.dat.br'.format(self.path), | 
|  | 1995 | new_data_name, | 
|  | 1996 | compress_type=zipfile.ZIP_STORED) | 
|  | 1997 | else: | 
|  | 1998 | new_data_name = '{}.new.dat'.format(self.partition) | 
|  | 1999 | ZipWrite(output_zip, '{}.new.dat'.format(self.path), new_data_name) | 
|  | 2000 |  | 
| Dan Albert | 8e0178d | 2015-01-27 15:53:15 -0800 | [diff] [blame] | 2001 | ZipWrite(output_zip, | 
|  | 2002 | '{}.patch.dat'.format(self.path), | 
|  | 2003 | '{}.patch.dat'.format(self.partition), | 
|  | 2004 | compress_type=zipfile.ZIP_STORED) | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 2005 |  | 
| Tianjie Xu | 209db46 | 2016-05-24 17:34:52 -0700 | [diff] [blame] | 2006 | if self.partition == "system": | 
|  | 2007 | code = ErrorCode.SYSTEM_UPDATE_FAILURE | 
|  | 2008 | else: | 
|  | 2009 | code = ErrorCode.VENDOR_UPDATE_FAILURE | 
|  | 2010 |  | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 2011 | call = ('block_image_update({device}, ' | 
| Dan Albert | 8e0178d | 2015-01-27 15:53:15 -0800 | [diff] [blame] | 2012 | 'package_extract_file("{partition}.transfer.list"), ' | 
| Tianjie Xu | b0a29ad | 2017-07-06 15:13:59 -0700 | [diff] [blame] | 2013 | '"{new_data_name}", "{partition}.patch.dat") ||\n' | 
| Tianjie Xu | 209db46 | 2016-05-24 17:34:52 -0700 | [diff] [blame] | 2014 | '  abort("E{code}: Failed to update {partition} image.");'.format( | 
| Tianjie Xu | b0a29ad | 2017-07-06 15:13:59 -0700 | [diff] [blame] | 2015 | device=self.device, partition=self.partition, | 
|  | 2016 | new_data_name=new_data_name, code=code)) | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 2017 | script.AppendExtra(script.WordWrap(call)) | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 2018 |  | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 2019 | def _HashBlocks(self, source, ranges): # pylint: disable=no-self-use | 
| Sami Tolvanen | dd67a29 | 2014-12-09 16:40:34 +0000 | [diff] [blame] | 2020 | data = source.ReadRangeSet(ranges) | 
|  | 2021 | ctx = sha1() | 
|  | 2022 |  | 
|  | 2023 | for p in data: | 
|  | 2024 | ctx.update(p) | 
|  | 2025 |  | 
|  | 2026 | return ctx.hexdigest() | 
|  | 2027 |  | 
| Tao Bao | e9b6191 | 2015-07-09 17:37:49 -0700 | [diff] [blame] | 2028 | def _HashZeroBlocks(self, num_blocks): # pylint: disable=no-self-use | 
|  | 2029 | """Return the hash value for all zero blocks.""" | 
|  | 2030 | zero_block = '\x00' * 4096 | 
|  | 2031 | ctx = sha1() | 
|  | 2032 | for _ in range(num_blocks): | 
|  | 2033 | ctx.update(zero_block) | 
|  | 2034 |  | 
|  | 2035 | return ctx.hexdigest() | 
|  | 2036 |  | 
| Doug Zongker | ab7ca1d | 2014-08-26 10:40:28 -0700 | [diff] [blame] | 2037 |  | 
|  | 2038 | DataImage = blockimgdiff.DataImage | 
|  | 2039 |  | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 2040 |  | 
| Doug Zongker | 96a57e7 | 2010-09-26 14:57:41 -0700 | [diff] [blame] | 2041 | # map recovery.fstab's fs_types to mount/format "partition types" | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 2042 | PARTITION_TYPES = { | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 2043 | "ext4": "EMMC", | 
|  | 2044 | "emmc": "EMMC", | 
| Mohamad Ayyash | 95e74c1 | 2015-05-01 15:39:36 -0700 | [diff] [blame] | 2045 | "f2fs": "EMMC", | 
|  | 2046 | "squashfs": "EMMC" | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 2047 | } | 
| Doug Zongker | 96a57e7 | 2010-09-26 14:57:41 -0700 | [diff] [blame] | 2048 |  | 
| Tao Bao | 76def24 | 2017-11-21 09:25:31 -0800 | [diff] [blame] | 2049 |  | 
| Doug Zongker | 96a57e7 | 2010-09-26 14:57:41 -0700 | [diff] [blame] | 2050 | def GetTypeAndDevice(mount_point, info): | 
|  | 2051 | fstab = info["fstab"] | 
|  | 2052 | if fstab: | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 2053 | return (PARTITION_TYPES[fstab[mount_point].fs_type], | 
|  | 2054 | fstab[mount_point].device) | 
| Doug Zongker | 96a57e7 | 2010-09-26 14:57:41 -0700 | [diff] [blame] | 2055 | else: | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 2056 | raise KeyError | 
| Baligh Uddin | beb6afd | 2013-11-13 00:22:34 +0000 | [diff] [blame] | 2057 |  | 
|  | 2058 |  | 
|  | 2059 | def ParseCertificate(data): | 
| Tao Bao | 17e4e61 | 2018-02-16 17:12:54 -0800 | [diff] [blame] | 2060 | """Parses and converts a PEM-encoded certificate into DER-encoded. | 
|  | 2061 |  | 
|  | 2062 | This gives the same result as `openssl x509 -in <filename> -outform DER`. | 
|  | 2063 |  | 
|  | 2064 | Returns: | 
|  | 2065 | The decoded certificate string. | 
|  | 2066 | """ | 
|  | 2067 | cert_buffer = [] | 
| Baligh Uddin | beb6afd | 2013-11-13 00:22:34 +0000 | [diff] [blame] | 2068 | save = False | 
|  | 2069 | for line in data.split("\n"): | 
|  | 2070 | if "--END CERTIFICATE--" in line: | 
|  | 2071 | break | 
|  | 2072 | if save: | 
| Tao Bao | 17e4e61 | 2018-02-16 17:12:54 -0800 | [diff] [blame] | 2073 | cert_buffer.append(line) | 
| Baligh Uddin | beb6afd | 2013-11-13 00:22:34 +0000 | [diff] [blame] | 2074 | if "--BEGIN CERTIFICATE--" in line: | 
|  | 2075 | save = True | 
| Tao Bao | 17e4e61 | 2018-02-16 17:12:54 -0800 | [diff] [blame] | 2076 | cert = "".join(cert_buffer).decode('base64') | 
| Baligh Uddin | beb6afd | 2013-11-13 00:22:34 +0000 | [diff] [blame] | 2077 | return cert | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 2078 |  | 
| Tao Bao | 04e1f01 | 2018-02-04 12:13:35 -0800 | [diff] [blame] | 2079 |  | 
|  | 2080 | def ExtractPublicKey(cert): | 
|  | 2081 | """Extracts the public key (PEM-encoded) from the given certificate file. | 
|  | 2082 |  | 
|  | 2083 | Args: | 
|  | 2084 | cert: The certificate filename. | 
|  | 2085 |  | 
|  | 2086 | Returns: | 
|  | 2087 | The public key string. | 
|  | 2088 |  | 
|  | 2089 | Raises: | 
|  | 2090 | AssertionError: On non-zero return from 'openssl'. | 
|  | 2091 | """ | 
|  | 2092 | # The behavior with '-out' is different between openssl 1.1 and openssl 1.0. | 
|  | 2093 | # While openssl 1.1 writes the key into the given filename followed by '-out', | 
|  | 2094 | # openssl 1.0 (both of 1.0.1 and 1.0.2) doesn't. So we collect the output from | 
|  | 2095 | # stdout instead. | 
|  | 2096 | cmd = ['openssl', 'x509', '-pubkey', '-noout', '-in', cert] | 
|  | 2097 | proc = Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | 
|  | 2098 | pubkey, stderrdata = proc.communicate() | 
|  | 2099 | assert proc.returncode == 0, \ | 
|  | 2100 | 'Failed to dump public key from certificate: %s\n%s' % (cert, stderrdata) | 
|  | 2101 | return pubkey | 
|  | 2102 |  | 
|  | 2103 |  | 
| Doug Zongker | 412c02f | 2014-02-13 10:58:24 -0800 | [diff] [blame] | 2104 | def MakeRecoveryPatch(input_dir, output_sink, recovery_img, boot_img, | 
|  | 2105 | info_dict=None): | 
| Tao Bao | 6d5d623 | 2018-03-09 17:04:42 -0800 | [diff] [blame] | 2106 | """Generates the recovery-from-boot patch and writes the script to output. | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 2107 |  | 
| Tao Bao | 6d5d623 | 2018-03-09 17:04:42 -0800 | [diff] [blame] | 2108 | Most of the space in the boot and recovery images is just the kernel, which is | 
|  | 2109 | identical for the two, so the resulting patch should be efficient. Add it to | 
|  | 2110 | the output zip, along with a shell script that is run from init.rc on first | 
|  | 2111 | boot to actually do the patching and install the new recovery image. | 
|  | 2112 |  | 
|  | 2113 | Args: | 
|  | 2114 | input_dir: The top-level input directory of the target-files.zip. | 
|  | 2115 | output_sink: The callback function that writes the result. | 
|  | 2116 | recovery_img: File object for the recovery image. | 
|  | 2117 | boot_img: File objects for the boot image. | 
|  | 2118 | info_dict: A dict returned by common.LoadInfoDict() on the input | 
|  | 2119 | target_files. Will use OPTIONS.info_dict if None has been given. | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 2120 | """ | 
| Doug Zongker | 412c02f | 2014-02-13 10:58:24 -0800 | [diff] [blame] | 2121 | if info_dict is None: | 
|  | 2122 | info_dict = OPTIONS.info_dict | 
|  | 2123 |  | 
| Tao Bao | 6d5d623 | 2018-03-09 17:04:42 -0800 | [diff] [blame] | 2124 | full_recovery_image = info_dict.get("full_recovery_image") == "true" | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 2125 |  | 
| Tao Bao | f2cffbd | 2015-07-22 12:33:18 -0700 | [diff] [blame] | 2126 | if full_recovery_image: | 
|  | 2127 | output_sink("etc/recovery.img", recovery_img.data) | 
|  | 2128 |  | 
|  | 2129 | else: | 
| Tao Bao | 6d5d623 | 2018-03-09 17:04:42 -0800 | [diff] [blame] | 2130 | system_root_image = info_dict.get("system_root_image") == "true" | 
| Tao Bao | f2cffbd | 2015-07-22 12:33:18 -0700 | [diff] [blame] | 2131 | path = os.path.join(input_dir, "SYSTEM", "etc", "recovery-resource.dat") | 
| Tao Bao | 6d5d623 | 2018-03-09 17:04:42 -0800 | [diff] [blame] | 2132 | # With system-root-image, boot and recovery images will have mismatching | 
|  | 2133 | # entries (only recovery has the ramdisk entry) (Bug: 72731506). Use bsdiff | 
|  | 2134 | # to handle such a case. | 
|  | 2135 | if system_root_image: | 
|  | 2136 | diff_program = ["bsdiff"] | 
| Tao Bao | f2cffbd | 2015-07-22 12:33:18 -0700 | [diff] [blame] | 2137 | bonus_args = "" | 
| Tao Bao | 6d5d623 | 2018-03-09 17:04:42 -0800 | [diff] [blame] | 2138 | assert not os.path.exists(path) | 
|  | 2139 | else: | 
|  | 2140 | diff_program = ["imgdiff"] | 
|  | 2141 | if os.path.exists(path): | 
|  | 2142 | diff_program.append("-b") | 
|  | 2143 | diff_program.append(path) | 
| Tao Bao | 4948aed | 2018-07-13 16:11:16 -0700 | [diff] [blame] | 2144 | bonus_args = "--bonus /system/etc/recovery-resource.dat" | 
| Tao Bao | 6d5d623 | 2018-03-09 17:04:42 -0800 | [diff] [blame] | 2145 | else: | 
|  | 2146 | bonus_args = "" | 
| Tao Bao | f2cffbd | 2015-07-22 12:33:18 -0700 | [diff] [blame] | 2147 |  | 
|  | 2148 | d = Difference(recovery_img, boot_img, diff_program=diff_program) | 
|  | 2149 | _, _, patch = d.ComputePatch() | 
|  | 2150 | output_sink("recovery-from-boot.p", patch) | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 2151 |  | 
| Dan Albert | ebb19aa | 2015-03-27 19:11:53 -0700 | [diff] [blame] | 2152 | try: | 
| Tao Bao | 6f0b219 | 2015-10-13 16:37:12 -0700 | [diff] [blame] | 2153 | # The following GetTypeAndDevice()s need to use the path in the target | 
|  | 2154 | # info_dict instead of source_info_dict. | 
| Dan Albert | ebb19aa | 2015-03-27 19:11:53 -0700 | [diff] [blame] | 2155 | boot_type, boot_device = GetTypeAndDevice("/boot", info_dict) | 
|  | 2156 | recovery_type, recovery_device = GetTypeAndDevice("/recovery", info_dict) | 
|  | 2157 | except KeyError: | 
| Ying Wang | a961a09 | 2014-07-29 11:42:37 -0700 | [diff] [blame] | 2158 | return | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 2159 |  | 
| Tao Bao | f2cffbd | 2015-07-22 12:33:18 -0700 | [diff] [blame] | 2160 | if full_recovery_image: | 
|  | 2161 | sh = """#!/system/bin/sh | 
| Tao Bao | 4948aed | 2018-07-13 16:11:16 -0700 | [diff] [blame] | 2162 | if ! applypatch --check %(type)s:%(device)s:%(size)d:%(sha1)s; then | 
|  | 2163 | applypatch \\ | 
|  | 2164 | --flash /system/etc/recovery.img \\ | 
|  | 2165 | --target %(type)s:%(device)s:%(size)d:%(sha1)s && \\ | 
|  | 2166 | log -t recovery "Installing new recovery image: succeeded" || \\ | 
|  | 2167 | log -t recovery "Installing new recovery image: failed" | 
| Tao Bao | f2cffbd | 2015-07-22 12:33:18 -0700 | [diff] [blame] | 2168 | else | 
|  | 2169 | log -t recovery "Recovery image already installed" | 
|  | 2170 | fi | 
|  | 2171 | """ % {'type': recovery_type, | 
|  | 2172 | 'device': recovery_device, | 
|  | 2173 | 'sha1': recovery_img.sha1, | 
|  | 2174 | 'size': recovery_img.size} | 
|  | 2175 | else: | 
|  | 2176 | sh = """#!/system/bin/sh | 
| Tao Bao | 4948aed | 2018-07-13 16:11:16 -0700 | [diff] [blame] | 2177 | if ! applypatch --check %(recovery_type)s:%(recovery_device)s:%(recovery_size)d:%(recovery_sha1)s; then | 
|  | 2178 | applypatch %(bonus_args)s \\ | 
|  | 2179 | --patch /system/recovery-from-boot.p \\ | 
|  | 2180 | --source %(boot_type)s:%(boot_device)s:%(boot_size)d:%(boot_sha1)s \\ | 
|  | 2181 | --target %(recovery_type)s:%(recovery_device)s:%(recovery_size)d:%(recovery_sha1)s && \\ | 
|  | 2182 | log -t recovery "Installing new recovery image: succeeded" || \\ | 
|  | 2183 | log -t recovery "Installing new recovery image: failed" | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 2184 | else | 
|  | 2185 | log -t recovery "Recovery image already installed" | 
|  | 2186 | fi | 
| Dan Albert | 8b72aef | 2015-03-23 19:13:21 -0700 | [diff] [blame] | 2187 | """ % {'boot_size': boot_img.size, | 
|  | 2188 | 'boot_sha1': boot_img.sha1, | 
|  | 2189 | 'recovery_size': recovery_img.size, | 
|  | 2190 | 'recovery_sha1': recovery_img.sha1, | 
|  | 2191 | 'boot_type': boot_type, | 
|  | 2192 | 'boot_device': boot_device, | 
|  | 2193 | 'recovery_type': recovery_type, | 
|  | 2194 | 'recovery_device': recovery_device, | 
|  | 2195 | 'bonus_args': bonus_args} | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 2196 |  | 
|  | 2197 | # The install script location moved from /system/etc to /system/bin | 
| Tianjie Xu | 78de9f1 | 2017-06-20 16:52:54 -0700 | [diff] [blame] | 2198 | # in the L release. | 
|  | 2199 | sh_location = "bin/install-recovery.sh" | 
| Tao Bao | 9f0c8df | 2015-07-07 18:31:47 -0700 | [diff] [blame] | 2200 |  | 
| Tao Bao | 32fcdab | 2018-10-12 10:30:39 -0700 | [diff] [blame] | 2201 | logger.info("putting script in %s", sh_location) | 
| Doug Zongker | c925382 | 2014-02-04 12:17:58 -0800 | [diff] [blame] | 2202 |  | 
|  | 2203 | output_sink(sh_location, sh) | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 2204 |  | 
|  | 2205 |  | 
|  | 2206 | class DynamicPartitionUpdate(object): | 
|  | 2207 | def __init__(self, src_group=None, tgt_group=None, progress=None, | 
|  | 2208 | block_difference=None): | 
|  | 2209 | self.src_group = src_group | 
|  | 2210 | self.tgt_group = tgt_group | 
|  | 2211 | self.progress = progress | 
|  | 2212 | self.block_difference = block_difference | 
|  | 2213 |  | 
|  | 2214 | @property | 
|  | 2215 | def src_size(self): | 
|  | 2216 | if not self.block_difference: | 
|  | 2217 | return 0 | 
|  | 2218 | return DynamicPartitionUpdate._GetSparseImageSize(self.block_difference.src) | 
|  | 2219 |  | 
|  | 2220 | @property | 
|  | 2221 | def tgt_size(self): | 
|  | 2222 | if not self.block_difference: | 
|  | 2223 | return 0 | 
|  | 2224 | return DynamicPartitionUpdate._GetSparseImageSize(self.block_difference.tgt) | 
|  | 2225 |  | 
|  | 2226 | @staticmethod | 
|  | 2227 | def _GetSparseImageSize(img): | 
|  | 2228 | if not img: | 
|  | 2229 | return 0 | 
|  | 2230 | return img.blocksize * img.total_blocks | 
|  | 2231 |  | 
|  | 2232 |  | 
|  | 2233 | class DynamicGroupUpdate(object): | 
|  | 2234 | def __init__(self, src_size=None, tgt_size=None): | 
|  | 2235 | # None: group does not exist. 0: no size limits. | 
|  | 2236 | self.src_size = src_size | 
|  | 2237 | self.tgt_size = tgt_size | 
|  | 2238 |  | 
|  | 2239 |  | 
|  | 2240 | class DynamicPartitionsDifference(object): | 
|  | 2241 | def __init__(self, info_dict, block_diffs, progress_dict=None, | 
|  | 2242 | source_info_dict=None): | 
|  | 2243 | if progress_dict is None: | 
|  | 2244 | progress_dict = dict() | 
|  | 2245 |  | 
|  | 2246 | self._remove_all_before_apply = False | 
|  | 2247 | if source_info_dict is None: | 
|  | 2248 | self._remove_all_before_apply = True | 
|  | 2249 | source_info_dict = dict() | 
|  | 2250 |  | 
|  | 2251 | block_diff_dict = {e.partition:e for e in block_diffs} | 
|  | 2252 | assert len(block_diff_dict) == len(block_diffs), \ | 
|  | 2253 | "Duplicated BlockDifference object for {}".format( | 
|  | 2254 | [partition for partition, count in | 
|  | 2255 | collections.Counter(e.partition for e in block_diffs).items() | 
|  | 2256 | if count > 1]) | 
|  | 2257 |  | 
| Yifan Hong | 79997e5 | 2019-01-23 16:56:19 -0800 | [diff] [blame] | 2258 | self._partition_updates = collections.OrderedDict() | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 2259 |  | 
|  | 2260 | for p, block_diff in block_diff_dict.items(): | 
|  | 2261 | self._partition_updates[p] = DynamicPartitionUpdate() | 
|  | 2262 | self._partition_updates[p].block_difference = block_diff | 
|  | 2263 |  | 
|  | 2264 | for p, progress in progress_dict.items(): | 
|  | 2265 | if p in self._partition_updates: | 
|  | 2266 | self._partition_updates[p].progress = progress | 
|  | 2267 |  | 
|  | 2268 | tgt_groups = shlex.split(info_dict.get( | 
|  | 2269 | "super_partition_groups", "").strip()) | 
|  | 2270 | src_groups = shlex.split(source_info_dict.get( | 
|  | 2271 | "super_partition_groups", "").strip()) | 
|  | 2272 |  | 
|  | 2273 | for g in tgt_groups: | 
|  | 2274 | for p in shlex.split(info_dict.get( | 
|  | 2275 | "super_%s_partition_list" % g, "").strip()): | 
|  | 2276 | assert p in self._partition_updates, \ | 
|  | 2277 | "{} is in target super_{}_partition_list but no BlockDifference " \ | 
|  | 2278 | "object is provided.".format(p, g) | 
|  | 2279 | self._partition_updates[p].tgt_group = g | 
|  | 2280 |  | 
|  | 2281 | for g in src_groups: | 
|  | 2282 | for p in shlex.split(source_info_dict.get( | 
|  | 2283 | "super_%s_partition_list" % g, "").strip()): | 
|  | 2284 | assert p in self._partition_updates, \ | 
|  | 2285 | "{} is in source super_{}_partition_list but no BlockDifference " \ | 
|  | 2286 | "object is provided.".format(p, g) | 
|  | 2287 | self._partition_updates[p].src_group = g | 
|  | 2288 |  | 
| Yifan Hong | 45433e4 | 2019-01-18 13:55:25 -0800 | [diff] [blame] | 2289 | target_dynamic_partitions = set(shlex.split(info_dict.get( | 
|  | 2290 | "dynamic_partition_list", "").strip())) | 
|  | 2291 | block_diffs_with_target = set(p for p, u in self._partition_updates.items() | 
|  | 2292 | if u.tgt_size) | 
|  | 2293 | assert block_diffs_with_target == target_dynamic_partitions, \ | 
|  | 2294 | "Target Dynamic partitions: {}, BlockDifference with target: {}".format( | 
|  | 2295 | list(target_dynamic_partitions), list(block_diffs_with_target)) | 
|  | 2296 |  | 
|  | 2297 | source_dynamic_partitions = set(shlex.split(source_info_dict.get( | 
|  | 2298 | "dynamic_partition_list", "").strip())) | 
|  | 2299 | block_diffs_with_source = set(p for p, u in self._partition_updates.items() | 
|  | 2300 | if u.src_size) | 
|  | 2301 | assert block_diffs_with_source == source_dynamic_partitions, \ | 
|  | 2302 | "Source Dynamic partitions: {}, BlockDifference with source: {}".format( | 
|  | 2303 | list(source_dynamic_partitions), list(block_diffs_with_source)) | 
|  | 2304 |  | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 2305 | if self._partition_updates: | 
|  | 2306 | logger.info("Updating dynamic partitions %s", | 
|  | 2307 | self._partition_updates.keys()) | 
|  | 2308 |  | 
| Yifan Hong | 79997e5 | 2019-01-23 16:56:19 -0800 | [diff] [blame] | 2309 | self._group_updates = collections.OrderedDict() | 
| Yifan Hong | 10c530d | 2018-12-27 17:34:18 -0800 | [diff] [blame] | 2310 |  | 
|  | 2311 | for g in tgt_groups: | 
|  | 2312 | self._group_updates[g] = DynamicGroupUpdate() | 
|  | 2313 | self._group_updates[g].tgt_size = int(info_dict.get( | 
|  | 2314 | "super_%s_group_size" % g, "0").strip()) | 
|  | 2315 |  | 
|  | 2316 | for g in src_groups: | 
|  | 2317 | if g not in self._group_updates: | 
|  | 2318 | self._group_updates[g] = DynamicGroupUpdate() | 
|  | 2319 | self._group_updates[g].src_size = int(source_info_dict.get( | 
|  | 2320 | "super_%s_group_size" % g, "0").strip()) | 
|  | 2321 |  | 
|  | 2322 | self._Compute() | 
|  | 2323 |  | 
|  | 2324 | def WriteScript(self, script, output_zip, write_verify_script=False): | 
|  | 2325 | script.Comment('--- Start patching dynamic partitions ---') | 
|  | 2326 | for p, u in self._partition_updates.items(): | 
|  | 2327 | if u.src_size and u.tgt_size and u.src_size > u.tgt_size: | 
|  | 2328 | script.Comment('Patch partition %s' % p) | 
|  | 2329 | u.block_difference.WriteScript(script, output_zip, progress=u.progress, | 
|  | 2330 | write_verify_script=False) | 
|  | 2331 |  | 
|  | 2332 | op_list_path = MakeTempFile() | 
|  | 2333 | with open(op_list_path, 'w') as f: | 
|  | 2334 | for line in self._op_list: | 
|  | 2335 | f.write('{}\n'.format(line)) | 
|  | 2336 |  | 
|  | 2337 | ZipWrite(output_zip, op_list_path, "dynamic_partitions_op_list") | 
|  | 2338 |  | 
|  | 2339 | script.Comment('Update dynamic partition metadata') | 
|  | 2340 | script.AppendExtra('assert(update_dynamic_partitions(' | 
|  | 2341 | 'package_extract_file("dynamic_partitions_op_list")));') | 
|  | 2342 |  | 
|  | 2343 | if write_verify_script: | 
|  | 2344 | for p, u in self._partition_updates.items(): | 
|  | 2345 | if u.src_size and u.tgt_size and u.src_size > u.tgt_size: | 
|  | 2346 | u.block_difference.WritePostInstallVerifyScript(script) | 
|  | 2347 | script.AppendExtra('unmap_partition("%s");' % p) # ignore errors | 
|  | 2348 |  | 
|  | 2349 | for p, u in self._partition_updates.items(): | 
|  | 2350 | if u.tgt_size and u.src_size <= u.tgt_size: | 
|  | 2351 | script.Comment('Patch partition %s' % p) | 
|  | 2352 | u.block_difference.WriteScript(script, output_zip, progress=u.progress, | 
|  | 2353 | write_verify_script=write_verify_script) | 
|  | 2354 | if write_verify_script: | 
|  | 2355 | script.AppendExtra('unmap_partition("%s");' % p) # ignore errors | 
|  | 2356 |  | 
|  | 2357 | script.Comment('--- End patching dynamic partitions ---') | 
|  | 2358 |  | 
|  | 2359 | def _Compute(self): | 
|  | 2360 | self._op_list = list() | 
|  | 2361 |  | 
|  | 2362 | def append(line): | 
|  | 2363 | self._op_list.append(line) | 
|  | 2364 |  | 
|  | 2365 | def comment(line): | 
|  | 2366 | self._op_list.append("# %s" % line) | 
|  | 2367 |  | 
|  | 2368 | if self._remove_all_before_apply: | 
|  | 2369 | comment('Remove all existing dynamic partitions and groups before ' | 
|  | 2370 | 'applying full OTA') | 
|  | 2371 | append('remove_all_groups') | 
|  | 2372 |  | 
|  | 2373 | for p, u in self._partition_updates.items(): | 
|  | 2374 | if u.src_group and not u.tgt_group: | 
|  | 2375 | append('remove %s' % p) | 
|  | 2376 |  | 
|  | 2377 | for p, u in self._partition_updates.items(): | 
|  | 2378 | if u.src_group and u.tgt_group and u.src_group != u.tgt_group: | 
|  | 2379 | comment('Move partition %s from %s to default' % (p, u.src_group)) | 
|  | 2380 | append('move %s default' % p) | 
|  | 2381 |  | 
|  | 2382 | for p, u in self._partition_updates.items(): | 
|  | 2383 | if u.src_size and u.tgt_size and u.src_size > u.tgt_size: | 
|  | 2384 | comment('Shrink partition %s from %d to %d' % | 
|  | 2385 | (p, u.src_size, u.tgt_size)) | 
|  | 2386 | append('resize %s %s' % (p, u.tgt_size)) | 
|  | 2387 |  | 
|  | 2388 | for g, u in self._group_updates.items(): | 
|  | 2389 | if u.src_size is not None and u.tgt_size is None: | 
|  | 2390 | append('remove_group %s' % g) | 
|  | 2391 | if (u.src_size is not None and u.tgt_size is not None and | 
|  | 2392 | u.src_size > u.tgt_size): | 
|  | 2393 | comment('Shrink group %s from %d to %d' % (g, u.src_size, u.tgt_size)) | 
|  | 2394 | append('resize_group %s %d' % (g, u.tgt_size)) | 
|  | 2395 |  | 
|  | 2396 | for g, u in self._group_updates.items(): | 
|  | 2397 | if u.src_size is None and u.tgt_size is not None: | 
|  | 2398 | comment('Add group %s with maximum size %d' % (g, u.tgt_size)) | 
|  | 2399 | append('add_group %s %d' % (g, u.tgt_size)) | 
|  | 2400 | if (u.src_size is not None and u.tgt_size is not None and | 
|  | 2401 | u.src_size < u.tgt_size): | 
|  | 2402 | comment('Grow group %s from %d to %d' % (g, u.src_size, u.tgt_size)) | 
|  | 2403 | append('resize_group %s %d' % (g, u.tgt_size)) | 
|  | 2404 |  | 
|  | 2405 | for p, u in self._partition_updates.items(): | 
|  | 2406 | if u.tgt_group and not u.src_group: | 
|  | 2407 | comment('Add partition %s to group %s' % (p, u.tgt_group)) | 
|  | 2408 | append('add %s %s' % (p, u.tgt_group)) | 
|  | 2409 |  | 
|  | 2410 | for p, u in self._partition_updates.items(): | 
|  | 2411 | if u.tgt_size and u.src_size < u.tgt_size: | 
|  | 2412 | comment('Grow partition %s from %d to %d' % (p, u.src_size, u.tgt_size)) | 
|  | 2413 | append('resize %s %d' % (p, u.tgt_size)) | 
|  | 2414 |  | 
|  | 2415 | for p, u in self._partition_updates.items(): | 
|  | 2416 | if u.src_group and u.tgt_group and u.src_group != u.tgt_group: | 
|  | 2417 | comment('Move partition %s from default to %s' % | 
|  | 2418 | (p, u.tgt_group)) | 
|  | 2419 | append('move %s %s' % (p, u.tgt_group)) |