method_count.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #! /usr/bin/env python3
  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. from __future__ import print_function
  6. import argparse
  7. import os
  8. import re
  9. import zipfile
  10. from pylib.dex import dex_parser
  11. class DexStatsCollector:
  12. """Tracks count of method/field/string/type as well as unique methods."""
  13. def __init__(self):
  14. # Signatures of all methods from all seen dex files.
  15. self._unique_methods = set()
  16. # Map of label -> { metric -> count }.
  17. self._counts_by_label = {}
  18. def _CollectFromDexfile(self, label, dexfile):
  19. assert label not in self._counts_by_label, 'exists: ' + label
  20. self._counts_by_label[label] = {
  21. 'fields': dexfile.header.field_ids_size,
  22. 'methods': dexfile.header.method_ids_size,
  23. 'strings': dexfile.header.string_ids_size,
  24. 'types': dexfile.header.type_ids_size,
  25. }
  26. self._unique_methods.update(dexfile.IterMethodSignatureParts())
  27. def CollectFromZip(self, label, path):
  28. """Add dex stats from an .apk/.jar/.aab/.zip."""
  29. with zipfile.ZipFile(path, 'r') as z:
  30. for subpath in z.namelist():
  31. if not re.match(r'.*classes\d*\.dex$', subpath):
  32. continue
  33. dexfile = dex_parser.DexFile(bytearray(z.read(subpath)))
  34. self._CollectFromDexfile('{}!{}'.format(label, subpath), dexfile)
  35. def CollectFromDex(self, label, path):
  36. """Add dex stats from a .dex file."""
  37. with open(path, 'rb') as f:
  38. dexfile = dex_parser.DexFile(bytearray(f.read()))
  39. self._CollectFromDexfile(label, dexfile)
  40. def MergeFrom(self, parent_label, other):
  41. """Add dex stats from another DexStatsCollector."""
  42. # pylint: disable=protected-access
  43. for label, other_counts in other._counts_by_label.items():
  44. new_label = '{}-{}'.format(parent_label, label)
  45. self._counts_by_label[new_label] = other_counts.copy()
  46. self._unique_methods.update(other._unique_methods)
  47. # pylint: enable=protected-access
  48. def GetUniqueMethodCount(self):
  49. """Returns total number of unique methods across encountered dex files."""
  50. return len(self._unique_methods)
  51. def GetCountsByLabel(self):
  52. """Returns dict of label -> {metric -> count}."""
  53. return self._counts_by_label
  54. def GetTotalCounts(self):
  55. """Returns dict of {metric -> count}, where |count| is sum(metric)."""
  56. ret = {}
  57. for metric in ('fields', 'methods', 'strings', 'types'):
  58. ret[metric] = sum(x[metric] for x in self._counts_by_label.values())
  59. return ret
  60. def GetDexCacheSize(self, pre_oreo):
  61. """Returns number of bytes of dirty RAM is consumed from all dex files."""
  62. # Dex Cache was optimized in Android Oreo:
  63. # https://source.android.com/devices/tech/dalvik/improvements#dex-cache-removal
  64. if pre_oreo:
  65. total = sum(self.GetTotalCounts().values())
  66. else:
  67. total = sum(c['methods'] for c in self._counts_by_label.values())
  68. return total * 4 # 4 bytes per entry.
  69. def main():
  70. parser = argparse.ArgumentParser()
  71. parser.add_argument('paths', nargs='+')
  72. args = parser.parse_args()
  73. collector = DexStatsCollector()
  74. for path in args.paths:
  75. if os.path.splitext(path)[1] in ('.zip', '.apk', '.jar', '.aab'):
  76. collector.CollectFromZip(path, path)
  77. else:
  78. collector.CollectFromDex(path, path)
  79. counts_by_label = collector.GetCountsByLabel()
  80. for label, counts in sorted(counts_by_label.items()):
  81. print('{}:'.format(label))
  82. for metric, count in sorted(counts.items()):
  83. print(' {}:'.format(metric), count)
  84. print()
  85. if len(counts_by_label) > 1:
  86. print('Totals:')
  87. for metric, count in sorted(collector.GetTotalCounts().items()):
  88. print(' {}:'.format(metric), count)
  89. print()
  90. print('Unique Methods:', collector.GetUniqueMethodCount())
  91. print('DexCache (Pre-Oreo):', collector.GetDexCacheSize(pre_oreo=True),
  92. 'bytes of dirty memory')
  93. print('DexCache (Oreo+):', collector.GetDexCacheSize(pre_oreo=False),
  94. 'bytes of dirty memory')
  95. if __name__ == '__main__':
  96. main()