tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

optimize_resources.py (5200B)


      1 #!/usr/bin/env python3
      2 #
      3 # Copyright 2021 The Chromium Authors
      4 # Use of this source code is governed by a BSD-style license that can be
      5 # found in the LICENSE file.
      6 
      7 import argparse
      8 import logging
      9 import os
     10 import sys
     11 
     12 from util import build_utils
     13 import action_helpers  # build_utils adds //build to sys.path.
     14 
     15 
     16 def _ParseArgs(args):
     17  """Parses command line options.
     18 
     19  Returns:
     20    An options object as from argparse.ArgumentParser.parse_args()
     21  """
     22  parser = argparse.ArgumentParser()
     23  parser.add_argument('--aapt2-path',
     24                      required=True,
     25                      help='Path to the Android aapt2 tool.')
     26  parser.add_argument(
     27      '--short-resource-paths',
     28      action='store_true',
     29      help='Whether to shorten resource paths inside the apk or module.')
     30  parser.add_argument(
     31      '--strip-resource-names',
     32      action='store_true',
     33      help='Whether to strip resource names from the resource table of the apk '
     34      'or module.')
     35  parser.add_argument('--input-path',
     36                      required=True,
     37                      help='Input resources APK.')
     38  parser.add_argument('--resources-config-paths',
     39                      default='[]',
     40                      help='GN list of paths to aapt2 resources config files.')
     41  parser.add_argument('--r-text-in',
     42                      required=True,
     43                      help='Path to R.txt. Used to exclude id/ resources.')
     44  parser.add_argument(
     45      '--resources-path-map-out-path',
     46      help='Path to file produced by aapt2 that maps original resource paths '
     47      'to shortened resource paths inside the apk or module.')
     48  parser.add_argument('--optimized-output-path',
     49                      required=True,
     50                      help='Output for `aapt2 optimize`.')
     51  options = parser.parse_args(args)
     52 
     53  options.resources_config_paths = action_helpers.parse_gn_list(
     54      options.resources_config_paths)
     55 
     56  if options.resources_path_map_out_path and not options.short_resource_paths:
     57    parser.error(
     58        '--resources-path-map-out-path requires --short-resource-paths')
     59  return options
     60 
     61 
     62 def _CombineResourceConfigs(resources_config_paths, out_config_path):
     63  with open(out_config_path, 'w') as out_config:
     64    for config_path in resources_config_paths:
     65      with open(config_path) as config:
     66        out_config.write(config.read())
     67        out_config.write('\n')
     68 
     69 
     70 def _ExtractNonCollapsableResources(rtxt_path):
     71  """Extract resources that should not be collapsed from the R.txt file
     72 
     73  Resources of type ID are references to UI elements/views. They are used by
     74  UI automation testing frameworks. They are kept in so that they don't break
     75  tests, even though they may not actually be used during runtime. See
     76  https://crbug.com/900993
     77  App icons (aka mipmaps) are sometimes referenced by other apps by name so must
     78  be keps as well. See https://b/161564466
     79 
     80  Args:
     81    rtxt_path: Path to R.txt file with all the resources
     82  Returns:
     83    List of resources in the form of <resource_type>/<resource_name>
     84  """
     85  resources = []
     86  _NO_COLLAPSE_TYPES = ['id', 'mipmap']
     87  with open(rtxt_path) as rtxt:
     88    for line in rtxt:
     89      for resource_type in _NO_COLLAPSE_TYPES:
     90        if ' {} '.format(resource_type) in line:
     91          resource_name = line.split()[2]
     92          resources.append('{}/{}'.format(resource_type, resource_name))
     93  return resources
     94 
     95 
     96 def _OptimizeApk(output, options, temp_dir, unoptimized_path, r_txt_path):
     97  """Optimize intermediate .ap_ file with aapt2.
     98 
     99  Args:
    100    output: Path to write to.
    101    options: The command-line options.
    102    temp_dir: A temporary directory.
    103    unoptimized_path: path of the apk to optimize.
    104    r_txt_path: path to the R.txt file of the unoptimized apk.
    105  """
    106  optimize_command = [
    107      options.aapt2_path,
    108      'optimize',
    109      unoptimized_path,
    110      '-o',
    111      output,
    112  ]
    113 
    114  # Optimize the resources.pb file by obfuscating resource names and only
    115  # allow usage via R.java constant.
    116  if options.strip_resource_names:
    117    no_collapse_resources = _ExtractNonCollapsableResources(r_txt_path)
    118    gen_config_path = os.path.join(temp_dir, 'aapt2.config')
    119    if options.resources_config_paths:
    120      _CombineResourceConfigs(options.resources_config_paths, gen_config_path)
    121    with open(gen_config_path, 'a') as config:
    122      for resource in no_collapse_resources:
    123        config.write('{}#no_collapse\n'.format(resource))
    124 
    125    optimize_command += [
    126        '--collapse-resource-names',
    127        '--resources-config-path',
    128        gen_config_path,
    129    ]
    130 
    131  if options.short_resource_paths:
    132    optimize_command += ['--shorten-resource-paths']
    133  if options.resources_path_map_out_path:
    134    optimize_command += [
    135        '--resource-path-shortening-map', options.resources_path_map_out_path
    136    ]
    137 
    138  logging.debug('Running aapt2 optimize')
    139  build_utils.CheckOutput(optimize_command,
    140                          print_stdout=False,
    141                          print_stderr=False)
    142 
    143 
    144 def main(args):
    145  options = _ParseArgs(args)
    146  with build_utils.TempDir() as temp_dir:
    147    _OptimizeApk(options.optimized_output_path, options, temp_dir,
    148                 options.input_path, options.r_text_in)
    149 
    150 
    151 if __name__ == '__main__':
    152  main(sys.argv[1:])