blob: 23dadf198ff0574aaafabe5ee0e117a1021c09b7 [file] [log] [blame]
Doug Zongkereef39442009-04-02 12:14:19 -07001# 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 Bao89fbb0f2017-01-10 10:47:58 -080015from __future__ import print_function
16
Doug Zongkerea5d7a92010-09-12 15:26:16 -070017import copy
Doug Zongker8ce7c252009-05-22 13:34:54 -070018import errno
Doug Zongkereef39442009-04-02 12:14:19 -070019import getopt
20import getpass
Narayan Kamatha07bf042017-08-14 14:49:21 +010021import gzip
Doug Zongker05d3dea2009-06-22 11:32:31 -070022import imp
Doug Zongkereef39442009-04-02 12:14:19 -070023import os
Ying Wang7e6d4e42010-12-13 16:25:36 -080024import platform
Doug Zongkereef39442009-04-02 12:14:19 -070025import re
T.R. Fullhart37e10522013-03-18 10:31:26 -070026import shlex
Doug Zongkereef39442009-04-02 12:14:19 -070027import shutil
Tao Baoc765cca2018-01-31 17:32:40 -080028import string
Doug Zongkereef39442009-04-02 12:14:19 -070029import subprocess
30import sys
31import tempfile
Doug Zongkerea5d7a92010-09-12 15:26:16 -070032import threading
33import time
Doug Zongker048e7ca2009-06-15 14:31:53 -070034import zipfile
Tao Bao12d87fc2018-01-31 12:18:52 -080035from hashlib import sha1, sha256
Doug Zongkereef39442009-04-02 12:14:19 -070036
Doug Zongkerab7ca1d2014-08-26 10:40:28 -070037import blockimgdiff
Tao Baoc765cca2018-01-31 17:32:40 -080038import sparse_img
Doug Zongkerab7ca1d2014-08-26 10:40:28 -070039
Dan Albert8b72aef2015-03-23 19:13:21 -070040class Options(object):
41 def __init__(self):
42 platform_search_path = {
43 "linux2": "out/host/linux-x86",
44 "darwin": "out/host/darwin-x86",
Doug Zongker85448772014-09-09 14:59:20 -070045 }
Doug Zongker85448772014-09-09 14:59:20 -070046
Tao Bao76def242017-11-21 09:25:31 -080047 self.search_path = platform_search_path.get(sys.platform)
Dan Albert8b72aef2015-03-23 19:13:21 -070048 self.signapk_path = "framework/signapk.jar" # Relative to search_path
Alex Klyubin9667b182015-12-10 13:38:50 -080049 self.signapk_shared_library_path = "lib64" # Relative to search_path
Dan Albert8b72aef2015-03-23 19:13:21 -070050 self.extra_signapk_args = []
51 self.java_path = "java" # Use the one on the path by default.
Tao Baoe95540e2016-11-08 12:08:53 -080052 self.java_args = ["-Xmx2048m"] # The default JVM args.
Dan Albert8b72aef2015-03-23 19:13:21 -070053 self.public_key_suffix = ".x509.pem"
54 self.private_key_suffix = ".pk8"
Dan Albertcd9ecc02015-03-27 16:37:23 -070055 # use otatools built boot_signer by default
56 self.boot_signer_path = "boot_signer"
Baligh Uddin601ddea2015-06-09 15:48:14 -070057 self.boot_signer_args = []
58 self.verity_signer_path = None
59 self.verity_signer_args = []
Dan Albert8b72aef2015-03-23 19:13:21 -070060 self.verbose = False
61 self.tempfiles = []
62 self.device_specific = None
63 self.extras = {}
64 self.info_dict = None
Tao Bao6f0b2192015-10-13 16:37:12 -070065 self.source_info_dict = None
66 self.target_info_dict = None
Dan Albert8b72aef2015-03-23 19:13:21 -070067 self.worker_threads = None
Tao Bao575d68a2015-08-07 19:49:45 -070068 # Stash size cannot exceed cache_size * threshold.
69 self.cache_size = None
70 self.stash_threshold = 0.8
Dan Albert8b72aef2015-03-23 19:13:21 -070071
72
73OPTIONS = Options()
Doug Zongkereef39442009-04-02 12:14:19 -070074
Doug Zongkerf6a53aa2009-12-15 15:06:55 -080075
76# Values for "certificate" in apkcerts that mean special things.
77SPECIAL_CERT_STRINGS = ("PRESIGNED", "EXTERNAL")
78
Tao Bao9dd909e2017-11-14 11:27:32 -080079
80# The partitions allowed to be signed by AVB (Android verified boot 2.0).
Dario Freni5f681e12018-05-29 13:09:01 +010081AVB_PARTITIONS = ('boot', 'recovery', 'system', 'vendor', 'product',
Dario Freni924af7d2018-08-17 00:56:14 +010082 'product_services', 'dtbo', 'odm')
Tao Bao9dd909e2017-11-14 11:27:32 -080083
84
Tianjie Xu861f4132018-09-12 11:49:33 -070085# Partitions that should have their care_map added to META/care_map.pb
86PARTITIONS_WITH_CARE_MAP = ('system', 'vendor', 'product', 'product_services',
87 'odm')
88
89
Tianjie Xu209db462016-05-24 17:34:52 -070090class ErrorCode(object):
91 """Define error_codes for failures that happen during the actual
92 update package installation.
93
94 Error codes 0-999 are reserved for failures before the package
95 installation (i.e. low battery, package verification failure).
96 Detailed code in 'bootable/recovery/error_code.h' """
97
98 SYSTEM_VERIFICATION_FAILURE = 1000
99 SYSTEM_UPDATE_FAILURE = 1001
100 SYSTEM_UNEXPECTED_CONTENTS = 1002
101 SYSTEM_NONZERO_CONTENTS = 1003
102 SYSTEM_RECOVER_FAILURE = 1004
103 VENDOR_VERIFICATION_FAILURE = 2000
104 VENDOR_UPDATE_FAILURE = 2001
105 VENDOR_UNEXPECTED_CONTENTS = 2002
106 VENDOR_NONZERO_CONTENTS = 2003
107 VENDOR_RECOVER_FAILURE = 2004
108 OEM_PROP_MISMATCH = 3000
109 FINGERPRINT_MISMATCH = 3001
110 THUMBPRINT_MISMATCH = 3002
111 OLDER_BUILD = 3003
112 DEVICE_MISMATCH = 3004
113 BAD_PATCH_FILE = 3005
114 INSUFFICIENT_CACHE_SPACE = 3006
115 TUNE_PARTITION_FAILURE = 3007
116 APPLY_PATCH_FAILURE = 3008
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800117
Tao Bao80921982018-03-21 21:02:19 -0700118
Dan Albert8b72aef2015-03-23 19:13:21 -0700119class ExternalError(RuntimeError):
120 pass
Doug Zongkereef39442009-04-02 12:14:19 -0700121
122
Tao Bao39451582017-05-04 11:10:47 -0700123def Run(args, verbose=None, **kwargs):
124 """Create and return a subprocess.Popen object.
125
126 Caller can specify if the command line should be printed. The global
127 OPTIONS.verbose will be used if not specified.
128 """
129 if verbose is None:
130 verbose = OPTIONS.verbose
131 if verbose:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800132 print(" running: ", " ".join(args))
Doug Zongkereef39442009-04-02 12:14:19 -0700133 return subprocess.Popen(args, **kwargs)
134
135
Tao Baoc765cca2018-01-31 17:32:40 -0800136def RoundUpTo4K(value):
137 rounded_up = value + 4095
138 return rounded_up - (rounded_up % 4096)
139
140
Ying Wang7e6d4e42010-12-13 16:25:36 -0800141def CloseInheritedPipes():
142 """ Gmake in MAC OS has file descriptor (PIPE) leak. We close those fds
143 before doing other work."""
144 if platform.system() != "Darwin":
145 return
146 for d in range(3, 1025):
147 try:
148 stat = os.fstat(d)
149 if stat is not None:
150 pipebit = stat[0] & 0x1000
151 if pipebit != 0:
152 os.close(d)
153 except OSError:
154 pass
155
156
Tao Bao410ad8b2018-08-24 12:08:38 -0700157def LoadInfoDict(input_file, repacking=False):
158 """Loads the key/value pairs from the given input target_files.
159
160 It reads `META/misc_info.txt` file in the target_files input, does sanity
161 checks and returns the parsed key/value pairs for to the given build. It's
162 usually called early when working on input target_files files, e.g. when
163 generating OTAs, or signing builds. Note that the function may be called
164 against an old target_files file (i.e. from past dessert releases). So the
165 property parsing needs to be backward compatible.
166
167 In a `META/misc_info.txt`, a few properties are stored as links to the files
168 in the PRODUCT_OUT directory. It works fine with the build system. However,
169 they are no longer available when (re)generating images from target_files zip.
170 When `repacking` is True, redirect these properties to the actual files in the
171 unzipped directory.
172
173 Args:
174 input_file: The input target_files file, which could be an open
175 zipfile.ZipFile instance, or a str for the dir that contains the files
176 unzipped from a target_files file.
177 repacking: Whether it's trying repack an target_files file after loading the
178 info dict (default: False). If so, it will rewrite a few loaded
179 properties (e.g. selinux_fc, root_dir) to point to the actual files in
180 target_files file. When doing repacking, `input_file` must be a dir.
181
182 Returns:
183 A dict that contains the parsed key/value pairs.
184
185 Raises:
186 AssertionError: On invalid input arguments.
187 ValueError: On malformed input values.
188 """
189 if repacking:
190 assert isinstance(input_file, str), \
191 "input_file must be a path str when doing repacking"
Doug Zongkerc19a8d52010-07-01 15:30:11 -0700192
Doug Zongkerc9253822014-02-04 12:17:58 -0800193 def read_helper(fn):
Dan Albert8b72aef2015-03-23 19:13:21 -0700194 if isinstance(input_file, zipfile.ZipFile):
195 return input_file.read(fn)
Doug Zongkerc9253822014-02-04 12:17:58 -0800196 else:
Dan Albert8b72aef2015-03-23 19:13:21 -0700197 path = os.path.join(input_file, *fn.split("/"))
Doug Zongkerc9253822014-02-04 12:17:58 -0800198 try:
199 with open(path) as f:
200 return f.read()
Dan Albert8b72aef2015-03-23 19:13:21 -0700201 except IOError as e:
Doug Zongkerc9253822014-02-04 12:17:58 -0800202 if e.errno == errno.ENOENT:
203 raise KeyError(fn)
Tao Bao6cd54732017-02-27 15:12:05 -0800204
Doug Zongkerc19a8d52010-07-01 15:30:11 -0700205 try:
Michael Runge6e836112014-04-15 17:40:21 -0700206 d = LoadDictionaryFromLines(read_helper("META/misc_info.txt").split("\n"))
Doug Zongker37974732010-09-16 17:44:38 -0700207 except KeyError:
Tao Bao410ad8b2018-08-24 12:08:38 -0700208 raise ValueError("Failed to find META/misc_info.txt in input target-files")
Doug Zongkerc19a8d52010-07-01 15:30:11 -0700209
Tao Bao410ad8b2018-08-24 12:08:38 -0700210 if "recovery_api_version" not in d:
211 raise ValueError("Failed to find 'recovery_api_version'")
212 if "fstab_version" not in d:
213 raise ValueError("Failed to find 'fstab_version'")
Ken Sumrall3b07cf12013-02-19 17:35:29 -0800214
Tao Bao410ad8b2018-08-24 12:08:38 -0700215 if repacking:
216 # We carry a copy of file_contexts.bin under META/. If not available, search
217 # BOOT/RAMDISK/. Note that sometimes we may need a different file to build
218 # images than the one running on device, in that case, we must have the one
219 # for image generation copied to META/.
Tao Bao79735a62015-08-28 10:52:03 -0700220 fc_basename = os.path.basename(d.get("selinux_fc", "file_contexts"))
Tao Bao410ad8b2018-08-24 12:08:38 -0700221 fc_config = os.path.join(input_file, "META", fc_basename)
Tom Cherryd14b8952018-08-09 14:26:00 -0700222 assert os.path.exists(fc_config)
Tao Bao2c15d9e2015-07-09 11:51:16 -0700223
Tom Cherryd14b8952018-08-09 14:26:00 -0700224 d["selinux_fc"] = fc_config
Tao Bao2c15d9e2015-07-09 11:51:16 -0700225
Tom Cherryd14b8952018-08-09 14:26:00 -0700226 # Similarly we need to redirect "root_dir", and "root_fs_config".
Tao Bao410ad8b2018-08-24 12:08:38 -0700227 d["root_dir"] = os.path.join(input_file, "ROOT")
Tom Cherryd14b8952018-08-09 14:26:00 -0700228 d["root_fs_config"] = os.path.join(
Tao Bao410ad8b2018-08-24 12:08:38 -0700229 input_file, "META", "root_filesystem_config.txt")
Tao Bao84e75682015-07-19 02:38:53 -0700230
Tao Baof54216f2016-03-29 15:12:37 -0700231 # Redirect {system,vendor}_base_fs_file.
232 if "system_base_fs_file" in d:
233 basename = os.path.basename(d["system_base_fs_file"])
Tao Bao410ad8b2018-08-24 12:08:38 -0700234 system_base_fs_file = os.path.join(input_file, "META", basename)
Tao Baob079b502016-05-03 08:01:19 -0700235 if os.path.exists(system_base_fs_file):
236 d["system_base_fs_file"] = system_base_fs_file
237 else:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800238 print("Warning: failed to find system base fs file: %s" % (
239 system_base_fs_file,))
Tao Baob079b502016-05-03 08:01:19 -0700240 del d["system_base_fs_file"]
Tao Baof54216f2016-03-29 15:12:37 -0700241
242 if "vendor_base_fs_file" in d:
243 basename = os.path.basename(d["vendor_base_fs_file"])
Tao Bao410ad8b2018-08-24 12:08:38 -0700244 vendor_base_fs_file = os.path.join(input_file, "META", basename)
Tao Baob079b502016-05-03 08:01:19 -0700245 if os.path.exists(vendor_base_fs_file):
246 d["vendor_base_fs_file"] = vendor_base_fs_file
247 else:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800248 print("Warning: failed to find vendor base fs file: %s" % (
249 vendor_base_fs_file,))
Tao Baob079b502016-05-03 08:01:19 -0700250 del d["vendor_base_fs_file"]
Tao Baof54216f2016-03-29 15:12:37 -0700251
Doug Zongker37974732010-09-16 17:44:38 -0700252 def makeint(key):
253 if key in d:
254 d[key] = int(d[key], 0)
255
256 makeint("recovery_api_version")
257 makeint("blocksize")
258 makeint("system_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700259 makeint("vendor_size")
Doug Zongker37974732010-09-16 17:44:38 -0700260 makeint("userdata_size")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700261 makeint("cache_size")
Doug Zongker37974732010-09-16 17:44:38 -0700262 makeint("recovery_size")
263 makeint("boot_size")
Ken Sumrall3b07cf12013-02-19 17:35:29 -0800264 makeint("fstab_version")
Doug Zongkerc19a8d52010-07-01 15:30:11 -0700265
Tao Baoa57ab9f2018-08-24 12:08:38 -0700266 # We changed recovery.fstab path in Q, from ../RAMDISK/etc/recovery.fstab to
267 # ../RAMDISK/system/etc/recovery.fstab. LoadInfoDict() has to handle both
268 # cases, since it may load the info_dict from an old build (e.g. when
269 # generating incremental OTAs from that build).
Tao Bao76def242017-11-21 09:25:31 -0800270 system_root_image = d.get("system_root_image") == "true"
271 if d.get("no_recovery") != "true":
Tao Bao696bb332018-08-17 16:27:01 -0700272 recovery_fstab_path = "RECOVERY/RAMDISK/system/etc/recovery.fstab"
Tao Baob4adc062018-08-22 18:27:14 -0700273 if isinstance(input_file, zipfile.ZipFile):
274 if recovery_fstab_path not in input_file.namelist():
275 recovery_fstab_path = "RECOVERY/RAMDISK/etc/recovery.fstab"
276 else:
277 path = os.path.join(input_file, *recovery_fstab_path.split("/"))
278 if not os.path.exists(path):
279 recovery_fstab_path = "RECOVERY/RAMDISK/etc/recovery.fstab"
Tao Bao76def242017-11-21 09:25:31 -0800280 d["fstab"] = LoadRecoveryFSTab(
281 read_helper, d["fstab_version"], recovery_fstab_path, system_root_image)
Tao Baob4adc062018-08-22 18:27:14 -0700282
Tao Bao76def242017-11-21 09:25:31 -0800283 elif d.get("recovery_as_boot") == "true":
Tao Bao696bb332018-08-17 16:27:01 -0700284 recovery_fstab_path = "BOOT/RAMDISK/system/etc/recovery.fstab"
Tao Baob4adc062018-08-22 18:27:14 -0700285 if isinstance(input_file, zipfile.ZipFile):
286 if recovery_fstab_path not in input_file.namelist():
287 recovery_fstab_path = "BOOT/RAMDISK/etc/recovery.fstab"
288 else:
289 path = os.path.join(input_file, *recovery_fstab_path.split("/"))
290 if not os.path.exists(path):
291 recovery_fstab_path = "BOOT/RAMDISK/etc/recovery.fstab"
Tao Bao76def242017-11-21 09:25:31 -0800292 d["fstab"] = LoadRecoveryFSTab(
293 read_helper, d["fstab_version"], recovery_fstab_path, system_root_image)
Tao Baob4adc062018-08-22 18:27:14 -0700294
Tianjie Xucfa86222016-03-07 16:31:19 -0800295 else:
296 d["fstab"] = None
297
Tianjie Xu861f4132018-09-12 11:49:33 -0700298 # Tries to load the build props for all partitions with care_map, including
299 # system and vendor.
300 for partition in PARTITIONS_WITH_CARE_MAP:
301 d["{}.build.prop".format(partition)] = LoadBuildProp(
302 read_helper, "{}/build.prop".format(partition.upper()))
303 d["build.prop"] = d["system.build.prop"]
Tao Bao12d87fc2018-01-31 12:18:52 -0800304
305 # Set up the salt (based on fingerprint or thumbprint) that will be used when
306 # adding AVB footer.
307 if d.get("avb_enable") == "true":
308 fp = None
309 if "build.prop" in d:
310 build_prop = d["build.prop"]
311 if "ro.build.fingerprint" in build_prop:
312 fp = build_prop["ro.build.fingerprint"]
313 elif "ro.build.thumbprint" in build_prop:
314 fp = build_prop["ro.build.thumbprint"]
315 if fp:
316 d["avb_salt"] = sha256(fp).hexdigest()
317
Doug Zongker1eb74dd2012-08-16 16:19:00 -0700318 return d
319
Tao Baod1de6f32017-03-01 16:38:48 -0800320
Tao Baobcd1d162017-08-26 13:10:26 -0700321def LoadBuildProp(read_helper, prop_file):
Doug Zongker1eb74dd2012-08-16 16:19:00 -0700322 try:
Tao Baobcd1d162017-08-26 13:10:26 -0700323 data = read_helper(prop_file)
Doug Zongker1eb74dd2012-08-16 16:19:00 -0700324 except KeyError:
Tao Baobcd1d162017-08-26 13:10:26 -0700325 print("Warning: could not read %s" % (prop_file,))
Doug Zongker1eb74dd2012-08-16 16:19:00 -0700326 data = ""
Michael Runge6e836112014-04-15 17:40:21 -0700327 return LoadDictionaryFromLines(data.split("\n"))
Doug Zongker1eb74dd2012-08-16 16:19:00 -0700328
Tao Baod1de6f32017-03-01 16:38:48 -0800329
Michael Runge6e836112014-04-15 17:40:21 -0700330def LoadDictionaryFromLines(lines):
Doug Zongker1eb74dd2012-08-16 16:19:00 -0700331 d = {}
Michael Runge6e836112014-04-15 17:40:21 -0700332 for line in lines:
Doug Zongker1eb74dd2012-08-16 16:19:00 -0700333 line = line.strip()
Dan Albert8b72aef2015-03-23 19:13:21 -0700334 if not line or line.startswith("#"):
335 continue
Ying Wang114b46f2014-04-15 11:24:00 -0700336 if "=" in line:
337 name, value = line.split("=", 1)
338 d[name] = value
Doug Zongkerc19a8d52010-07-01 15:30:11 -0700339 return d
340
Tao Baod1de6f32017-03-01 16:38:48 -0800341
Tianjie Xucfa86222016-03-07 16:31:19 -0800342def LoadRecoveryFSTab(read_helper, fstab_version, recovery_fstab_path,
343 system_root_image=False):
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700344 class Partition(object):
Tao Baod1de6f32017-03-01 16:38:48 -0800345 def __init__(self, mount_point, fs_type, device, length, context):
Dan Albert8b72aef2015-03-23 19:13:21 -0700346 self.mount_point = mount_point
347 self.fs_type = fs_type
348 self.device = device
349 self.length = length
Tao Bao548eb762015-06-10 12:32:41 -0700350 self.context = context
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700351
352 try:
Tianjie Xucfa86222016-03-07 16:31:19 -0800353 data = read_helper(recovery_fstab_path)
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700354 except KeyError:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800355 print("Warning: could not find {}".format(recovery_fstab_path))
Jeff Davidson033fbe22011-10-26 18:08:09 -0700356 data = ""
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700357
Tao Baod1de6f32017-03-01 16:38:48 -0800358 assert fstab_version == 2
359
360 d = {}
361 for line in data.split("\n"):
362 line = line.strip()
363 if not line or line.startswith("#"):
364 continue
365
366 # <src> <mnt_point> <type> <mnt_flags and options> <fs_mgr_flags>
367 pieces = line.split()
368 if len(pieces) != 5:
369 raise ValueError("malformed recovery.fstab line: \"%s\"" % (line,))
370
371 # Ignore entries that are managed by vold.
372 options = pieces[4]
373 if "voldmanaged=" in options:
374 continue
375
376 # It's a good line, parse it.
377 length = 0
378 options = options.split(",")
379 for i in options:
380 if i.startswith("length="):
381 length = int(i[7:])
Doug Zongker086cbb02011-02-17 15:54:20 -0800382 else:
Tao Baod1de6f32017-03-01 16:38:48 -0800383 # Ignore all unknown options in the unified fstab.
Dan Albert8b72aef2015-03-23 19:13:21 -0700384 continue
Ken Sumrall3b07cf12013-02-19 17:35:29 -0800385
Tao Baod1de6f32017-03-01 16:38:48 -0800386 mount_flags = pieces[3]
387 # Honor the SELinux context if present.
388 context = None
389 for i in mount_flags.split(","):
390 if i.startswith("context="):
391 context = i
Doug Zongker086cbb02011-02-17 15:54:20 -0800392
Tao Baod1de6f32017-03-01 16:38:48 -0800393 mount_point = pieces[1]
394 d[mount_point] = Partition(mount_point=mount_point, fs_type=pieces[2],
395 device=pieces[0], length=length, context=context)
Ken Sumrall3b07cf12013-02-19 17:35:29 -0800396
Daniel Rosenberge6853b02015-06-05 17:59:27 -0700397 # / is used for the system mount point when the root directory is included in
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700398 # system. Other areas assume system is always at "/system" so point /system
399 # at /.
Daniel Rosenberge6853b02015-06-05 17:59:27 -0700400 if system_root_image:
401 assert not d.has_key("/system") and d.has_key("/")
402 d["/system"] = d["/"]
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700403 return d
404
405
Doug Zongker37974732010-09-16 17:44:38 -0700406def DumpInfoDict(d):
407 for k, v in sorted(d.items()):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800408 print("%-25s = (%s) %s" % (k, type(v).__name__, v))
Doug Zongkerc19a8d52010-07-01 15:30:11 -0700409
Dan Albert8b72aef2015-03-23 19:13:21 -0700410
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800411def AppendAVBSigningArgs(cmd, partition):
412 """Append signing arguments for avbtool."""
413 # e.g., "--key path/to/signing_key --algorithm SHA256_RSA4096"
414 key_path = OPTIONS.info_dict.get("avb_" + partition + "_key_path")
415 algorithm = OPTIONS.info_dict.get("avb_" + partition + "_algorithm")
416 if key_path and algorithm:
417 cmd.extend(["--key", key_path, "--algorithm", algorithm])
Tao Bao2b6dfd62017-09-27 17:17:43 -0700418 avb_salt = OPTIONS.info_dict.get("avb_salt")
419 # make_vbmeta_image doesn't like "--salt" (and it's not needed).
Tao Bao744c4c72018-08-20 21:09:07 -0700420 if avb_salt and not partition.startswith("vbmeta"):
Tao Bao2b6dfd62017-09-27 17:17:43 -0700421 cmd.extend(["--salt", avb_salt])
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800422
423
Tao Bao02a08592018-07-22 12:40:45 -0700424def GetAvbChainedPartitionArg(partition, info_dict, key=None):
425 """Constructs and returns the arg to build or verify a chained partition.
426
427 Args:
428 partition: The partition name.
429 info_dict: The info dict to look up the key info and rollback index
430 location.
431 key: The key to be used for building or verifying the partition. Defaults to
432 the key listed in info_dict.
433
434 Returns:
435 A string of form "partition:rollback_index_location:key" that can be used to
436 build or verify vbmeta image.
437
438 Raises:
439 AssertionError: When it fails to extract the public key with avbtool.
440 """
441 if key is None:
442 key = info_dict["avb_" + partition + "_key_path"]
443 avbtool = os.getenv('AVBTOOL') or info_dict["avb_avbtool"]
444 pubkey_path = MakeTempFile(prefix="avb-", suffix=".pubkey")
445 proc = Run(
446 [avbtool, "extract_public_key", "--key", key, "--output", pubkey_path],
447 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
448 stdoutdata, _ = proc.communicate()
449 assert proc.returncode == 0, \
450 "Failed to extract pubkey for {}:\n{}".format(
451 partition, stdoutdata)
452
453 rollback_index_location = info_dict[
454 "avb_" + partition + "_rollback_index_location"]
455 return "{}:{}:{}".format(partition, rollback_index_location, pubkey_path)
456
457
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700458def _BuildBootableImage(sourcedir, fs_config_file, info_dict=None,
Tao Baod42e97e2016-11-30 12:11:57 -0800459 has_ramdisk=False, two_step_image=False):
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700460 """Build a bootable image from the specified sourcedir.
Doug Zongkere1c31ba2009-06-23 17:40:35 -0700461
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700462 Take a kernel, cmdline, and optionally a ramdisk directory from the input (in
Tao Baod42e97e2016-11-30 12:11:57 -0800463 'sourcedir'), and turn them into a boot image. 'two_step_image' indicates if
464 we are building a two-step special image (i.e. building a recovery image to
465 be loaded into /boot in two-step OTAs).
466
467 Return the image data, or None if sourcedir does not appear to contains files
468 for building the requested image.
469 """
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700470
471 def make_ramdisk():
472 ramdisk_img = tempfile.NamedTemporaryFile()
473
474 if os.access(fs_config_file, os.F_OK):
475 cmd = ["mkbootfs", "-f", fs_config_file,
476 os.path.join(sourcedir, "RAMDISK")]
477 else:
478 cmd = ["mkbootfs", os.path.join(sourcedir, "RAMDISK")]
479 p1 = Run(cmd, stdout=subprocess.PIPE)
480 p2 = Run(["minigzip"], stdin=p1.stdout, stdout=ramdisk_img.file.fileno())
481
482 p2.wait()
483 p1.wait()
484 assert p1.returncode == 0, "mkbootfs of %s ramdisk failed" % (sourcedir,)
485 assert p2.returncode == 0, "minigzip of %s ramdisk failed" % (sourcedir,)
486
487 return ramdisk_img
488
489 if not os.access(os.path.join(sourcedir, "kernel"), os.F_OK):
490 return None
491
492 if has_ramdisk and not os.access(os.path.join(sourcedir, "RAMDISK"), os.F_OK):
Doug Zongkere1c31ba2009-06-23 17:40:35 -0700493 return None
Doug Zongkereef39442009-04-02 12:14:19 -0700494
Doug Zongkerd5131602012-08-02 14:46:42 -0700495 if info_dict is None:
496 info_dict = OPTIONS.info_dict
497
Doug Zongkereef39442009-04-02 12:14:19 -0700498 img = tempfile.NamedTemporaryFile()
499
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700500 if has_ramdisk:
501 ramdisk_img = make_ramdisk()
Doug Zongkereef39442009-04-02 12:14:19 -0700502
Bjorn Andersson612e2cd2012-11-25 16:53:44 -0800503 # use MKBOOTIMG from environ, or "mkbootimg" if empty or not set
504 mkbootimg = os.getenv('MKBOOTIMG') or "mkbootimg"
505
506 cmd = [mkbootimg, "--kernel", os.path.join(sourcedir, "kernel")]
Doug Zongker38a649f2009-06-17 09:07:09 -0700507
Benoit Fradina45a8682014-07-14 21:00:43 +0200508 fn = os.path.join(sourcedir, "second")
509 if os.access(fn, os.F_OK):
510 cmd.append("--second")
511 cmd.append(fn)
512
Doug Zongker171f1cd2009-06-15 22:36:37 -0700513 fn = os.path.join(sourcedir, "cmdline")
514 if os.access(fn, os.F_OK):
Doug Zongker38a649f2009-06-17 09:07:09 -0700515 cmd.append("--cmdline")
516 cmd.append(open(fn).read().rstrip("\n"))
517
518 fn = os.path.join(sourcedir, "base")
519 if os.access(fn, os.F_OK):
520 cmd.append("--base")
521 cmd.append(open(fn).read().rstrip("\n"))
522
Ying Wang4de6b5b2010-08-25 14:29:34 -0700523 fn = os.path.join(sourcedir, "pagesize")
524 if os.access(fn, os.F_OK):
525 cmd.append("--pagesize")
526 cmd.append(open(fn).read().rstrip("\n"))
527
Tao Bao76def242017-11-21 09:25:31 -0800528 args = info_dict.get("mkbootimg_args")
Doug Zongkerd5131602012-08-02 14:46:42 -0700529 if args and args.strip():
Jianxun Zhang09849492013-04-17 15:19:19 -0700530 cmd.extend(shlex.split(args))
Doug Zongkerd5131602012-08-02 14:46:42 -0700531
Tao Bao76def242017-11-21 09:25:31 -0800532 args = info_dict.get("mkbootimg_version_args")
Sami Tolvanen3303d902016-03-15 16:49:30 +0000533 if args and args.strip():
534 cmd.extend(shlex.split(args))
535
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700536 if has_ramdisk:
537 cmd.extend(["--ramdisk", ramdisk_img.name])
538
Tao Baod95e9fd2015-03-29 23:07:41 -0700539 img_unsigned = None
Tao Bao76def242017-11-21 09:25:31 -0800540 if info_dict.get("vboot"):
Tao Baod95e9fd2015-03-29 23:07:41 -0700541 img_unsigned = tempfile.NamedTemporaryFile()
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700542 cmd.extend(["--output", img_unsigned.name])
Tao Baod95e9fd2015-03-29 23:07:41 -0700543 else:
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700544 cmd.extend(["--output", img.name])
Doug Zongker38a649f2009-06-17 09:07:09 -0700545
Tao Baobf70c3182017-07-11 17:27:55 -0700546 # "boot" or "recovery", without extension.
547 partition_name = os.path.basename(sourcedir).lower()
548
Hridya Valsarajue74a38b2018-03-21 12:15:11 -0700549 if (partition_name == "recovery" and
550 info_dict.get("include_recovery_dtbo") == "true"):
551 fn = os.path.join(sourcedir, "recovery_dtbo")
552 cmd.extend(["--recovery_dtbo", fn])
553
Doug Zongker38a649f2009-06-17 09:07:09 -0700554 p = Run(cmd, stdout=subprocess.PIPE)
Doug Zongkereef39442009-04-02 12:14:19 -0700555 p.communicate()
Tao Baobf70c3182017-07-11 17:27:55 -0700556 assert p.returncode == 0, "mkbootimg of %s image failed" % (partition_name,)
Doug Zongkereef39442009-04-02 12:14:19 -0700557
Tao Bao76def242017-11-21 09:25:31 -0800558 if (info_dict.get("boot_signer") == "true" and
559 info_dict.get("verity_key")):
Tao Baod42e97e2016-11-30 12:11:57 -0800560 # Hard-code the path as "/boot" for two-step special recovery image (which
561 # will be loaded into /boot during the two-step OTA).
562 if two_step_image:
563 path = "/boot"
564 else:
Tao Baobf70c3182017-07-11 17:27:55 -0700565 path = "/" + partition_name
Baligh Uddin601ddea2015-06-09 15:48:14 -0700566 cmd = [OPTIONS.boot_signer_path]
567 cmd.extend(OPTIONS.boot_signer_args)
568 cmd.extend([path, img.name,
569 info_dict["verity_key"] + ".pk8",
570 info_dict["verity_key"] + ".x509.pem", img.name])
Geremy Condra95ebe7a2014-08-19 17:27:56 -0700571 p = Run(cmd, stdout=subprocess.PIPE)
572 p.communicate()
573 assert p.returncode == 0, "boot_signer of %s image failed" % path
574
Tao Baod95e9fd2015-03-29 23:07:41 -0700575 # Sign the image if vboot is non-empty.
Tao Bao76def242017-11-21 09:25:31 -0800576 elif info_dict.get("vboot"):
Tao Baobf70c3182017-07-11 17:27:55 -0700577 path = "/" + partition_name
Tao Baod95e9fd2015-03-29 23:07:41 -0700578 img_keyblock = tempfile.NamedTemporaryFile()
Tao Bao4f104d12017-02-17 23:21:31 -0800579 # We have switched from the prebuilt futility binary to using the tool
580 # (futility-host) built from the source. Override the setting in the old
581 # TF.zip.
582 futility = info_dict["futility"]
583 if futility.startswith("prebuilts/"):
584 futility = "futility-host"
585 cmd = [info_dict["vboot_signer_cmd"], futility,
Tao Baod95e9fd2015-03-29 23:07:41 -0700586 img_unsigned.name, info_dict["vboot_key"] + ".vbpubk",
Furquan Shaikh852b8de2015-08-10 11:43:45 -0700587 info_dict["vboot_key"] + ".vbprivk",
588 info_dict["vboot_subkey"] + ".vbprivk",
589 img_keyblock.name,
Tao Baod95e9fd2015-03-29 23:07:41 -0700590 img.name]
591 p = Run(cmd, stdout=subprocess.PIPE)
592 p.communicate()
593 assert p.returncode == 0, "vboot_signer of %s image failed" % path
594
Tao Baof3282b42015-04-01 11:21:55 -0700595 # Clean up the temp files.
596 img_unsigned.close()
597 img_keyblock.close()
598
David Zeuthen8fecb282017-12-01 16:24:01 -0500599 # AVB: if enabled, calculate and add hash to boot.img or recovery.img.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800600 if info_dict.get("avb_enable") == "true":
Tao Bao3ebfdde2017-05-23 23:06:55 -0700601 avbtool = os.getenv('AVBTOOL') or info_dict["avb_avbtool"]
David Zeuthen8fecb282017-12-01 16:24:01 -0500602 part_size = info_dict[partition_name + "_size"]
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400603 cmd = [avbtool, "add_hash_footer", "--image", img.name,
Tao Baobf70c3182017-07-11 17:27:55 -0700604 "--partition_size", str(part_size), "--partition_name",
605 partition_name]
606 AppendAVBSigningArgs(cmd, partition_name)
David Zeuthen8fecb282017-12-01 16:24:01 -0500607 args = info_dict.get("avb_" + partition_name + "_add_hash_footer_args")
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400608 if args and args.strip():
609 cmd.extend(shlex.split(args))
610 p = Run(cmd, stdout=subprocess.PIPE)
611 p.communicate()
612 assert p.returncode == 0, "avbtool add_hash_footer of %s failed" % (
Tao Baobf70c3182017-07-11 17:27:55 -0700613 partition_name,)
David Zeuthend995f4b2016-01-29 16:59:17 -0500614
615 img.seek(os.SEEK_SET, 0)
616 data = img.read()
617
618 if has_ramdisk:
619 ramdisk_img.close()
620 img.close()
621
622 return data
623
624
Doug Zongkerd5131602012-08-02 14:46:42 -0700625def GetBootableImage(name, prebuilt_name, unpack_dir, tree_subdir,
Tao Baod42e97e2016-11-30 12:11:57 -0800626 info_dict=None, two_step_image=False):
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700627 """Return a File object with the desired bootable image.
628
629 Look for it in 'unpack_dir'/BOOTABLE_IMAGES under the name 'prebuilt_name',
630 otherwise look for it under 'unpack_dir'/IMAGES, otherwise construct it from
631 the source files in 'unpack_dir'/'tree_subdir'."""
Doug Zongkereef39442009-04-02 12:14:19 -0700632
Doug Zongker55d93282011-01-25 17:03:34 -0800633 prebuilt_path = os.path.join(unpack_dir, "BOOTABLE_IMAGES", prebuilt_name)
634 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800635 print("using prebuilt %s from BOOTABLE_IMAGES..." % (prebuilt_name,))
Doug Zongker55d93282011-01-25 17:03:34 -0800636 return File.FromLocalFile(name, prebuilt_path)
Doug Zongker6f1d0312014-08-22 08:07:12 -0700637
638 prebuilt_path = os.path.join(unpack_dir, "IMAGES", prebuilt_name)
639 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800640 print("using prebuilt %s from IMAGES..." % (prebuilt_name,))
Doug Zongker6f1d0312014-08-22 08:07:12 -0700641 return File.FromLocalFile(name, prebuilt_path)
642
Tao Bao89fbb0f2017-01-10 10:47:58 -0800643 print("building image from target_files %s..." % (tree_subdir,))
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700644
645 if info_dict is None:
646 info_dict = OPTIONS.info_dict
647
648 # With system_root_image == "true", we don't pack ramdisk into the boot image.
Daniel Rosenberg40ef35b2015-11-10 19:21:34 -0800649 # Unless "recovery_as_boot" is specified, in which case we carry the ramdisk
650 # for recovery.
651 has_ramdisk = (info_dict.get("system_root_image") != "true" or
652 prebuilt_name != "boot.img" or
653 info_dict.get("recovery_as_boot") == "true")
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700654
Doug Zongker6f1d0312014-08-22 08:07:12 -0700655 fs_config = "META/" + tree_subdir.lower() + "_filesystem_config.txt"
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400656 data = _BuildBootableImage(os.path.join(unpack_dir, tree_subdir),
657 os.path.join(unpack_dir, fs_config),
Tao Baod42e97e2016-11-30 12:11:57 -0800658 info_dict, has_ramdisk, two_step_image)
Doug Zongker6f1d0312014-08-22 08:07:12 -0700659 if data:
660 return File(name, data)
661 return None
Doug Zongker55d93282011-01-25 17:03:34 -0800662
Doug Zongkereef39442009-04-02 12:14:19 -0700663
Narayan Kamatha07bf042017-08-14 14:49:21 +0100664def Gunzip(in_filename, out_filename):
Tao Bao76def242017-11-21 09:25:31 -0800665 """Gunzips the given gzip compressed file to a given output file."""
666 with gzip.open(in_filename, "rb") as in_file, \
667 open(out_filename, "wb") as out_file:
Narayan Kamatha07bf042017-08-14 14:49:21 +0100668 shutil.copyfileobj(in_file, out_file)
669
670
Doug Zongker75f17362009-12-08 13:46:44 -0800671def UnzipTemp(filename, pattern=None):
Tao Bao1c830bf2017-12-25 10:43:47 -0800672 """Unzips the given archive into a temporary directory and returns the name.
Doug Zongker55d93282011-01-25 17:03:34 -0800673
Tao Bao1c830bf2017-12-25 10:43:47 -0800674 If filename is of the form "foo.zip+bar.zip", unzip foo.zip into a temp dir,
675 then unzip bar.zip into that_dir/BOOTABLE_IMAGES.
Doug Zongker55d93282011-01-25 17:03:34 -0800676
Tao Bao1c830bf2017-12-25 10:43:47 -0800677 Returns:
Tao Baodba59ee2018-01-09 13:21:02 -0800678 The name of the temporary directory.
Doug Zongker55d93282011-01-25 17:03:34 -0800679 """
Doug Zongkereef39442009-04-02 12:14:19 -0700680
Doug Zongker55d93282011-01-25 17:03:34 -0800681 def unzip_to_dir(filename, dirname):
682 cmd = ["unzip", "-o", "-q", filename, "-d", dirname]
683 if pattern is not None:
Tao Bao6b0b2f92017-03-05 11:38:11 -0800684 cmd.extend(pattern)
Tao Bao80921982018-03-21 21:02:19 -0700685 p = Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
686 stdoutdata, _ = p.communicate()
Doug Zongker55d93282011-01-25 17:03:34 -0800687 if p.returncode != 0:
Tao Bao80921982018-03-21 21:02:19 -0700688 raise ExternalError(
689 "Failed to unzip input target-files \"{}\":\n{}".format(
690 filename, stdoutdata))
Doug Zongker55d93282011-01-25 17:03:34 -0800691
Tao Bao1c830bf2017-12-25 10:43:47 -0800692 tmp = MakeTempDir(prefix="targetfiles-")
Doug Zongker55d93282011-01-25 17:03:34 -0800693 m = re.match(r"^(.*[.]zip)\+(.*[.]zip)$", filename, re.IGNORECASE)
694 if m:
695 unzip_to_dir(m.group(1), tmp)
696 unzip_to_dir(m.group(2), os.path.join(tmp, "BOOTABLE_IMAGES"))
697 filename = m.group(1)
698 else:
699 unzip_to_dir(filename, tmp)
700
Tao Baodba59ee2018-01-09 13:21:02 -0800701 return tmp
Doug Zongkereef39442009-04-02 12:14:19 -0700702
703
Tao Baoe709b092018-02-07 12:40:00 -0800704def GetSparseImage(which, tmpdir, input_zip, allow_shared_blocks):
Tao Baoc765cca2018-01-31 17:32:40 -0800705 """Returns a SparseImage object suitable for passing to BlockImageDiff.
706
707 This function loads the specified sparse image from the given path, and
708 performs additional processing for OTA purpose. For example, it always adds
709 block 0 to clobbered blocks list. It also detects files that cannot be
710 reconstructed from the block list, for whom we should avoid applying imgdiff.
711
712 Args:
713 which: The partition name, which must be "system" or "vendor".
714 tmpdir: The directory that contains the prebuilt image and block map file.
715 input_zip: The target-files ZIP archive.
Tao Baoe709b092018-02-07 12:40:00 -0800716 allow_shared_blocks: Whether having shared blocks is allowed.
Tao Baoc765cca2018-01-31 17:32:40 -0800717
718 Returns:
719 A SparseImage object, with file_map info loaded.
720 """
721 assert which in ("system", "vendor")
722
723 path = os.path.join(tmpdir, "IMAGES", which + ".img")
724 mappath = os.path.join(tmpdir, "IMAGES", which + ".map")
725
726 # The image and map files must have been created prior to calling
727 # ota_from_target_files.py (since LMP).
728 assert os.path.exists(path) and os.path.exists(mappath)
729
730 # In ext4 filesystems, block 0 might be changed even being mounted R/O. We add
731 # it to clobbered_blocks so that it will be written to the target
732 # unconditionally. Note that they are still part of care_map. (Bug: 20939131)
733 clobbered_blocks = "0"
734
Tao Baoe709b092018-02-07 12:40:00 -0800735 image = sparse_img.SparseImage(path, mappath, clobbered_blocks,
736 allow_shared_blocks=allow_shared_blocks)
Tao Baoc765cca2018-01-31 17:32:40 -0800737
738 # block.map may contain less blocks, because mke2fs may skip allocating blocks
739 # if they contain all zeros. We can't reconstruct such a file from its block
740 # list. Tag such entries accordingly. (Bug: 65213616)
741 for entry in image.file_map:
Tao Baoc765cca2018-01-31 17:32:40 -0800742 # Skip artificial names, such as "__ZERO", "__NONZERO-1".
Tao Baod3554e62018-07-10 15:31:22 -0700743 if not entry.startswith('/'):
Tao Baoc765cca2018-01-31 17:32:40 -0800744 continue
745
Tom Cherryd14b8952018-08-09 14:26:00 -0700746 # "/system/framework/am.jar" => "SYSTEM/framework/am.jar". Note that the
747 # filename listed in system.map may contain an additional leading slash
748 # (i.e. "//system/framework/am.jar"). Using lstrip to get consistent
749 # results.
Tao Baod3554e62018-07-10 15:31:22 -0700750 arcname = string.replace(entry, which, which.upper(), 1).lstrip('/')
751
Tom Cherryd14b8952018-08-09 14:26:00 -0700752 # Special handling another case, where files not under /system
753 # (e.g. "/sbin/charger") are packed under ROOT/ in a target_files.zip.
Tao Baod3554e62018-07-10 15:31:22 -0700754 if which == 'system' and not arcname.startswith('SYSTEM'):
755 arcname = 'ROOT/' + arcname
756
757 assert arcname in input_zip.namelist(), \
758 "Failed to find the ZIP entry for {}".format(entry)
759
Tao Baoc765cca2018-01-31 17:32:40 -0800760 info = input_zip.getinfo(arcname)
761 ranges = image.file_map[entry]
Tao Baoe709b092018-02-07 12:40:00 -0800762
763 # If a RangeSet has been tagged as using shared blocks while loading the
764 # image, its block list must be already incomplete due to that reason. Don't
765 # give it 'incomplete' tag to avoid messing up the imgdiff stats.
766 if ranges.extra.get('uses_shared_blocks'):
767 continue
768
Tao Baoc765cca2018-01-31 17:32:40 -0800769 if RoundUpTo4K(info.file_size) > ranges.size() * 4096:
770 ranges.extra['incomplete'] = True
771
772 return image
773
774
Doug Zongkereef39442009-04-02 12:14:19 -0700775def GetKeyPasswords(keylist):
776 """Given a list of keys, prompt the user to enter passwords for
777 those which require them. Return a {key: password} dict. password
778 will be None if the key has no password."""
779
Doug Zongker8ce7c252009-05-22 13:34:54 -0700780 no_passwords = []
781 need_passwords = []
T.R. Fullhart37e10522013-03-18 10:31:26 -0700782 key_passwords = {}
Doug Zongkereef39442009-04-02 12:14:19 -0700783 devnull = open("/dev/null", "w+b")
784 for k in sorted(keylist):
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800785 # We don't need a password for things that aren't really keys.
786 if k in SPECIAL_CERT_STRINGS:
Doug Zongker8ce7c252009-05-22 13:34:54 -0700787 no_passwords.append(k)
Doug Zongker43874f82009-04-14 14:05:15 -0700788 continue
789
T.R. Fullhart37e10522013-03-18 10:31:26 -0700790 p = Run(["openssl", "pkcs8", "-in", k+OPTIONS.private_key_suffix,
Doug Zongker602a84e2009-06-18 08:35:12 -0700791 "-inform", "DER", "-nocrypt"],
792 stdin=devnull.fileno(),
793 stdout=devnull.fileno(),
794 stderr=subprocess.STDOUT)
Doug Zongkereef39442009-04-02 12:14:19 -0700795 p.communicate()
796 if p.returncode == 0:
T.R. Fullhart37e10522013-03-18 10:31:26 -0700797 # Definitely an unencrypted key.
Doug Zongker8ce7c252009-05-22 13:34:54 -0700798 no_passwords.append(k)
Doug Zongkereef39442009-04-02 12:14:19 -0700799 else:
T.R. Fullhart37e10522013-03-18 10:31:26 -0700800 p = Run(["openssl", "pkcs8", "-in", k+OPTIONS.private_key_suffix,
801 "-inform", "DER", "-passin", "pass:"],
802 stdin=devnull.fileno(),
803 stdout=devnull.fileno(),
804 stderr=subprocess.PIPE)
Dan Albert8b72aef2015-03-23 19:13:21 -0700805 _, stderr = p.communicate()
T.R. Fullhart37e10522013-03-18 10:31:26 -0700806 if p.returncode == 0:
807 # Encrypted key with empty string as password.
808 key_passwords[k] = ''
809 elif stderr.startswith('Error decrypting key'):
810 # Definitely encrypted key.
811 # It would have said "Error reading key" if it didn't parse correctly.
812 need_passwords.append(k)
813 else:
814 # Potentially, a type of key that openssl doesn't understand.
815 # We'll let the routines in signapk.jar handle it.
816 no_passwords.append(k)
Doug Zongkereef39442009-04-02 12:14:19 -0700817 devnull.close()
Doug Zongker8ce7c252009-05-22 13:34:54 -0700818
T.R. Fullhart37e10522013-03-18 10:31:26 -0700819 key_passwords.update(PasswordManager().GetPasswords(need_passwords))
Tao Bao76def242017-11-21 09:25:31 -0800820 key_passwords.update(dict.fromkeys(no_passwords))
Doug Zongkereef39442009-04-02 12:14:19 -0700821 return key_passwords
822
823
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800824def GetMinSdkVersion(apk_name):
Tao Baof47bf0f2018-03-21 23:28:51 -0700825 """Gets the minSdkVersion declared in the APK.
826
827 It calls 'aapt' to query the embedded minSdkVersion from the given APK file.
828 This can be both a decimal number (API Level) or a codename.
829
830 Args:
831 apk_name: The APK filename.
832
833 Returns:
834 The parsed SDK version string.
835
836 Raises:
837 ExternalError: On failing to obtain the min SDK version.
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800838 """
Tao Baof47bf0f2018-03-21 23:28:51 -0700839 proc = Run(
840 ["aapt", "dump", "badging", apk_name], stdout=subprocess.PIPE,
841 stderr=subprocess.PIPE)
842 stdoutdata, stderrdata = proc.communicate()
843 if proc.returncode != 0:
844 raise ExternalError(
845 "Failed to obtain minSdkVersion: aapt return code {}:\n{}\n{}".format(
846 proc.returncode, stdoutdata, stderrdata))
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800847
Tao Baof47bf0f2018-03-21 23:28:51 -0700848 for line in stdoutdata.split("\n"):
849 # Looking for lines such as sdkVersion:'23' or sdkVersion:'M'.
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800850 m = re.match(r'sdkVersion:\'([^\']*)\'', line)
851 if m:
852 return m.group(1)
853 raise ExternalError("No minSdkVersion returned by aapt")
854
855
856def GetMinSdkVersionInt(apk_name, codename_to_api_level_map):
Tao Baof47bf0f2018-03-21 23:28:51 -0700857 """Returns the minSdkVersion declared in the APK as a number (API Level).
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800858
Tao Baof47bf0f2018-03-21 23:28:51 -0700859 If minSdkVersion is set to a codename, it is translated to a number using the
860 provided map.
861
862 Args:
863 apk_name: The APK filename.
864
865 Returns:
866 The parsed SDK version number.
867
868 Raises:
869 ExternalError: On failing to get the min SDK version number.
870 """
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800871 version = GetMinSdkVersion(apk_name)
872 try:
873 return int(version)
874 except ValueError:
875 # Not a decimal number. Codename?
876 if version in codename_to_api_level_map:
877 return codename_to_api_level_map[version]
878 else:
Tao Baof47bf0f2018-03-21 23:28:51 -0700879 raise ExternalError(
880 "Unknown minSdkVersion: '{}'. Known codenames: {}".format(
881 version, codename_to_api_level_map))
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800882
883
884def SignFile(input_name, output_name, key, password, min_api_level=None,
Tao Bao76def242017-11-21 09:25:31 -0800885 codename_to_api_level_map=None, whole_file=False):
Doug Zongkereef39442009-04-02 12:14:19 -0700886 """Sign the input_name zip/jar/apk, producing output_name. Use the
887 given key and password (the latter may be None if the key does not
888 have a password.
889
Doug Zongker951495f2009-08-14 12:44:19 -0700890 If whole_file is true, use the "-w" option to SignApk to embed a
891 signature that covers the whole file in the archive comment of the
892 zip file.
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800893
894 min_api_level is the API Level (int) of the oldest platform this file may end
895 up on. If not specified for an APK, the API Level is obtained by interpreting
896 the minSdkVersion attribute of the APK's AndroidManifest.xml.
897
898 codename_to_api_level_map is needed to translate the codename which may be
899 encountered as the APK's minSdkVersion.
Doug Zongkereef39442009-04-02 12:14:19 -0700900 """
Tao Bao76def242017-11-21 09:25:31 -0800901 if codename_to_api_level_map is None:
902 codename_to_api_level_map = {}
Doug Zongker951495f2009-08-14 12:44:19 -0700903
Alex Klyubin9667b182015-12-10 13:38:50 -0800904 java_library_path = os.path.join(
905 OPTIONS.search_path, OPTIONS.signapk_shared_library_path)
906
Tao Baoe95540e2016-11-08 12:08:53 -0800907 cmd = ([OPTIONS.java_path] + OPTIONS.java_args +
908 ["-Djava.library.path=" + java_library_path,
909 "-jar", os.path.join(OPTIONS.search_path, OPTIONS.signapk_path)] +
910 OPTIONS.extra_signapk_args)
Doug Zongker951495f2009-08-14 12:44:19 -0700911 if whole_file:
912 cmd.append("-w")
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800913
914 min_sdk_version = min_api_level
915 if min_sdk_version is None:
916 if not whole_file:
917 min_sdk_version = GetMinSdkVersionInt(
918 input_name, codename_to_api_level_map)
919 if min_sdk_version is not None:
920 cmd.extend(["--min-sdk-version", str(min_sdk_version)])
921
T.R. Fullhart37e10522013-03-18 10:31:26 -0700922 cmd.extend([key + OPTIONS.public_key_suffix,
923 key + OPTIONS.private_key_suffix,
Alex Klyubineb756d72015-12-04 09:21:08 -0800924 input_name, output_name])
Doug Zongker951495f2009-08-14 12:44:19 -0700925
Tao Bao80921982018-03-21 21:02:19 -0700926 p = Run(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
927 stderr=subprocess.STDOUT)
Doug Zongkereef39442009-04-02 12:14:19 -0700928 if password is not None:
929 password += "\n"
Tao Bao80921982018-03-21 21:02:19 -0700930 stdoutdata, _ = p.communicate(password)
Doug Zongkereef39442009-04-02 12:14:19 -0700931 if p.returncode != 0:
Tao Bao80921982018-03-21 21:02:19 -0700932 raise ExternalError(
933 "Failed to run signapk.jar: return code {}:\n{}".format(
934 p.returncode, stdoutdata))
Doug Zongkereef39442009-04-02 12:14:19 -0700935
Doug Zongkereef39442009-04-02 12:14:19 -0700936
Doug Zongker37974732010-09-16 17:44:38 -0700937def CheckSize(data, target, info_dict):
Tao Bao9dd909e2017-11-14 11:27:32 -0800938 """Checks the data string passed against the max size limit.
Doug Zongkerc77a9ad2010-09-16 11:28:43 -0700939
Tao Bao9dd909e2017-11-14 11:27:32 -0800940 For non-AVB images, raise exception if the data is too big. Print a warning
941 if the data is nearing the maximum size.
942
943 For AVB images, the actual image size should be identical to the limit.
944
945 Args:
946 data: A string that contains all the data for the partition.
947 target: The partition name. The ".img" suffix is optional.
948 info_dict: The dict to be looked up for relevant info.
949 """
Dan Albert8b72aef2015-03-23 19:13:21 -0700950 if target.endswith(".img"):
951 target = target[:-4]
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700952 mount_point = "/" + target
953
Ying Wangf8824af2014-06-03 14:07:27 -0700954 fs_type = None
955 limit = None
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700956 if info_dict["fstab"]:
Dan Albert8b72aef2015-03-23 19:13:21 -0700957 if mount_point == "/userdata":
958 mount_point = "/data"
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700959 p = info_dict["fstab"][mount_point]
960 fs_type = p.fs_type
Andrew Boie0f9aec82012-02-14 09:32:52 -0800961 device = p.device
962 if "/" in device:
963 device = device[device.rfind("/")+1:]
Tao Bao76def242017-11-21 09:25:31 -0800964 limit = info_dict.get(device + "_size")
Dan Albert8b72aef2015-03-23 19:13:21 -0700965 if not fs_type or not limit:
966 return
Doug Zongkereef39442009-04-02 12:14:19 -0700967
Andrew Boie0f9aec82012-02-14 09:32:52 -0800968 size = len(data)
Tao Bao9dd909e2017-11-14 11:27:32 -0800969 # target could be 'userdata' or 'cache'. They should follow the non-AVB image
970 # path.
971 if info_dict.get("avb_enable") == "true" and target in AVB_PARTITIONS:
972 if size != limit:
973 raise ExternalError(
974 "Mismatching image size for %s: expected %d actual %d" % (
975 target, limit, size))
976 else:
977 pct = float(size) * 100.0 / limit
978 msg = "%s size (%d) is %.2f%% of limit (%d)" % (target, size, pct, limit)
979 if pct >= 99.0:
980 raise ExternalError(msg)
981 elif pct >= 95.0:
982 print("\n WARNING: %s\n" % (msg,))
983 elif OPTIONS.verbose:
984 print(" ", msg)
Doug Zongkereef39442009-04-02 12:14:19 -0700985
986
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800987def ReadApkCerts(tf_zip):
Tao Bao818ddf52018-01-05 11:17:34 -0800988 """Parses the APK certs info from a given target-files zip.
989
990 Given a target-files ZipFile, parses the META/apkcerts.txt entry and returns a
991 tuple with the following elements: (1) a dictionary that maps packages to
992 certs (based on the "certificate" and "private_key" attributes in the file;
993 (2) a string representing the extension of compressed APKs in the target files
994 (e.g ".gz", ".bro").
995
996 Args:
997 tf_zip: The input target_files ZipFile (already open).
998
999 Returns:
1000 (certmap, ext): certmap is a dictionary that maps packages to certs; ext is
1001 the extension string of compressed APKs (e.g. ".gz"), or None if there's
1002 no compressed APKs.
1003 """
Doug Zongkerf6a53aa2009-12-15 15:06:55 -08001004 certmap = {}
Narayan Kamatha07bf042017-08-14 14:49:21 +01001005 compressed_extension = None
1006
Tao Bao0f990332017-09-08 19:02:54 -07001007 # META/apkcerts.txt contains the info for _all_ the packages known at build
1008 # time. Filter out the ones that are not installed.
1009 installed_files = set()
1010 for name in tf_zip.namelist():
1011 basename = os.path.basename(name)
1012 if basename:
1013 installed_files.add(basename)
1014
Doug Zongkerf6a53aa2009-12-15 15:06:55 -08001015 for line in tf_zip.read("META/apkcerts.txt").split("\n"):
1016 line = line.strip()
Dan Albert8b72aef2015-03-23 19:13:21 -07001017 if not line:
1018 continue
Tao Bao818ddf52018-01-05 11:17:34 -08001019 m = re.match(
1020 r'^name="(?P<NAME>.*)"\s+certificate="(?P<CERT>.*)"\s+'
1021 r'private_key="(?P<PRIVKEY>.*?)"(\s+compressed="(?P<COMPRESSED>.*)")?$',
1022 line)
1023 if not m:
1024 continue
Narayan Kamatha07bf042017-08-14 14:49:21 +01001025
Tao Bao818ddf52018-01-05 11:17:34 -08001026 matches = m.groupdict()
1027 cert = matches["CERT"]
1028 privkey = matches["PRIVKEY"]
1029 name = matches["NAME"]
1030 this_compressed_extension = matches["COMPRESSED"]
1031
1032 public_key_suffix_len = len(OPTIONS.public_key_suffix)
1033 private_key_suffix_len = len(OPTIONS.private_key_suffix)
1034 if cert in SPECIAL_CERT_STRINGS and not privkey:
1035 certmap[name] = cert
1036 elif (cert.endswith(OPTIONS.public_key_suffix) and
1037 privkey.endswith(OPTIONS.private_key_suffix) and
1038 cert[:-public_key_suffix_len] == privkey[:-private_key_suffix_len]):
1039 certmap[name] = cert[:-public_key_suffix_len]
1040 else:
1041 raise ValueError("Failed to parse line from apkcerts.txt:\n" + line)
1042
1043 if not this_compressed_extension:
1044 continue
1045
1046 # Only count the installed files.
1047 filename = name + '.' + this_compressed_extension
1048 if filename not in installed_files:
1049 continue
1050
1051 # Make sure that all the values in the compression map have the same
1052 # extension. We don't support multiple compression methods in the same
1053 # system image.
1054 if compressed_extension:
1055 if this_compressed_extension != compressed_extension:
1056 raise ValueError(
1057 "Multiple compressed extensions: {} vs {}".format(
1058 compressed_extension, this_compressed_extension))
1059 else:
1060 compressed_extension = this_compressed_extension
1061
1062 return (certmap,
1063 ("." + compressed_extension) if compressed_extension else None)
Doug Zongkerf6a53aa2009-12-15 15:06:55 -08001064
1065
Doug Zongkereef39442009-04-02 12:14:19 -07001066COMMON_DOCSTRING = """
Tao Bao30df8b42018-04-23 15:32:53 -07001067Global options
1068
1069 -p (--path) <dir>
1070 Prepend <dir>/bin to the list of places to search for binaries run by this
1071 script, and expect to find jars in <dir>/framework.
Doug Zongkereef39442009-04-02 12:14:19 -07001072
Doug Zongker05d3dea2009-06-22 11:32:31 -07001073 -s (--device_specific) <file>
Tao Bao30df8b42018-04-23 15:32:53 -07001074 Path to the Python module containing device-specific releasetools code.
Doug Zongker05d3dea2009-06-22 11:32:31 -07001075
Tao Bao30df8b42018-04-23 15:32:53 -07001076 -x (--extra) <key=value>
1077 Add a key/value pair to the 'extras' dict, which device-specific extension
1078 code may look at.
Doug Zongker8bec09e2009-11-30 15:37:14 -08001079
Doug Zongkereef39442009-04-02 12:14:19 -07001080 -v (--verbose)
1081 Show command lines being executed.
1082
1083 -h (--help)
1084 Display this usage message and exit.
1085"""
1086
1087def Usage(docstring):
Tao Bao89fbb0f2017-01-10 10:47:58 -08001088 print(docstring.rstrip("\n"))
1089 print(COMMON_DOCSTRING)
Doug Zongkereef39442009-04-02 12:14:19 -07001090
1091
1092def ParseOptions(argv,
1093 docstring,
1094 extra_opts="", extra_long_opts=(),
1095 extra_option_handler=None):
1096 """Parse the options in argv and return any arguments that aren't
1097 flags. docstring is the calling module's docstring, to be displayed
1098 for errors and -h. extra_opts and extra_long_opts are for flags
1099 defined by the caller, which are processed by passing them to
1100 extra_option_handler."""
1101
1102 try:
1103 opts, args = getopt.getopt(
Doug Zongker8bec09e2009-11-30 15:37:14 -08001104 argv, "hvp:s:x:" + extra_opts,
Alex Klyubin9667b182015-12-10 13:38:50 -08001105 ["help", "verbose", "path=", "signapk_path=",
1106 "signapk_shared_library_path=", "extra_signapk_args=",
Baligh Uddinbdc2e312014-09-05 17:36:20 -07001107 "java_path=", "java_args=", "public_key_suffix=",
Baligh Uddin601ddea2015-06-09 15:48:14 -07001108 "private_key_suffix=", "boot_signer_path=", "boot_signer_args=",
1109 "verity_signer_path=", "verity_signer_args=", "device_specific=",
Baligh Uddine2048682014-11-20 09:52:05 -08001110 "extra="] +
T.R. Fullhart37e10522013-03-18 10:31:26 -07001111 list(extra_long_opts))
Dan Albert8b72aef2015-03-23 19:13:21 -07001112 except getopt.GetoptError as err:
Doug Zongkereef39442009-04-02 12:14:19 -07001113 Usage(docstring)
Tao Bao89fbb0f2017-01-10 10:47:58 -08001114 print("**", str(err), "**")
Doug Zongkereef39442009-04-02 12:14:19 -07001115 sys.exit(2)
1116
Doug Zongkereef39442009-04-02 12:14:19 -07001117 for o, a in opts:
1118 if o in ("-h", "--help"):
1119 Usage(docstring)
1120 sys.exit()
1121 elif o in ("-v", "--verbose"):
1122 OPTIONS.verbose = True
1123 elif o in ("-p", "--path"):
Doug Zongker602a84e2009-06-18 08:35:12 -07001124 OPTIONS.search_path = a
T.R. Fullhart37e10522013-03-18 10:31:26 -07001125 elif o in ("--signapk_path",):
1126 OPTIONS.signapk_path = a
Alex Klyubin9667b182015-12-10 13:38:50 -08001127 elif o in ("--signapk_shared_library_path",):
1128 OPTIONS.signapk_shared_library_path = a
T.R. Fullhart37e10522013-03-18 10:31:26 -07001129 elif o in ("--extra_signapk_args",):
1130 OPTIONS.extra_signapk_args = shlex.split(a)
1131 elif o in ("--java_path",):
1132 OPTIONS.java_path = a
Baligh Uddin339ee492014-09-05 11:18:07 -07001133 elif o in ("--java_args",):
Tao Baoe95540e2016-11-08 12:08:53 -08001134 OPTIONS.java_args = shlex.split(a)
T.R. Fullhart37e10522013-03-18 10:31:26 -07001135 elif o in ("--public_key_suffix",):
1136 OPTIONS.public_key_suffix = a
1137 elif o in ("--private_key_suffix",):
1138 OPTIONS.private_key_suffix = a
Baligh Uddine2048682014-11-20 09:52:05 -08001139 elif o in ("--boot_signer_path",):
1140 OPTIONS.boot_signer_path = a
Baligh Uddin601ddea2015-06-09 15:48:14 -07001141 elif o in ("--boot_signer_args",):
1142 OPTIONS.boot_signer_args = shlex.split(a)
1143 elif o in ("--verity_signer_path",):
1144 OPTIONS.verity_signer_path = a
1145 elif o in ("--verity_signer_args",):
1146 OPTIONS.verity_signer_args = shlex.split(a)
Doug Zongker05d3dea2009-06-22 11:32:31 -07001147 elif o in ("-s", "--device_specific"):
1148 OPTIONS.device_specific = a
Doug Zongker5ecba702009-12-03 16:36:20 -08001149 elif o in ("-x", "--extra"):
Doug Zongker8bec09e2009-11-30 15:37:14 -08001150 key, value = a.split("=", 1)
1151 OPTIONS.extras[key] = value
Doug Zongkereef39442009-04-02 12:14:19 -07001152 else:
1153 if extra_option_handler is None or not extra_option_handler(o, a):
1154 assert False, "unknown option \"%s\"" % (o,)
1155
Doug Zongker85448772014-09-09 14:59:20 -07001156 if OPTIONS.search_path:
1157 os.environ["PATH"] = (os.path.join(OPTIONS.search_path, "bin") +
1158 os.pathsep + os.environ["PATH"])
Doug Zongkereef39442009-04-02 12:14:19 -07001159
1160 return args
1161
1162
Tao Bao4c851b12016-09-19 13:54:38 -07001163def MakeTempFile(prefix='tmp', suffix=''):
Doug Zongkerfc44a512014-08-26 13:10:25 -07001164 """Make a temp file and add it to the list of things to be deleted
1165 when Cleanup() is called. Return the filename."""
1166 fd, fn = tempfile.mkstemp(prefix=prefix, suffix=suffix)
1167 os.close(fd)
1168 OPTIONS.tempfiles.append(fn)
1169 return fn
1170
1171
Tao Bao1c830bf2017-12-25 10:43:47 -08001172def MakeTempDir(prefix='tmp', suffix=''):
1173 """Makes a temporary dir that will be cleaned up with a call to Cleanup().
1174
1175 Returns:
1176 The absolute pathname of the new directory.
1177 """
1178 dir_name = tempfile.mkdtemp(suffix=suffix, prefix=prefix)
1179 OPTIONS.tempfiles.append(dir_name)
1180 return dir_name
1181
1182
Doug Zongkereef39442009-04-02 12:14:19 -07001183def Cleanup():
1184 for i in OPTIONS.tempfiles:
1185 if os.path.isdir(i):
Tao Bao1c830bf2017-12-25 10:43:47 -08001186 shutil.rmtree(i, ignore_errors=True)
Doug Zongkereef39442009-04-02 12:14:19 -07001187 else:
1188 os.remove(i)
Tao Bao1c830bf2017-12-25 10:43:47 -08001189 del OPTIONS.tempfiles[:]
Doug Zongker8ce7c252009-05-22 13:34:54 -07001190
1191
1192class PasswordManager(object):
1193 def __init__(self):
Tao Bao76def242017-11-21 09:25:31 -08001194 self.editor = os.getenv("EDITOR")
1195 self.pwfile = os.getenv("ANDROID_PW_FILE")
Doug Zongker8ce7c252009-05-22 13:34:54 -07001196
1197 def GetPasswords(self, items):
1198 """Get passwords corresponding to each string in 'items',
1199 returning a dict. (The dict may have keys in addition to the
1200 values in 'items'.)
1201
1202 Uses the passwords in $ANDROID_PW_FILE if available, letting the
1203 user edit that file to add more needed passwords. If no editor is
1204 available, or $ANDROID_PW_FILE isn't define, prompts the user
1205 interactively in the ordinary way.
1206 """
1207
1208 current = self.ReadFile()
1209
1210 first = True
1211 while True:
1212 missing = []
1213 for i in items:
1214 if i not in current or not current[i]:
1215 missing.append(i)
1216 # Are all the passwords already in the file?
Dan Albert8b72aef2015-03-23 19:13:21 -07001217 if not missing:
1218 return current
Doug Zongker8ce7c252009-05-22 13:34:54 -07001219
1220 for i in missing:
1221 current[i] = ""
1222
1223 if not first:
Tao Bao89fbb0f2017-01-10 10:47:58 -08001224 print("key file %s still missing some passwords." % (self.pwfile,))
Doug Zongker8ce7c252009-05-22 13:34:54 -07001225 answer = raw_input("try to edit again? [y]> ").strip()
1226 if answer and answer[0] not in 'yY':
1227 raise RuntimeError("key passwords unavailable")
1228 first = False
1229
1230 current = self.UpdateAndReadFile(current)
1231
Dan Albert8b72aef2015-03-23 19:13:21 -07001232 def PromptResult(self, current): # pylint: disable=no-self-use
Doug Zongker8ce7c252009-05-22 13:34:54 -07001233 """Prompt the user to enter a value (password) for each key in
1234 'current' whose value is fales. Returns a new dict with all the
1235 values.
1236 """
1237 result = {}
1238 for k, v in sorted(current.iteritems()):
1239 if v:
1240 result[k] = v
1241 else:
1242 while True:
Dan Albert8b72aef2015-03-23 19:13:21 -07001243 result[k] = getpass.getpass(
1244 "Enter password for %s key> " % k).strip()
1245 if result[k]:
1246 break
Doug Zongker8ce7c252009-05-22 13:34:54 -07001247 return result
1248
1249 def UpdateAndReadFile(self, current):
1250 if not self.editor or not self.pwfile:
1251 return self.PromptResult(current)
1252
1253 f = open(self.pwfile, "w")
Dan Albert8b72aef2015-03-23 19:13:21 -07001254 os.chmod(self.pwfile, 0o600)
Doug Zongker8ce7c252009-05-22 13:34:54 -07001255 f.write("# Enter key passwords between the [[[ ]]] brackets.\n")
1256 f.write("# (Additional spaces are harmless.)\n\n")
1257
1258 first_line = None
Dan Albert8b72aef2015-03-23 19:13:21 -07001259 sorted_list = sorted([(not v, k, v) for (k, v) in current.iteritems()])
1260 for i, (_, k, v) in enumerate(sorted_list):
Doug Zongker8ce7c252009-05-22 13:34:54 -07001261 f.write("[[[ %s ]]] %s\n" % (v, k))
1262 if not v and first_line is None:
1263 # position cursor on first line with no password.
1264 first_line = i + 4
1265 f.close()
1266
1267 p = Run([self.editor, "+%d" % (first_line,), self.pwfile])
1268 _, _ = p.communicate()
1269
1270 return self.ReadFile()
1271
1272 def ReadFile(self):
1273 result = {}
Dan Albert8b72aef2015-03-23 19:13:21 -07001274 if self.pwfile is None:
1275 return result
Doug Zongker8ce7c252009-05-22 13:34:54 -07001276 try:
1277 f = open(self.pwfile, "r")
1278 for line in f:
1279 line = line.strip()
Dan Albert8b72aef2015-03-23 19:13:21 -07001280 if not line or line[0] == '#':
1281 continue
Doug Zongker8ce7c252009-05-22 13:34:54 -07001282 m = re.match(r"^\[\[\[\s*(.*?)\s*\]\]\]\s*(\S+)$", line)
1283 if not m:
Tao Bao89fbb0f2017-01-10 10:47:58 -08001284 print("failed to parse password file: ", line)
Doug Zongker8ce7c252009-05-22 13:34:54 -07001285 else:
1286 result[m.group(2)] = m.group(1)
1287 f.close()
Dan Albert8b72aef2015-03-23 19:13:21 -07001288 except IOError as e:
Doug Zongker8ce7c252009-05-22 13:34:54 -07001289 if e.errno != errno.ENOENT:
Tao Bao89fbb0f2017-01-10 10:47:58 -08001290 print("error reading password file: ", str(e))
Doug Zongker8ce7c252009-05-22 13:34:54 -07001291 return result
Doug Zongker048e7ca2009-06-15 14:31:53 -07001292
1293
Dan Albert8e0178d2015-01-27 15:53:15 -08001294def ZipWrite(zip_file, filename, arcname=None, perms=0o644,
1295 compress_type=None):
1296 import datetime
1297
1298 # http://b/18015246
1299 # Python 2.7's zipfile implementation wrongly thinks that zip64 is required
1300 # for files larger than 2GiB. We can work around this by adjusting their
1301 # limit. Note that `zipfile.writestr()` will not work for strings larger than
1302 # 2GiB. The Python interpreter sometimes rejects strings that large (though
1303 # it isn't clear to me exactly what circumstances cause this).
1304 # `zipfile.write()` must be used directly to work around this.
1305 #
1306 # This mess can be avoided if we port to python3.
1307 saved_zip64_limit = zipfile.ZIP64_LIMIT
1308 zipfile.ZIP64_LIMIT = (1 << 32) - 1
1309
1310 if compress_type is None:
1311 compress_type = zip_file.compression
1312 if arcname is None:
1313 arcname = filename
1314
1315 saved_stat = os.stat(filename)
1316
1317 try:
1318 # `zipfile.write()` doesn't allow us to pass ZipInfo, so just modify the
1319 # file to be zipped and reset it when we're done.
1320 os.chmod(filename, perms)
1321
1322 # Use a fixed timestamp so the output is repeatable.
Bryan Henrye6d547d2018-07-31 18:32:00 -07001323 # Note: Use of fromtimestamp rather than utcfromtimestamp here is
1324 # intentional. zip stores datetimes in local time without a time zone
1325 # attached, so we need "epoch" but in the local time zone to get 2009/01/01
1326 # in the zip archive.
1327 local_epoch = datetime.datetime.fromtimestamp(0)
1328 timestamp = (datetime.datetime(2009, 1, 1) - local_epoch).total_seconds()
Dan Albert8e0178d2015-01-27 15:53:15 -08001329 os.utime(filename, (timestamp, timestamp))
1330
1331 zip_file.write(filename, arcname=arcname, compress_type=compress_type)
1332 finally:
1333 os.chmod(filename, saved_stat.st_mode)
1334 os.utime(filename, (saved_stat.st_atime, saved_stat.st_mtime))
1335 zipfile.ZIP64_LIMIT = saved_zip64_limit
1336
1337
Tao Bao58c1b962015-05-20 09:32:18 -07001338def ZipWriteStr(zip_file, zinfo_or_arcname, data, perms=None,
Tao Baof3282b42015-04-01 11:21:55 -07001339 compress_type=None):
1340 """Wrap zipfile.writestr() function to work around the zip64 limit.
1341
1342 Even with the ZIP64_LIMIT workaround, it won't allow writing a string
1343 longer than 2GiB. It gives 'OverflowError: size does not fit in an int'
1344 when calling crc32(bytes).
1345
1346 But it still works fine to write a shorter string into a large zip file.
1347 We should use ZipWrite() whenever possible, and only use ZipWriteStr()
1348 when we know the string won't be too long.
1349 """
1350
1351 saved_zip64_limit = zipfile.ZIP64_LIMIT
1352 zipfile.ZIP64_LIMIT = (1 << 32) - 1
1353
1354 if not isinstance(zinfo_or_arcname, zipfile.ZipInfo):
1355 zinfo = zipfile.ZipInfo(filename=zinfo_or_arcname)
Dan Albert8b72aef2015-03-23 19:13:21 -07001356 zinfo.compress_type = zip_file.compression
Tao Bao58c1b962015-05-20 09:32:18 -07001357 if perms is None:
Tao Bao2a410582015-07-10 17:18:23 -07001358 perms = 0o100644
Geremy Condra36bd3652014-02-06 19:45:10 -08001359 else:
Tao Baof3282b42015-04-01 11:21:55 -07001360 zinfo = zinfo_or_arcname
1361
1362 # If compress_type is given, it overrides the value in zinfo.
1363 if compress_type is not None:
1364 zinfo.compress_type = compress_type
1365
Tao Bao58c1b962015-05-20 09:32:18 -07001366 # If perms is given, it has a priority.
1367 if perms is not None:
Tao Bao2a410582015-07-10 17:18:23 -07001368 # If perms doesn't set the file type, mark it as a regular file.
1369 if perms & 0o770000 == 0:
1370 perms |= 0o100000
Tao Bao58c1b962015-05-20 09:32:18 -07001371 zinfo.external_attr = perms << 16
1372
Tao Baof3282b42015-04-01 11:21:55 -07001373 # Use a fixed timestamp so the output is repeatable.
Tao Baof3282b42015-04-01 11:21:55 -07001374 zinfo.date_time = (2009, 1, 1, 0, 0, 0)
1375
Dan Albert8b72aef2015-03-23 19:13:21 -07001376 zip_file.writestr(zinfo, data)
Tao Baof3282b42015-04-01 11:21:55 -07001377 zipfile.ZIP64_LIMIT = saved_zip64_limit
1378
1379
Tao Bao89d7ab22017-12-14 17:05:33 -08001380def ZipDelete(zip_filename, entries):
1381 """Deletes entries from a ZIP file.
1382
1383 Since deleting entries from a ZIP file is not supported, it shells out to
1384 'zip -d'.
1385
1386 Args:
1387 zip_filename: The name of the ZIP file.
1388 entries: The name of the entry, or the list of names to be deleted.
1389
1390 Raises:
1391 AssertionError: In case of non-zero return from 'zip'.
1392 """
1393 if isinstance(entries, basestring):
1394 entries = [entries]
1395 cmd = ["zip", "-d", zip_filename] + entries
1396 proc = Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
1397 stdoutdata, _ = proc.communicate()
1398 assert proc.returncode == 0, "Failed to delete %s:\n%s" % (entries,
1399 stdoutdata)
1400
1401
Tao Baof3282b42015-04-01 11:21:55 -07001402def ZipClose(zip_file):
1403 # http://b/18015246
1404 # zipfile also refers to ZIP64_LIMIT during close() when it writes out the
1405 # central directory.
1406 saved_zip64_limit = zipfile.ZIP64_LIMIT
1407 zipfile.ZIP64_LIMIT = (1 << 32) - 1
1408
1409 zip_file.close()
1410
1411 zipfile.ZIP64_LIMIT = saved_zip64_limit
Doug Zongker05d3dea2009-06-22 11:32:31 -07001412
1413
1414class DeviceSpecificParams(object):
1415 module = None
1416 def __init__(self, **kwargs):
1417 """Keyword arguments to the constructor become attributes of this
1418 object, which is passed to all functions in the device-specific
1419 module."""
1420 for k, v in kwargs.iteritems():
1421 setattr(self, k, v)
Doug Zongker8bec09e2009-11-30 15:37:14 -08001422 self.extras = OPTIONS.extras
Doug Zongker05d3dea2009-06-22 11:32:31 -07001423
1424 if self.module is None:
1425 path = OPTIONS.device_specific
Dan Albert8b72aef2015-03-23 19:13:21 -07001426 if not path:
1427 return
Doug Zongker8e2f2b92009-06-24 14:34:57 -07001428 try:
1429 if os.path.isdir(path):
1430 info = imp.find_module("releasetools", [path])
1431 else:
1432 d, f = os.path.split(path)
1433 b, x = os.path.splitext(f)
1434 if x == ".py":
1435 f = b
1436 info = imp.find_module(f, [d])
Tao Bao89fbb0f2017-01-10 10:47:58 -08001437 print("loaded device-specific extensions from", path)
Doug Zongker8e2f2b92009-06-24 14:34:57 -07001438 self.module = imp.load_module("device_specific", *info)
1439 except ImportError:
Tao Bao89fbb0f2017-01-10 10:47:58 -08001440 print("unable to load device-specific module; assuming none")
Doug Zongker05d3dea2009-06-22 11:32:31 -07001441
1442 def _DoCall(self, function_name, *args, **kwargs):
1443 """Call the named function in the device-specific module, passing
1444 the given args and kwargs. The first argument to the call will be
1445 the DeviceSpecific object itself. If there is no module, or the
1446 module does not define the function, return the value of the
1447 'default' kwarg (which itself defaults to None)."""
1448 if self.module is None or not hasattr(self.module, function_name):
Tao Bao76def242017-11-21 09:25:31 -08001449 return kwargs.get("default")
Doug Zongker05d3dea2009-06-22 11:32:31 -07001450 return getattr(self.module, function_name)(*((self,) + args), **kwargs)
1451
1452 def FullOTA_Assertions(self):
1453 """Called after emitting the block of assertions at the top of a
1454 full OTA package. Implementations can add whatever additional
1455 assertions they like."""
1456 return self._DoCall("FullOTA_Assertions")
1457
Doug Zongkere5ff5902012-01-17 10:55:37 -08001458 def FullOTA_InstallBegin(self):
1459 """Called at the start of full OTA installation."""
1460 return self._DoCall("FullOTA_InstallBegin")
1461
Doug Zongker05d3dea2009-06-22 11:32:31 -07001462 def FullOTA_InstallEnd(self):
1463 """Called at the end of full OTA installation; typically this is
1464 used to install the image for the device's baseband processor."""
1465 return self._DoCall("FullOTA_InstallEnd")
1466
1467 def IncrementalOTA_Assertions(self):
1468 """Called after emitting the block of assertions at the top of an
1469 incremental OTA package. Implementations can add whatever
1470 additional assertions they like."""
1471 return self._DoCall("IncrementalOTA_Assertions")
1472
Doug Zongkere5ff5902012-01-17 10:55:37 -08001473 def IncrementalOTA_VerifyBegin(self):
1474 """Called at the start of the verification phase of incremental
1475 OTA installation; additional checks can be placed here to abort
1476 the script before any changes are made."""
1477 return self._DoCall("IncrementalOTA_VerifyBegin")
1478
Doug Zongker05d3dea2009-06-22 11:32:31 -07001479 def IncrementalOTA_VerifyEnd(self):
1480 """Called at the end of the verification phase of incremental OTA
1481 installation; additional checks can be placed here to abort the
1482 script before any changes are made."""
1483 return self._DoCall("IncrementalOTA_VerifyEnd")
1484
Doug Zongkere5ff5902012-01-17 10:55:37 -08001485 def IncrementalOTA_InstallBegin(self):
1486 """Called at the start of incremental OTA installation (after
1487 verification is complete)."""
1488 return self._DoCall("IncrementalOTA_InstallBegin")
1489
Doug Zongker05d3dea2009-06-22 11:32:31 -07001490 def IncrementalOTA_InstallEnd(self):
1491 """Called at the end of incremental OTA installation; typically
1492 this is used to install the image for the device's baseband
1493 processor."""
1494 return self._DoCall("IncrementalOTA_InstallEnd")
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001495
Tao Bao9bc6bb22015-11-09 16:58:28 -08001496 def VerifyOTA_Assertions(self):
1497 return self._DoCall("VerifyOTA_Assertions")
1498
Tao Bao76def242017-11-21 09:25:31 -08001499
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001500class File(object):
Tao Bao76def242017-11-21 09:25:31 -08001501 def __init__(self, name, data, compress_size=None):
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001502 self.name = name
1503 self.data = data
1504 self.size = len(data)
YOUNG HO CHAccc5c402016-10-13 13:40:46 +09001505 self.compress_size = compress_size or self.size
Doug Zongker55d93282011-01-25 17:03:34 -08001506 self.sha1 = sha1(data).hexdigest()
1507
1508 @classmethod
1509 def FromLocalFile(cls, name, diskname):
1510 f = open(diskname, "rb")
1511 data = f.read()
1512 f.close()
1513 return File(name, data)
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001514
1515 def WriteToTemp(self):
1516 t = tempfile.NamedTemporaryFile()
1517 t.write(self.data)
1518 t.flush()
1519 return t
1520
Dan Willemsen2ee00d52017-03-05 19:51:56 -08001521 def WriteToDir(self, d):
1522 with open(os.path.join(d, self.name), "wb") as fp:
1523 fp.write(self.data)
1524
Geremy Condra36bd3652014-02-06 19:45:10 -08001525 def AddToZip(self, z, compression=None):
Tao Baof3282b42015-04-01 11:21:55 -07001526 ZipWriteStr(z, self.name, self.data, compress_type=compression)
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001527
Tao Bao76def242017-11-21 09:25:31 -08001528
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001529DIFF_PROGRAM_BY_EXT = {
1530 ".gz" : "imgdiff",
1531 ".zip" : ["imgdiff", "-z"],
1532 ".jar" : ["imgdiff", "-z"],
1533 ".apk" : ["imgdiff", "-z"],
1534 ".img" : "imgdiff",
1535 }
1536
Tao Bao76def242017-11-21 09:25:31 -08001537
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001538class Difference(object):
Doug Zongker24cd2802012-08-14 16:36:15 -07001539 def __init__(self, tf, sf, diff_program=None):
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001540 self.tf = tf
1541 self.sf = sf
1542 self.patch = None
Doug Zongker24cd2802012-08-14 16:36:15 -07001543 self.diff_program = diff_program
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001544
1545 def ComputePatch(self):
1546 """Compute the patch (as a string of data) needed to turn sf into
1547 tf. Returns the same tuple as GetPatch()."""
1548
1549 tf = self.tf
1550 sf = self.sf
1551
Doug Zongker24cd2802012-08-14 16:36:15 -07001552 if self.diff_program:
1553 diff_program = self.diff_program
1554 else:
1555 ext = os.path.splitext(tf.name)[1]
1556 diff_program = DIFF_PROGRAM_BY_EXT.get(ext, "bsdiff")
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001557
1558 ttemp = tf.WriteToTemp()
1559 stemp = sf.WriteToTemp()
1560
1561 ext = os.path.splitext(tf.name)[1]
1562
1563 try:
1564 ptemp = tempfile.NamedTemporaryFile()
1565 if isinstance(diff_program, list):
1566 cmd = copy.copy(diff_program)
1567 else:
1568 cmd = [diff_program]
1569 cmd.append(stemp.name)
1570 cmd.append(ttemp.name)
1571 cmd.append(ptemp.name)
1572 p = Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Doug Zongkerf8340082014-08-05 10:39:37 -07001573 err = []
1574 def run():
1575 _, e = p.communicate()
Dan Albert8b72aef2015-03-23 19:13:21 -07001576 if e:
1577 err.append(e)
Doug Zongkerf8340082014-08-05 10:39:37 -07001578 th = threading.Thread(target=run)
1579 th.start()
1580 th.join(timeout=300) # 5 mins
1581 if th.is_alive():
Tao Bao89fbb0f2017-01-10 10:47:58 -08001582 print("WARNING: diff command timed out")
Doug Zongkerf8340082014-08-05 10:39:37 -07001583 p.terminate()
1584 th.join(5)
1585 if th.is_alive():
1586 p.kill()
1587 th.join()
1588
Tianjie Xua2a9f992018-01-05 15:15:54 -08001589 if p.returncode != 0:
Tao Bao89fbb0f2017-01-10 10:47:58 -08001590 print("WARNING: failure running %s:\n%s\n" % (
1591 diff_program, "".join(err)))
Doug Zongkerf8340082014-08-05 10:39:37 -07001592 self.patch = None
1593 return None, None, None
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001594 diff = ptemp.read()
1595 finally:
1596 ptemp.close()
1597 stemp.close()
1598 ttemp.close()
1599
1600 self.patch = diff
1601 return self.tf, self.sf, self.patch
1602
1603
1604 def GetPatch(self):
Tao Bao76def242017-11-21 09:25:31 -08001605 """Returns a tuple of (target_file, source_file, patch_data).
1606
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001607 patch_data may be None if ComputePatch hasn't been called, or if
Tao Bao76def242017-11-21 09:25:31 -08001608 computing the patch failed.
1609 """
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001610 return self.tf, self.sf, self.patch
1611
1612
1613def ComputeDifferences(diffs):
1614 """Call ComputePatch on all the Difference objects in 'diffs'."""
Tao Bao89fbb0f2017-01-10 10:47:58 -08001615 print(len(diffs), "diffs to compute")
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001616
1617 # Do the largest files first, to try and reduce the long-pole effect.
1618 by_size = [(i.tf.size, i) for i in diffs]
1619 by_size.sort(reverse=True)
1620 by_size = [i[1] for i in by_size]
1621
1622 lock = threading.Lock()
1623 diff_iter = iter(by_size) # accessed under lock
1624
1625 def worker():
1626 try:
1627 lock.acquire()
1628 for d in diff_iter:
1629 lock.release()
1630 start = time.time()
1631 d.ComputePatch()
1632 dur = time.time() - start
1633 lock.acquire()
1634
1635 tf, sf, patch = d.GetPatch()
1636 if sf.name == tf.name:
1637 name = tf.name
1638 else:
1639 name = "%s (%s)" % (tf.name, sf.name)
1640 if patch is None:
Tao Bao76def242017-11-21 09:25:31 -08001641 print(
1642 "patching failed! %s" % (name,))
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001643 else:
Tao Bao89fbb0f2017-01-10 10:47:58 -08001644 print("%8.2f sec %8d / %8d bytes (%6.2f%%) %s" % (
1645 dur, len(patch), tf.size, 100.0 * len(patch) / tf.size, name))
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001646 lock.release()
Dan Albert8b72aef2015-03-23 19:13:21 -07001647 except Exception as e:
Tao Bao89fbb0f2017-01-10 10:47:58 -08001648 print(e)
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001649 raise
1650
1651 # start worker threads; wait for them all to finish.
1652 threads = [threading.Thread(target=worker)
1653 for i in range(OPTIONS.worker_threads)]
1654 for th in threads:
1655 th.start()
1656 while threads:
1657 threads.pop().join()
Doug Zongker96a57e72010-09-26 14:57:41 -07001658
1659
Dan Albert8b72aef2015-03-23 19:13:21 -07001660class BlockDifference(object):
1661 def __init__(self, partition, tgt, src=None, check_first_block=False,
Tao Bao293fd132016-06-11 12:19:23 -07001662 version=None, disable_imgdiff=False):
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001663 self.tgt = tgt
1664 self.src = src
1665 self.partition = partition
Doug Zongkerb34fcce2014-09-11 09:34:56 -07001666 self.check_first_block = check_first_block
Tao Bao293fd132016-06-11 12:19:23 -07001667 self.disable_imgdiff = disable_imgdiff
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001668
Tao Baodd2a5892015-03-12 12:32:37 -07001669 if version is None:
Tao Bao0582cb62017-12-21 11:47:01 -08001670 version = max(
1671 int(i) for i in
1672 OPTIONS.info_dict.get("blockimgdiff_versions", "1").split(","))
Tao Bao8fad03e2017-03-01 14:36:26 -08001673 assert version >= 3
Tao Baodd2a5892015-03-12 12:32:37 -07001674 self.version = version
Doug Zongker62338182014-09-08 08:29:55 -07001675
1676 b = blockimgdiff.BlockImageDiff(tgt, src, threads=OPTIONS.worker_threads,
Tao Bao293fd132016-06-11 12:19:23 -07001677 version=self.version,
1678 disable_imgdiff=self.disable_imgdiff)
Tao Bao04bce3a2018-02-28 11:11:00 -08001679 self.path = os.path.join(MakeTempDir(), partition)
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001680 b.Compute(self.path)
Tao Baod8d14be2016-02-04 14:26:02 -08001681 self._required_cache = b.max_stashed_size
Tao Baod522bdc2016-04-12 15:53:16 -07001682 self.touched_src_ranges = b.touched_src_ranges
1683 self.touched_src_sha1 = b.touched_src_sha1
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001684
Tao Baoaac4ad52015-10-16 15:26:34 -07001685 if src is None:
1686 _, self.device = GetTypeAndDevice("/" + partition, OPTIONS.info_dict)
1687 else:
1688 _, self.device = GetTypeAndDevice("/" + partition,
1689 OPTIONS.source_info_dict)
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001690
Tao Baod8d14be2016-02-04 14:26:02 -08001691 @property
1692 def required_cache(self):
1693 return self._required_cache
1694
Tao Bao76def242017-11-21 09:25:31 -08001695 def WriteScript(self, script, output_zip, progress=None,
1696 write_verify_script=False):
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001697 if not self.src:
1698 # write the output unconditionally
Jesse Zhao75bcea02015-01-06 10:59:53 -08001699 script.Print("Patching %s image unconditionally..." % (self.partition,))
1700 else:
1701 script.Print("Patching %s image after verification." % (self.partition,))
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001702
Dan Albert8b72aef2015-03-23 19:13:21 -07001703 if progress:
1704 script.ShowProgress(progress, 0)
Jesse Zhao75bcea02015-01-06 10:59:53 -08001705 self._WriteUpdate(script, output_zip)
Tao Bao76def242017-11-21 09:25:31 -08001706
1707 if write_verify_script:
Tianjie Xub2deb222016-03-25 15:01:33 -07001708 self._WritePostInstallVerifyScript(script)
Jesse Zhao75bcea02015-01-06 10:59:53 -08001709
Tao Bao9bc6bb22015-11-09 16:58:28 -08001710 def WriteStrictVerifyScript(self, script):
1711 """Verify all the blocks in the care_map, including clobbered blocks.
1712
1713 This differs from the WriteVerifyScript() function: a) it prints different
1714 error messages; b) it doesn't allow half-way updated images to pass the
1715 verification."""
1716
1717 partition = self.partition
1718 script.Print("Verifying %s..." % (partition,))
1719 ranges = self.tgt.care_map
1720 ranges_str = ranges.to_string_raw()
Tao Bao76def242017-11-21 09:25:31 -08001721 script.AppendExtra(
1722 'range_sha1("%s", "%s") == "%s" && ui_print(" Verified.") || '
1723 'ui_print("\\"%s\\" has unexpected contents.");' % (
1724 self.device, ranges_str,
1725 self.tgt.TotalSha1(include_clobbered_blocks=True),
1726 self.device))
Tao Bao9bc6bb22015-11-09 16:58:28 -08001727 script.AppendExtra("")
1728
Tao Baod522bdc2016-04-12 15:53:16 -07001729 def WriteVerifyScript(self, script, touched_blocks_only=False):
Sami Tolvanendd67a292014-12-09 16:40:34 +00001730 partition = self.partition
Tao Baof9efe282016-04-14 15:58:05 -07001731
1732 # full OTA
Jesse Zhao75bcea02015-01-06 10:59:53 -08001733 if not self.src:
Sami Tolvanendd67a292014-12-09 16:40:34 +00001734 script.Print("Image %s will be patched unconditionally." % (partition,))
Tao Baof9efe282016-04-14 15:58:05 -07001735
1736 # incremental OTA
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001737 else:
Tao Bao8fad03e2017-03-01 14:36:26 -08001738 if touched_blocks_only:
Tao Baod522bdc2016-04-12 15:53:16 -07001739 ranges = self.touched_src_ranges
1740 expected_sha1 = self.touched_src_sha1
1741 else:
1742 ranges = self.src.care_map.subtract(self.src.clobbered_blocks)
1743 expected_sha1 = self.src.TotalSha1()
Tao Baof9efe282016-04-14 15:58:05 -07001744
1745 # No blocks to be checked, skipping.
1746 if not ranges:
1747 return
1748
Tao Bao5ece99d2015-05-12 11:42:31 -07001749 ranges_str = ranges.to_string_raw()
Tao Bao76def242017-11-21 09:25:31 -08001750 script.AppendExtra(
1751 'if (range_sha1("%s", "%s") == "%s" || block_image_verify("%s", '
1752 'package_extract_file("%s.transfer.list"), "%s.new.dat", '
1753 '"%s.patch.dat")) then' % (
1754 self.device, ranges_str, expected_sha1,
1755 self.device, partition, partition, partition))
Tao Baodd2a5892015-03-12 12:32:37 -07001756 script.Print('Verified %s image...' % (partition,))
Dan Albert8b72aef2015-03-23 19:13:21 -07001757 script.AppendExtra('else')
Sami Tolvanendd67a292014-12-09 16:40:34 +00001758
Tianjie Xufc3422a2015-12-15 11:53:59 -08001759 if self.version >= 4:
1760
1761 # Bug: 21124327
1762 # When generating incrementals for the system and vendor partitions in
1763 # version 4 or newer, explicitly check the first block (which contains
1764 # the superblock) of the partition to see if it's what we expect. If
1765 # this check fails, give an explicit log message about the partition
1766 # having been remounted R/W (the most likely explanation).
1767 if self.check_first_block:
1768 script.AppendExtra('check_first_block("%s");' % (self.device,))
1769
1770 # If version >= 4, try block recovery before abort update
Tianjie Xu209db462016-05-24 17:34:52 -07001771 if partition == "system":
1772 code = ErrorCode.SYSTEM_RECOVER_FAILURE
1773 else:
1774 code = ErrorCode.VENDOR_RECOVER_FAILURE
Tianjie Xufc3422a2015-12-15 11:53:59 -08001775 script.AppendExtra((
1776 'ifelse (block_image_recover("{device}", "{ranges}") && '
1777 'block_image_verify("{device}", '
1778 'package_extract_file("{partition}.transfer.list"), '
1779 '"{partition}.new.dat", "{partition}.patch.dat"), '
1780 'ui_print("{partition} recovered successfully."), '
Tianjie Xu209db462016-05-24 17:34:52 -07001781 'abort("E{code}: {partition} partition fails to recover"));\n'
Tianjie Xufc3422a2015-12-15 11:53:59 -08001782 'endif;').format(device=self.device, ranges=ranges_str,
Tianjie Xu209db462016-05-24 17:34:52 -07001783 partition=partition, code=code))
Doug Zongkerb34fcce2014-09-11 09:34:56 -07001784
Tao Baodd2a5892015-03-12 12:32:37 -07001785 # Abort the OTA update. Note that the incremental OTA cannot be applied
1786 # even if it may match the checksum of the target partition.
1787 # a) If version < 3, operations like move and erase will make changes
1788 # unconditionally and damage the partition.
1789 # b) If version >= 3, it won't even reach here.
Tianjie Xufc3422a2015-12-15 11:53:59 -08001790 else:
Tianjie Xu209db462016-05-24 17:34:52 -07001791 if partition == "system":
1792 code = ErrorCode.SYSTEM_VERIFICATION_FAILURE
1793 else:
1794 code = ErrorCode.VENDOR_VERIFICATION_FAILURE
1795 script.AppendExtra((
1796 'abort("E%d: %s partition has unexpected contents");\n'
1797 'endif;') % (code, partition))
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001798
Tao Bao5fcaaef2015-06-01 13:40:49 -07001799 def _WritePostInstallVerifyScript(self, script):
1800 partition = self.partition
1801 script.Print('Verifying the updated %s image...' % (partition,))
1802 # Unlike pre-install verification, clobbered_blocks should not be ignored.
1803 ranges = self.tgt.care_map
1804 ranges_str = ranges.to_string_raw()
Tao Bao76def242017-11-21 09:25:31 -08001805 script.AppendExtra(
1806 'if range_sha1("%s", "%s") == "%s" then' % (
1807 self.device, ranges_str,
1808 self.tgt.TotalSha1(include_clobbered_blocks=True)))
Tao Baoe9b61912015-07-09 17:37:49 -07001809
1810 # Bug: 20881595
1811 # Verify that extended blocks are really zeroed out.
1812 if self.tgt.extended:
1813 ranges_str = self.tgt.extended.to_string_raw()
Tao Bao76def242017-11-21 09:25:31 -08001814 script.AppendExtra(
1815 'if range_sha1("%s", "%s") == "%s" then' % (
1816 self.device, ranges_str,
1817 self._HashZeroBlocks(self.tgt.extended.size())))
Tao Baoe9b61912015-07-09 17:37:49 -07001818 script.Print('Verified the updated %s image.' % (partition,))
Tianjie Xu209db462016-05-24 17:34:52 -07001819 if partition == "system":
1820 code = ErrorCode.SYSTEM_NONZERO_CONTENTS
1821 else:
1822 code = ErrorCode.VENDOR_NONZERO_CONTENTS
Tao Baoe9b61912015-07-09 17:37:49 -07001823 script.AppendExtra(
1824 'else\n'
Tianjie Xu209db462016-05-24 17:34:52 -07001825 ' abort("E%d: %s partition has unexpected non-zero contents after '
1826 'OTA update");\n'
1827 'endif;' % (code, partition))
Tao Baoe9b61912015-07-09 17:37:49 -07001828 else:
1829 script.Print('Verified the updated %s image.' % (partition,))
1830
Tianjie Xu209db462016-05-24 17:34:52 -07001831 if partition == "system":
1832 code = ErrorCode.SYSTEM_UNEXPECTED_CONTENTS
1833 else:
1834 code = ErrorCode.VENDOR_UNEXPECTED_CONTENTS
1835
Tao Bao5fcaaef2015-06-01 13:40:49 -07001836 script.AppendExtra(
1837 'else\n'
Tianjie Xu209db462016-05-24 17:34:52 -07001838 ' abort("E%d: %s partition has unexpected contents after OTA '
1839 'update");\n'
1840 'endif;' % (code, partition))
Tao Bao5fcaaef2015-06-01 13:40:49 -07001841
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001842 def _WriteUpdate(self, script, output_zip):
Dan Albert8e0178d2015-01-27 15:53:15 -08001843 ZipWrite(output_zip,
1844 '{}.transfer.list'.format(self.path),
1845 '{}.transfer.list'.format(self.partition))
Tianjie Xub0a29ad2017-07-06 15:13:59 -07001846
Tao Bao76def242017-11-21 09:25:31 -08001847 # For full OTA, compress the new.dat with brotli with quality 6 to reduce
1848 # its size. Quailty 9 almost triples the compression time but doesn't
1849 # further reduce the size too much. For a typical 1.8G system.new.dat
Tianjie Xub0a29ad2017-07-06 15:13:59 -07001850 # zip | brotli(quality 6) | brotli(quality 9)
1851 # compressed_size: 942M | 869M (~8% reduced) | 854M
1852 # compression_time: 75s | 265s | 719s
1853 # decompression_time: 15s | 25s | 25s
1854
1855 if not self.src:
Alex Deymob10e07a2017-11-09 23:53:42 +01001856 brotli_cmd = ['brotli', '--quality=6',
1857 '--output={}.new.dat.br'.format(self.path),
1858 '{}.new.dat'.format(self.path)]
Tianjie Xub0a29ad2017-07-06 15:13:59 -07001859 print("Compressing {}.new.dat with brotli".format(self.partition))
Tao Bao80921982018-03-21 21:02:19 -07001860 p = Run(brotli_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
1861 stdoutdata, _ = p.communicate()
1862 assert p.returncode == 0, \
1863 'Failed to compress {}.new.dat with brotli:\n{}'.format(
1864 self.partition, stdoutdata)
Tianjie Xub0a29ad2017-07-06 15:13:59 -07001865
1866 new_data_name = '{}.new.dat.br'.format(self.partition)
1867 ZipWrite(output_zip,
1868 '{}.new.dat.br'.format(self.path),
1869 new_data_name,
1870 compress_type=zipfile.ZIP_STORED)
1871 else:
1872 new_data_name = '{}.new.dat'.format(self.partition)
1873 ZipWrite(output_zip, '{}.new.dat'.format(self.path), new_data_name)
1874
Dan Albert8e0178d2015-01-27 15:53:15 -08001875 ZipWrite(output_zip,
1876 '{}.patch.dat'.format(self.path),
1877 '{}.patch.dat'.format(self.partition),
1878 compress_type=zipfile.ZIP_STORED)
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001879
Tianjie Xu209db462016-05-24 17:34:52 -07001880 if self.partition == "system":
1881 code = ErrorCode.SYSTEM_UPDATE_FAILURE
1882 else:
1883 code = ErrorCode.VENDOR_UPDATE_FAILURE
1884
Dan Albert8e0178d2015-01-27 15:53:15 -08001885 call = ('block_image_update("{device}", '
1886 'package_extract_file("{partition}.transfer.list"), '
Tianjie Xub0a29ad2017-07-06 15:13:59 -07001887 '"{new_data_name}", "{partition}.patch.dat") ||\n'
Tianjie Xu209db462016-05-24 17:34:52 -07001888 ' abort("E{code}: Failed to update {partition} image.");'.format(
Tianjie Xub0a29ad2017-07-06 15:13:59 -07001889 device=self.device, partition=self.partition,
1890 new_data_name=new_data_name, code=code))
Dan Albert8b72aef2015-03-23 19:13:21 -07001891 script.AppendExtra(script.WordWrap(call))
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001892
Dan Albert8b72aef2015-03-23 19:13:21 -07001893 def _HashBlocks(self, source, ranges): # pylint: disable=no-self-use
Sami Tolvanendd67a292014-12-09 16:40:34 +00001894 data = source.ReadRangeSet(ranges)
1895 ctx = sha1()
1896
1897 for p in data:
1898 ctx.update(p)
1899
1900 return ctx.hexdigest()
1901
Tao Baoe9b61912015-07-09 17:37:49 -07001902 def _HashZeroBlocks(self, num_blocks): # pylint: disable=no-self-use
1903 """Return the hash value for all zero blocks."""
1904 zero_block = '\x00' * 4096
1905 ctx = sha1()
1906 for _ in range(num_blocks):
1907 ctx.update(zero_block)
1908
1909 return ctx.hexdigest()
1910
Doug Zongkerab7ca1d2014-08-26 10:40:28 -07001911
1912DataImage = blockimgdiff.DataImage
1913
Tao Bao76def242017-11-21 09:25:31 -08001914
Doug Zongker96a57e72010-09-26 14:57:41 -07001915# map recovery.fstab's fs_types to mount/format "partition types"
Dan Albert8b72aef2015-03-23 19:13:21 -07001916PARTITION_TYPES = {
Dan Albert8b72aef2015-03-23 19:13:21 -07001917 "ext4": "EMMC",
1918 "emmc": "EMMC",
Mohamad Ayyash95e74c12015-05-01 15:39:36 -07001919 "f2fs": "EMMC",
1920 "squashfs": "EMMC"
Dan Albert8b72aef2015-03-23 19:13:21 -07001921}
Doug Zongker96a57e72010-09-26 14:57:41 -07001922
Tao Bao76def242017-11-21 09:25:31 -08001923
Doug Zongker96a57e72010-09-26 14:57:41 -07001924def GetTypeAndDevice(mount_point, info):
1925 fstab = info["fstab"]
1926 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -07001927 return (PARTITION_TYPES[fstab[mount_point].fs_type],
1928 fstab[mount_point].device)
Doug Zongker96a57e72010-09-26 14:57:41 -07001929 else:
Dan Albert8b72aef2015-03-23 19:13:21 -07001930 raise KeyError
Baligh Uddinbeb6afd2013-11-13 00:22:34 +00001931
1932
1933def ParseCertificate(data):
Tao Bao17e4e612018-02-16 17:12:54 -08001934 """Parses and converts a PEM-encoded certificate into DER-encoded.
1935
1936 This gives the same result as `openssl x509 -in <filename> -outform DER`.
1937
1938 Returns:
1939 The decoded certificate string.
1940 """
1941 cert_buffer = []
Baligh Uddinbeb6afd2013-11-13 00:22:34 +00001942 save = False
1943 for line in data.split("\n"):
1944 if "--END CERTIFICATE--" in line:
1945 break
1946 if save:
Tao Bao17e4e612018-02-16 17:12:54 -08001947 cert_buffer.append(line)
Baligh Uddinbeb6afd2013-11-13 00:22:34 +00001948 if "--BEGIN CERTIFICATE--" in line:
1949 save = True
Tao Bao17e4e612018-02-16 17:12:54 -08001950 cert = "".join(cert_buffer).decode('base64')
Baligh Uddinbeb6afd2013-11-13 00:22:34 +00001951 return cert
Doug Zongkerc9253822014-02-04 12:17:58 -08001952
Tao Bao04e1f012018-02-04 12:13:35 -08001953
1954def ExtractPublicKey(cert):
1955 """Extracts the public key (PEM-encoded) from the given certificate file.
1956
1957 Args:
1958 cert: The certificate filename.
1959
1960 Returns:
1961 The public key string.
1962
1963 Raises:
1964 AssertionError: On non-zero return from 'openssl'.
1965 """
1966 # The behavior with '-out' is different between openssl 1.1 and openssl 1.0.
1967 # While openssl 1.1 writes the key into the given filename followed by '-out',
1968 # openssl 1.0 (both of 1.0.1 and 1.0.2) doesn't. So we collect the output from
1969 # stdout instead.
1970 cmd = ['openssl', 'x509', '-pubkey', '-noout', '-in', cert]
1971 proc = Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1972 pubkey, stderrdata = proc.communicate()
1973 assert proc.returncode == 0, \
1974 'Failed to dump public key from certificate: %s\n%s' % (cert, stderrdata)
1975 return pubkey
1976
1977
Doug Zongker412c02f2014-02-13 10:58:24 -08001978def MakeRecoveryPatch(input_dir, output_sink, recovery_img, boot_img,
1979 info_dict=None):
Tao Bao6d5d6232018-03-09 17:04:42 -08001980 """Generates the recovery-from-boot patch and writes the script to output.
Doug Zongkerc9253822014-02-04 12:17:58 -08001981
Tao Bao6d5d6232018-03-09 17:04:42 -08001982 Most of the space in the boot and recovery images is just the kernel, which is
1983 identical for the two, so the resulting patch should be efficient. Add it to
1984 the output zip, along with a shell script that is run from init.rc on first
1985 boot to actually do the patching and install the new recovery image.
1986
1987 Args:
1988 input_dir: The top-level input directory of the target-files.zip.
1989 output_sink: The callback function that writes the result.
1990 recovery_img: File object for the recovery image.
1991 boot_img: File objects for the boot image.
1992 info_dict: A dict returned by common.LoadInfoDict() on the input
1993 target_files. Will use OPTIONS.info_dict if None has been given.
Doug Zongkerc9253822014-02-04 12:17:58 -08001994 """
Doug Zongker412c02f2014-02-13 10:58:24 -08001995 if info_dict is None:
1996 info_dict = OPTIONS.info_dict
1997
Tao Bao6d5d6232018-03-09 17:04:42 -08001998 full_recovery_image = info_dict.get("full_recovery_image") == "true"
Doug Zongkerc9253822014-02-04 12:17:58 -08001999
Tao Baof2cffbd2015-07-22 12:33:18 -07002000 if full_recovery_image:
2001 output_sink("etc/recovery.img", recovery_img.data)
2002
2003 else:
Tao Bao6d5d6232018-03-09 17:04:42 -08002004 system_root_image = info_dict.get("system_root_image") == "true"
Tao Baof2cffbd2015-07-22 12:33:18 -07002005 path = os.path.join(input_dir, "SYSTEM", "etc", "recovery-resource.dat")
Tao Bao6d5d6232018-03-09 17:04:42 -08002006 # With system-root-image, boot and recovery images will have mismatching
2007 # entries (only recovery has the ramdisk entry) (Bug: 72731506). Use bsdiff
2008 # to handle such a case.
2009 if system_root_image:
2010 diff_program = ["bsdiff"]
Tao Baof2cffbd2015-07-22 12:33:18 -07002011 bonus_args = ""
Tao Bao6d5d6232018-03-09 17:04:42 -08002012 assert not os.path.exists(path)
2013 else:
2014 diff_program = ["imgdiff"]
2015 if os.path.exists(path):
2016 diff_program.append("-b")
2017 diff_program.append(path)
Tao Bao4948aed2018-07-13 16:11:16 -07002018 bonus_args = "--bonus /system/etc/recovery-resource.dat"
Tao Bao6d5d6232018-03-09 17:04:42 -08002019 else:
2020 bonus_args = ""
Tao Baof2cffbd2015-07-22 12:33:18 -07002021
2022 d = Difference(recovery_img, boot_img, diff_program=diff_program)
2023 _, _, patch = d.ComputePatch()
2024 output_sink("recovery-from-boot.p", patch)
Doug Zongkerc9253822014-02-04 12:17:58 -08002025
Dan Albertebb19aa2015-03-27 19:11:53 -07002026 try:
Tao Bao6f0b2192015-10-13 16:37:12 -07002027 # The following GetTypeAndDevice()s need to use the path in the target
2028 # info_dict instead of source_info_dict.
Dan Albertebb19aa2015-03-27 19:11:53 -07002029 boot_type, boot_device = GetTypeAndDevice("/boot", info_dict)
2030 recovery_type, recovery_device = GetTypeAndDevice("/recovery", info_dict)
2031 except KeyError:
Ying Wanga961a092014-07-29 11:42:37 -07002032 return
Doug Zongkerc9253822014-02-04 12:17:58 -08002033
Tao Baof2cffbd2015-07-22 12:33:18 -07002034 if full_recovery_image:
2035 sh = """#!/system/bin/sh
Tao Bao4948aed2018-07-13 16:11:16 -07002036if ! applypatch --check %(type)s:%(device)s:%(size)d:%(sha1)s; then
2037 applypatch \\
2038 --flash /system/etc/recovery.img \\
2039 --target %(type)s:%(device)s:%(size)d:%(sha1)s && \\
2040 log -t recovery "Installing new recovery image: succeeded" || \\
2041 log -t recovery "Installing new recovery image: failed"
Tao Baof2cffbd2015-07-22 12:33:18 -07002042else
2043 log -t recovery "Recovery image already installed"
2044fi
2045""" % {'type': recovery_type,
2046 'device': recovery_device,
2047 'sha1': recovery_img.sha1,
2048 'size': recovery_img.size}
2049 else:
2050 sh = """#!/system/bin/sh
Tao Bao4948aed2018-07-13 16:11:16 -07002051if ! applypatch --check %(recovery_type)s:%(recovery_device)s:%(recovery_size)d:%(recovery_sha1)s; then
2052 applypatch %(bonus_args)s \\
2053 --patch /system/recovery-from-boot.p \\
2054 --source %(boot_type)s:%(boot_device)s:%(boot_size)d:%(boot_sha1)s \\
2055 --target %(recovery_type)s:%(recovery_device)s:%(recovery_size)d:%(recovery_sha1)s && \\
2056 log -t recovery "Installing new recovery image: succeeded" || \\
2057 log -t recovery "Installing new recovery image: failed"
Doug Zongkerc9253822014-02-04 12:17:58 -08002058else
2059 log -t recovery "Recovery image already installed"
2060fi
Dan Albert8b72aef2015-03-23 19:13:21 -07002061""" % {'boot_size': boot_img.size,
2062 'boot_sha1': boot_img.sha1,
2063 'recovery_size': recovery_img.size,
2064 'recovery_sha1': recovery_img.sha1,
2065 'boot_type': boot_type,
2066 'boot_device': boot_device,
2067 'recovery_type': recovery_type,
2068 'recovery_device': recovery_device,
2069 'bonus_args': bonus_args}
Doug Zongkerc9253822014-02-04 12:17:58 -08002070
2071 # The install script location moved from /system/etc to /system/bin
Tianjie Xu78de9f12017-06-20 16:52:54 -07002072 # in the L release.
2073 sh_location = "bin/install-recovery.sh"
Tao Bao9f0c8df2015-07-07 18:31:47 -07002074
Tao Bao89fbb0f2017-01-10 10:47:58 -08002075 print("putting script in", sh_location)
Doug Zongkerc9253822014-02-04 12:17:58 -08002076
2077 output_sink(sh_location, sh)