1#!/usr/bin/env python 2# 3# Copyright (C) 2019 The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17import logging 18import os.path 19import re 20import shlex 21import shutil 22import zipfile 23 24import apex_manifest 25import common 26from common import UnzipTemp, RunAndCheckOutput, MakeTempFile, OPTIONS 27 28import ota_metadata_pb2 29 30 31logger = logging.getLogger(__name__) 32 33OPTIONS = common.OPTIONS 34 35APEX_PAYLOAD_IMAGE = 'apex_payload.img' 36 37APEX_PUBKEY = 'apex_pubkey' 38 39 40class ApexInfoError(Exception): 41 """An Exception raised during Apex Information command.""" 42 43 def __init__(self, message): 44 Exception.__init__(self, message) 45 46 47class ApexSigningError(Exception): 48 """An Exception raised during Apex Payload signing.""" 49 50 def __init__(self, message): 51 Exception.__init__(self, message) 52 53 54class ApexApkSigner(object): 55 """Class to sign the apk files and other files in an apex payload image and repack the apex""" 56 57 def __init__(self, apex_path, key_passwords, codename_to_api_level_map, avbtool=None, sign_tool=None): 58 self.apex_path = apex_path 59 if not key_passwords: 60 self.key_passwords = dict() 61 else: 62 self.key_passwords = key_passwords 63 self.codename_to_api_level_map = codename_to_api_level_map 64 self.debugfs_path = os.path.join( 65 OPTIONS.search_path, "bin", "debugfs_static") 66 self.fsckerofs_path = os.path.join( 67 OPTIONS.search_path, "bin", "fsck.erofs") 68 self.blkid_path = os.path.join( 69 OPTIONS.search_path, "bin", "blkid_static") 70 self.avbtool = avbtool if avbtool else "avbtool" 71 self.sign_tool = sign_tool 72 73 def ProcessApexFile(self, apk_keys, payload_key, signing_args=None, is_sepolicy=False): 74 """Scans and signs the payload files and repack the apex 75 76 Args: 77 apk_keys: A dict that holds the signing keys for apk files. 78 79 Returns: 80 The repacked apex file containing the signed apk files. 81 """ 82 if not os.path.exists(self.debugfs_path): 83 raise ApexSigningError( 84 "Couldn't find location of debugfs_static: " + 85 "Path {} does not exist. ".format(self.debugfs_path) + 86 "Make sure bin/debugfs_static can be found in -p <path>") 87 list_cmd = ['deapexer', '--debugfs_path', self.debugfs_path, 88 'list', self.apex_path] 89 entries_names = common.RunAndCheckOutput(list_cmd).split() 90 apk_entries = [name for name in entries_names if name.endswith('.apk')] 91 sepolicy_entries = [] 92 if is_sepolicy: 93 sepolicy_entries = [name for name in entries_names if 94 name.startswith('./etc/SEPolicy') and name.endswith('.zip')] 95 96 # No need to sign and repack, return the original apex path. 97 if not apk_entries and not sepolicy_entries and self.sign_tool is None: 98 logger.info('No apk file to sign in %s', self.apex_path) 99 return self.apex_path 100 101 for entry in apk_entries: 102 apk_name = os.path.basename(entry) 103 if apk_name not in apk_keys: 104 raise ApexSigningError('Failed to find signing keys for apk file {} in' 105 ' apex {}. Use "-e <apkname>=" to specify a key' 106 .format(entry, self.apex_path)) 107 if not any(dirname in entry for dirname in ['app/', 'priv-app/', 108 'overlay/']): 109 logger.warning('Apk path does not contain the intended directory name:' 110 ' %s', entry) 111 112 payload_dir, has_signed_content = self.ExtractApexPayloadAndSignContents( 113 apk_entries, sepolicy_entries, apk_keys, payload_key, signing_args) 114 if not has_signed_content: 115 logger.info('No contents have been signed in %s', self.apex_path) 116 return self.apex_path 117 118 return self.RepackApexPayload(payload_dir, payload_key, signing_args) 119 120 def ExtractApexPayloadAndSignContents(self, apk_entries, sepolicy_entries, apk_keys, payload_key, signing_args): 121 """Extracts the payload image and signs the containing apk files.""" 122 if not os.path.exists(self.debugfs_path): 123 raise ApexSigningError( 124 "Couldn't find location of debugfs_static: " + 125 "Path {} does not exist. ".format(self.debugfs_path) + 126 "Make sure bin/debugfs_static can be found in -p <path>") 127 if not os.path.exists(self.fsckerofs_path): 128 raise ApexSigningError( 129 "Couldn't find location of fsck.erofs: " + 130 "Path {} does not exist. ".format(self.fsckerofs_path) + 131 "Make sure bin/fsck.erofs can be found in -p <path>") 132 if not os.path.exists(self.blkid_path): 133 raise ApexSigningError( 134 "Couldn't find location of blkid: " + 135 "Path {} does not exist. ".format(self.blkid_path) + 136 "Make sure bin/blkid can be found in -p <path>") 137 payload_dir = common.MakeTempDir() 138 extract_cmd = ['deapexer', '--debugfs_path', self.debugfs_path, 139 '--fsckerofs_path', self.fsckerofs_path, 140 '--blkid_path', self.blkid_path, 'extract', 141 self.apex_path, payload_dir] 142 common.RunAndCheckOutput(extract_cmd) 143 assert os.path.exists(self.apex_path) 144 145 has_signed_content = False 146 for entry in apk_entries: 147 apk_path = os.path.join(payload_dir, entry) 148 149 key_name = apk_keys.get(os.path.basename(entry)) 150 if key_name in common.SPECIAL_CERT_STRINGS: 151 logger.info('Not signing: %s due to special cert string', apk_path) 152 continue 153 154 logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path) 155 # Rename the unsigned apk and overwrite the original apk path with the 156 # signed apk file. 157 unsigned_apk = common.MakeTempFile() 158 os.rename(apk_path, unsigned_apk) 159 common.SignFile( 160 unsigned_apk, apk_path, key_name, self.key_passwords.get(key_name), 161 codename_to_api_level_map=self.codename_to_api_level_map) 162 has_signed_content = True 163 164 for entry in sepolicy_entries: 165 sepolicy_path = os.path.join(payload_dir, entry) 166 167 if not 'etc' in entry: 168 logger.warning('Sepolicy path does not contain the intended directory name etc:' 169 ' %s', entry) 170 171 key_name = apk_keys.get(os.path.basename(entry)) 172 if key_name is None: 173 logger.warning('Failed to find signing keys for {} in' 174 ' apex {}, payload key will be used instead.' 175 ' Use "-e <name>=" to specify a key' 176 .format(entry, self.apex_path)) 177 key_name = payload_key 178 179 if key_name in common.SPECIAL_CERT_STRINGS: 180 logger.info('Not signing: %s due to special cert string', sepolicy_path) 181 continue 182 183 if OPTIONS.sign_sepolicy_path is not None: 184 sig_path = os.path.join(payload_dir, sepolicy_path + '.sig') 185 fsv_sig_path = os.path.join(payload_dir, sepolicy_path + '.fsv_sig') 186 old_sig = common.MakeTempFile() 187 old_fsv_sig = common.MakeTempFile() 188 os.rename(sig_path, old_sig) 189 os.rename(fsv_sig_path, old_fsv_sig) 190 191 logger.info('Signing sepolicy file %s in apex %s', sepolicy_path, self.apex_path) 192 if common.SignSePolicy(sepolicy_path, key_name, self.key_passwords.get(key_name)): 193 has_signed_content = True 194 195 if self.sign_tool: 196 logger.info('Signing payload contents in apex %s with %s', self.apex_path, self.sign_tool) 197 # Pass avbtool to the custom signing tool 198 cmd = [self.sign_tool, '--avbtool', self.avbtool] 199 # Pass signing_args verbatim which will be forwarded to avbtool (e.g. --signing_helper=...) 200 if signing_args: 201 cmd.extend(['--signing_args', '"{}"'.format(signing_args)]) 202 cmd.extend([payload_key, payload_dir]) 203 common.RunAndCheckOutput(cmd) 204 has_signed_content = True 205 206 return payload_dir, has_signed_content 207 208 def RepackApexPayload(self, payload_dir, payload_key, signing_args=None): 209 """Rebuilds the apex file with the updated payload directory.""" 210 apex_dir = common.MakeTempDir() 211 # Extract the apex file and reuse its meta files as repack parameters. 212 common.UnzipToDir(self.apex_path, apex_dir) 213 arguments_dict = { 214 'manifest': os.path.join(apex_dir, 'apex_manifest.pb'), 215 'build_info': os.path.join(apex_dir, 'apex_build_info.pb'), 216 'key': payload_key, 217 } 218 for filename in arguments_dict.values(): 219 assert os.path.exists(filename), 'file {} not found'.format(filename) 220 221 # The repack process will add back these files later in the payload image. 222 for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']: 223 path = os.path.join(payload_dir, name) 224 if os.path.isfile(path): 225 os.remove(path) 226 elif os.path.isdir(path): 227 shutil.rmtree(path, ignore_errors=True) 228 229 # TODO(xunchang) the signing process can be improved by using 230 # '--unsigned_payload_only'. But we need to parse the vbmeta earlier for 231 # the signing arguments, e.g. algorithm, salt, etc. 232 payload_img = os.path.join(apex_dir, APEX_PAYLOAD_IMAGE) 233 generate_image_cmd = ['apexer', '--force', '--payload_only', 234 '--do_not_check_keyname', '--apexer_tool_path', 235 os.getenv('PATH')] 236 for key, val in arguments_dict.items(): 237 generate_image_cmd.extend(['--' + key, val]) 238 239 # Add quote to the signing_args as we will pass 240 # --signing_args "--signing_helper_with_files=%path" to apexer 241 if signing_args: 242 generate_image_cmd.extend( 243 ['--signing_args', '"{}"'.format(signing_args)]) 244 245 # optional arguments for apex repacking 246 manifest_json = os.path.join(apex_dir, 'apex_manifest.json') 247 if os.path.exists(manifest_json): 248 generate_image_cmd.extend(['--manifest_json', manifest_json]) 249 generate_image_cmd.extend([payload_dir, payload_img]) 250 if OPTIONS.verbose: 251 generate_image_cmd.append('-v') 252 common.RunAndCheckOutput(generate_image_cmd) 253 254 # Add the payload image back to the apex file. 255 common.ZipDelete(self.apex_path, APEX_PAYLOAD_IMAGE) 256 with zipfile.ZipFile(self.apex_path, 'a', allowZip64=True) as output_apex: 257 common.ZipWrite(output_apex, payload_img, APEX_PAYLOAD_IMAGE, 258 compress_type=zipfile.ZIP_STORED) 259 return self.apex_path 260 261 262def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name, 263 algorithm, salt, hash_algorithm, no_hashtree, signing_args=None): 264 """Signs a given payload_file with the payload key.""" 265 # Add the new footer. Old footer, if any, will be replaced by avbtool. 266 cmd = [avbtool, 'add_hashtree_footer', 267 '--do_not_generate_fec', 268 '--algorithm', algorithm, 269 '--key', payload_key_path, 270 '--prop', 'apex.key:{}'.format(payload_key_name), 271 '--image', payload_file, 272 '--salt', salt, 273 '--hash_algorithm', hash_algorithm] 274 if no_hashtree: 275 cmd.append('--no_hashtree') 276 if signing_args: 277 cmd.extend(shlex.split(signing_args)) 278 279 try: 280 common.RunAndCheckOutput(cmd) 281 except common.ExternalError as e: 282 raise ApexSigningError( 283 'Failed to sign APEX payload {} with {}:\n{}'.format( 284 payload_file, payload_key_path, e)) 285 286 # Verify the signed payload image with specified public key. 287 logger.info('Verifying %s', payload_file) 288 VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree) 289 290 291def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False): 292 """Verifies the APEX payload signature with the given key.""" 293 cmd = [avbtool, 'verify_image', '--image', payload_file, 294 '--key', payload_key] 295 if no_hashtree: 296 cmd.append('--accept_zeroed_hashtree') 297 try: 298 common.RunAndCheckOutput(cmd) 299 except common.ExternalError as e: 300 raise ApexSigningError( 301 'Failed to validate payload signing for {} with {}:\n{}'.format( 302 payload_file, payload_key, e)) 303 304 305def ParseApexPayloadInfo(avbtool, payload_path): 306 """Parses the APEX payload info. 307 308 Args: 309 avbtool: The AVB tool to use. 310 payload_path: The path to the payload image. 311 312 Raises: 313 ApexInfoError on parsing errors. 314 315 Returns: 316 A dict that contains payload property-value pairs. The dict should at least 317 contain Algorithm, Salt, Tree Size and apex.key. 318 """ 319 if not os.path.exists(payload_path): 320 raise ApexInfoError('Failed to find image: {}'.format(payload_path)) 321 322 cmd = [avbtool, 'info_image', '--image', payload_path] 323 try: 324 output = common.RunAndCheckOutput(cmd) 325 except common.ExternalError as e: 326 raise ApexInfoError( 327 'Failed to get APEX payload info for {}:\n{}'.format( 328 payload_path, e)) 329 330 # Extract the Algorithm / Hash Algorithm / Salt / Prop info / Tree size from 331 # payload (i.e. an image signed with avbtool). For example, 332 # Algorithm: SHA256_RSA4096 333 PAYLOAD_INFO_PATTERN = ( 334 r'^\s*(?P<key>Algorithm|Hash Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$') 335 payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN) 336 337 payload_info = {} 338 for line in output.split('\n'): 339 line_info = payload_info_matcher.match(line) 340 if not line_info: 341 continue 342 343 key, value = line_info.group('key'), line_info.group('value') 344 345 if key == 'Prop': 346 # Further extract the property key-value pair, from a 'Prop:' line. For 347 # example, 348 # Prop: apex.key -> 'com.android.runtime' 349 # Note that avbtool writes single or double quotes around values. 350 PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$' 351 352 prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN) 353 prop = prop_matcher.match(value) 354 if not prop: 355 raise ApexInfoError( 356 'Failed to parse prop string {}'.format(value)) 357 358 prop_key, prop_value = prop.group('key'), prop.group('value') 359 if prop_key == 'apex.key': 360 # avbtool dumps the prop value with repr(), which contains single / 361 # double quotes that we don't want. 362 payload_info[prop_key] = prop_value.strip('\"\'') 363 364 else: 365 payload_info[key] = value 366 367 # Validation check. 368 for key in ('Algorithm', 'Salt', 'apex.key', 'Hash Algorithm'): 369 if key not in payload_info: 370 raise ApexInfoError( 371 'Failed to find {} prop in {}'.format(key, payload_path)) 372 373 return payload_info 374 375 376def SignUncompressedApex(avbtool, apex_file, payload_key, container_key, 377 container_pw, apk_keys, codename_to_api_level_map, 378 no_hashtree, signing_args=None, sign_tool=None, 379 is_sepolicy=False): 380 """Signs the current uncompressed APEX with the given payload/container keys. 381 382 Args: 383 apex_file: Uncompressed APEX file. 384 payload_key: The path to payload signing key (w/ extension). 385 container_key: The path to container signing key (w/o extension). 386 container_pw: The matching password of the container_key, or None. 387 apk_keys: A dict that holds the signing keys for apk files. 388 codename_to_api_level_map: A dict that maps from codename to API level. 389 no_hashtree: Don't include hashtree in the signed APEX. 390 signing_args: Additional args to be passed to the payload signer. 391 sign_tool: A tool to sign the contents of the APEX. 392 is_sepolicy: Indicates if the apex is a sepolicy.apex 393 394 Returns: 395 The path to the signed APEX file. 396 """ 397 # 1. Extract the apex payload image and sign the files (e.g. APKs). Repack 398 # the apex file after signing. 399 apk_signer = ApexApkSigner(apex_file, container_pw, 400 codename_to_api_level_map, 401 avbtool, sign_tool) 402 apex_file = apk_signer.ProcessApexFile( 403 apk_keys, payload_key, signing_args, is_sepolicy) 404 405 # 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given 406 # payload_key. 407 payload_dir = common.MakeTempDir(prefix='apex-payload-') 408 with zipfile.ZipFile(apex_file) as apex_fd: 409 payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir) 410 zip_items = apex_fd.namelist() 411 412 payload_info = ParseApexPayloadInfo(avbtool, payload_file) 413 if no_hashtree is None: 414 no_hashtree = payload_info.get("Tree Size", 0) == 0 415 SignApexPayload( 416 avbtool, 417 payload_file, 418 payload_key, 419 payload_info['apex.key'], 420 payload_info['Algorithm'], 421 payload_info['Salt'], 422 payload_info['Hash Algorithm'], 423 no_hashtree, 424 signing_args) 425 426 # 2b. Update the embedded payload public key. 427 payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key) 428 common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE) 429 if APEX_PUBKEY in zip_items: 430 common.ZipDelete(apex_file, APEX_PUBKEY) 431 apex_zip = zipfile.ZipFile(apex_file, 'a', allowZip64=True) 432 common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE) 433 common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY) 434 common.ZipClose(apex_zip) 435 436 # 3. Sign the APEX container with container_key. 437 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex') 438 439 # Specify the 4K alignment when calling SignApk. 440 extra_signapk_args = OPTIONS.extra_signapk_args[:] 441 extra_signapk_args.extend(['-a', '4096', '--align-file-size']) 442 443 password = container_pw.get(container_key) if container_pw else None 444 common.SignFile( 445 apex_file, 446 signed_apex, 447 container_key, 448 password, 449 codename_to_api_level_map=codename_to_api_level_map, 450 extra_signapk_args=extra_signapk_args) 451 452 return signed_apex 453 454 455def SignCompressedApex(avbtool, apex_file, payload_key, container_key, 456 container_pw, apk_keys, codename_to_api_level_map, 457 no_hashtree, signing_args=None, sign_tool=None, 458 is_sepolicy=False): 459 """Signs the current compressed APEX with the given payload/container keys. 460 461 Args: 462 apex_file: Raw uncompressed APEX data. 463 payload_key: The path to payload signing key (w/ extension). 464 container_key: The path to container signing key (w/o extension). 465 container_pw: The matching password of the container_key, or None. 466 apk_keys: A dict that holds the signing keys for apk files. 467 codename_to_api_level_map: A dict that maps from codename to API level. 468 no_hashtree: Don't include hashtree in the signed APEX. 469 signing_args: Additional args to be passed to the payload signer. 470 is_sepolicy: Indicates if the apex is a sepolicy.apex 471 472 Returns: 473 The path to the signed APEX file. 474 """ 475 debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static') 476 477 # 1. Decompress original_apex inside compressed apex. 478 original_apex_file = common.MakeTempFile(prefix='original-apex-', 479 suffix='.apex') 480 # Decompression target path should not exist 481 os.remove(original_apex_file) 482 common.RunAndCheckOutput(['deapexer', '--debugfs_path', debugfs_path, 483 'decompress', '--input', apex_file, 484 '--output', original_apex_file]) 485 486 # 2. Sign original_apex 487 signed_original_apex_file = SignUncompressedApex( 488 avbtool, 489 original_apex_file, 490 payload_key, 491 container_key, 492 container_pw, 493 apk_keys, 494 codename_to_api_level_map, 495 no_hashtree, 496 signing_args, 497 sign_tool, 498 is_sepolicy) 499 500 # 3. Compress signed original apex. 501 compressed_apex_file = common.MakeTempFile(prefix='apex-container-', 502 suffix='.capex') 503 common.RunAndCheckOutput(['apex_compression_tool', 504 'compress', 505 '--apex_compression_tool_path', os.getenv('PATH'), 506 '--input', signed_original_apex_file, 507 '--output', compressed_apex_file]) 508 509 # 4. Sign the APEX container with container_key. 510 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.capex') 511 512 password = container_pw.get(container_key) if container_pw else None 513 common.SignFile( 514 compressed_apex_file, 515 signed_apex, 516 container_key, 517 password, 518 codename_to_api_level_map=codename_to_api_level_map, 519 extra_signapk_args=OPTIONS.extra_signapk_args) 520 521 return signed_apex 522 523 524def SignApex(avbtool, apex_data, payload_key, container_key, container_pw, 525 apk_keys, codename_to_api_level_map, no_hashtree, 526 signing_args=None, sign_tool=None, is_sepolicy=False): 527 """Signs the current APEX with the given payload/container keys. 528 529 Args: 530 apex_file: Path to apex file path. 531 payload_key: The path to payload signing key (w/ extension). 532 container_key: The path to container signing key (w/o extension). 533 container_pw: The matching password of the container_key, or None. 534 apk_keys: A dict that holds the signing keys for apk files. 535 codename_to_api_level_map: A dict that maps from codename to API level. 536 no_hashtree: Don't include hashtree in the signed APEX. 537 signing_args: Additional args to be passed to the payload signer. 538 is_sepolicy: Indicates if the apex is a sepolicy.apex 539 540 Returns: 541 The path to the signed APEX file. 542 """ 543 apex_file = common.MakeTempFile(prefix='apex-container-', suffix='.apex') 544 with open(apex_file, 'wb') as output_fp: 545 output_fp.write(apex_data) 546 547 debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static') 548 cmd = ['deapexer', '--debugfs_path', debugfs_path, 549 'info', '--print-type', apex_file] 550 551 try: 552 apex_type = common.RunAndCheckOutput(cmd).strip() 553 if apex_type == 'UNCOMPRESSED': 554 return SignUncompressedApex( 555 avbtool, 556 apex_file, 557 payload_key=payload_key, 558 container_key=container_key, 559 container_pw=container_pw, 560 codename_to_api_level_map=codename_to_api_level_map, 561 no_hashtree=no_hashtree, 562 apk_keys=apk_keys, 563 signing_args=signing_args, 564 sign_tool=sign_tool, 565 is_sepolicy=is_sepolicy) 566 elif apex_type == 'COMPRESSED': 567 return SignCompressedApex( 568 avbtool, 569 apex_file, 570 payload_key=payload_key, 571 container_key=container_key, 572 container_pw=container_pw, 573 codename_to_api_level_map=codename_to_api_level_map, 574 no_hashtree=no_hashtree, 575 apk_keys=apk_keys, 576 signing_args=signing_args, 577 sign_tool=sign_tool, 578 is_sepolicy=is_sepolicy) 579 else: 580 # TODO(b/172912232): support signing compressed apex 581 raise ApexInfoError('Unsupported apex type {}'.format(apex_type)) 582 583 except common.ExternalError as e: 584 raise ApexInfoError( 585 'Failed to get type for {}:\n{}'.format(apex_file, e)) 586 587 588def GetApexInfoFromTargetFiles(input_file, partition, compressed_only=True): 589 """ 590 Get information about system APEX stored in the input_file zip 591 592 Args: 593 input_file: The filename of the target build target-files zip or directory. 594 595 Return: 596 A list of ota_metadata_pb2.ApexInfo() populated using the APEX stored in 597 /system partition of the input_file 598 """ 599 600 # Extract the apex files so that we can run checks on them 601 if not isinstance(input_file, str): 602 raise RuntimeError("must pass filepath to target-files zip or directory") 603 604 apex_subdir = os.path.join(partition.upper(), 'apex') 605 if os.path.isdir(input_file): 606 tmp_dir = input_file 607 else: 608 tmp_dir = UnzipTemp(input_file, [os.path.join(apex_subdir, '*')]) 609 target_dir = os.path.join(tmp_dir, apex_subdir) 610 611 # Partial target-files packages for vendor-only builds may not contain 612 # a system apex directory. 613 if not os.path.exists(target_dir): 614 logger.info('No APEX directory at path: %s', target_dir) 615 return [] 616 617 apex_infos = [] 618 619 debugfs_path = "debugfs" 620 if OPTIONS.search_path: 621 debugfs_path = os.path.join(OPTIONS.search_path, "bin", "debugfs_static") 622 623 deapexer = 'deapexer' 624 if OPTIONS.search_path: 625 deapexer_path = os.path.join(OPTIONS.search_path, "bin", "deapexer") 626 if os.path.isfile(deapexer_path): 627 deapexer = deapexer_path 628 629 for apex_filename in sorted(os.listdir(target_dir)): 630 apex_filepath = os.path.join(target_dir, apex_filename) 631 if not os.path.isfile(apex_filepath) or \ 632 not zipfile.is_zipfile(apex_filepath): 633 logger.info("Skipping %s because it's not a zipfile", apex_filepath) 634 continue 635 apex_info = ota_metadata_pb2.ApexInfo() 636 # Open the apex file to retrieve information 637 manifest = apex_manifest.fromApex(apex_filepath) 638 apex_info.package_name = manifest.name 639 apex_info.version = manifest.version 640 # Check if the file is compressed or not 641 apex_type = RunAndCheckOutput([ 642 deapexer, "--debugfs_path", debugfs_path, 643 'info', '--print-type', apex_filepath]).rstrip() 644 if apex_type == 'COMPRESSED': 645 apex_info.is_compressed = True 646 elif apex_type == 'UNCOMPRESSED': 647 apex_info.is_compressed = False 648 else: 649 raise RuntimeError('Not an APEX file: ' + apex_type) 650 651 # Decompress compressed APEX to determine its size 652 if apex_info.is_compressed: 653 decompressed_file_path = MakeTempFile(prefix="decompressed-", 654 suffix=".apex") 655 # Decompression target path should not exist 656 os.remove(decompressed_file_path) 657 RunAndCheckOutput([deapexer, 'decompress', '--input', apex_filepath, 658 '--output', decompressed_file_path]) 659 apex_info.decompressed_size = os.path.getsize(decompressed_file_path) 660 661 if not compressed_only or apex_info.is_compressed: 662 apex_infos.append(apex_info) 663 664 return apex_infos 665