Ben Murdoch | 097c5b2 | 2016-05-18 11:27:45 +0100 | [diff] [blame] | 1 | #! /usr/bin/env python |
| 2 | # Copyright 2015 The Chromium Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | import argparse |
| 7 | import os |
| 8 | import re |
| 9 | import shutil |
| 10 | import sys |
| 11 | import tempfile |
| 12 | import zipfile |
| 13 | |
| 14 | import devil_chromium |
| 15 | from devil.android.sdk import dexdump |
| 16 | from pylib.constants import host_paths |
| 17 | |
| 18 | sys.path.append(os.path.join(host_paths.DIR_SOURCE_ROOT, 'build', 'util', 'lib', |
| 19 | 'common')) |
| 20 | import perf_tests_results_helper # pylint: disable=import-error |
| 21 | |
| 22 | |
| 23 | _METHOD_IDS_SIZE_RE = re.compile(r'^method_ids_size +: +(\d+)$') |
| 24 | |
| 25 | def ExtractIfZip(dexfile, tmpdir): |
| 26 | if not os.path.splitext(dexfile)[1] in ('.zip', '.apk', '.jar'): |
| 27 | return [dexfile] |
| 28 | |
| 29 | with zipfile.ZipFile(dexfile, 'r') as z: |
| 30 | dex_files = [n for n in z.namelist() if n.endswith('.dex')] |
| 31 | z.extractall(tmpdir, dex_files) |
| 32 | |
| 33 | return [os.path.join(tmpdir, f) for f in dex_files] |
| 34 | |
| 35 | def SingleMethodCount(dexfile): |
| 36 | for line in dexdump.DexDump(dexfile, file_summary=True): |
| 37 | m = _METHOD_IDS_SIZE_RE.match(line) |
| 38 | if m: |
| 39 | return m.group(1) |
| 40 | raise Exception('"method_ids_size" not found in dex dump of %s' % dexfile) |
| 41 | |
| 42 | def MethodCount(dexfile): |
| 43 | tmpdir = tempfile.mkdtemp(suffix='_dex_extract') |
| 44 | multidex_file_list = ExtractIfZip(dexfile, tmpdir) |
| 45 | try: |
| 46 | return sum(int(SingleMethodCount(d)) for d in multidex_file_list) |
| 47 | finally: |
| 48 | shutil.rmtree(tmpdir) |
| 49 | |
| 50 | def main(): |
| 51 | parser = argparse.ArgumentParser() |
| 52 | parser.add_argument( |
| 53 | '--apk-name', help='Name of the APK to which the dexfile corresponds.') |
| 54 | parser.add_argument('dexfile') |
| 55 | |
| 56 | args = parser.parse_args() |
| 57 | |
| 58 | devil_chromium.Initialize() |
| 59 | |
| 60 | if not args.apk_name: |
| 61 | dirname, basename = os.path.split(args.dexfile) |
| 62 | while basename: |
| 63 | if 'apk' in basename: |
| 64 | args.apk_name = basename |
| 65 | break |
| 66 | dirname, basename = os.path.split(dirname) |
| 67 | else: |
| 68 | parser.error( |
| 69 | 'Unable to determine apk name from %s, ' |
| 70 | 'and --apk-name was not provided.' % args.dexfile) |
| 71 | |
| 72 | method_count = MethodCount(args.dexfile) |
| 73 | perf_tests_results_helper.PrintPerfResult( |
| 74 | '%s_methods' % args.apk_name, 'total', [method_count], 'methods') |
| 75 | return 0 |
| 76 | |
| 77 | if __name__ == '__main__': |
| 78 | sys.exit(main()) |
| 79 | |