Factorize out print-dexsegments to utils, enable for other scripts:

Enable for run_on_app and run_proguard_dx_on_gmscore.

Bug:
Change-Id: I7dfe7272c42e9bc879032b44612daa404b64d266
diff --git a/tools/run_on_app.py b/tools/run_on_app.py
index d7db7fb..a091e1c 100755
--- a/tools/run_on_app.py
+++ b/tools/run_on_app.py
@@ -4,6 +4,7 @@
 # BSD-style license that can be found in the LICENSE file.
 
 from __future__ import print_function
+from glob import glob
 import optparse
 import os
 import sys
@@ -74,14 +75,18 @@
                     'the run.')
   result.add_option('--print-runtimeraw',
                     metavar='BENCHMARKNAME',
-                    help='Prints the line \'<BENCHMARKNAME>(RunTimeRaw):' +
-                         ' <elapsed> ms\' at the end where <elapsed> is' +
-                         ' the elapsed time in milliseconds.')
+                    help='Print the line \'<BENCHMARKNAME>(RunTimeRaw):' +
+                        ' <elapsed> ms\' at the end where <elapsed> is' +
+                        ' the elapsed time in milliseconds.')
   result.add_option('--print-memoryuse',
                     metavar='BENCHMARKNAME',
-                    help='Prints the line \'<BENCHMARKNAME>(MemoryUse):' +
-                         ' <mem>\' at the end where <mem> is the peak' +
-                         ' peak resident set size (VmHWM) in bytes.')
+                    help='Print the line \'<BENCHMARKNAME>(MemoryUse):' +
+                        ' <mem>\' at the end where <mem> is the peak' +
+                        ' peak resident set size (VmHWM) in bytes.')
+  result.add_option('--print-dexsegments',
+                    metavar='BENCHMARKNAME',
+                    help='Print the sizes of individual dex segments as ' +
+                        '\'<BENCHMARKNAME>-<segment>(CodeSize): <bytes>\'')
   return result.parse_args()
 
 # Most apps have the -printmapping and -printseeds in the Proguard
@@ -207,5 +212,9 @@
     print('{}(RunTimeRaw): {} ms'
         .format(options.print_runtimeraw, 1000.0 * (time.time() - t0)))
 
+  if options.print_dexsegments:
+    dex_files = glob(os.path.join(outdir, '*.dex'))
+    utils.print_dexsegments(options.print_dexsegments, dex_files)
+
 if __name__ == '__main__':
   sys.exit(main())
diff --git a/tools/run_proguard_dx_on_gmscore.py b/tools/run_proguard_dx_on_gmscore.py
index de716b0..06f56f9 100755
--- a/tools/run_proguard_dx_on_gmscore.py
+++ b/tools/run_proguard_dx_on_gmscore.py
@@ -6,6 +6,7 @@
 # Run ProGuard and the DX or CompatDX (= D8) tool on GmsCore V10.
 
 from __future__ import print_function
+from glob import glob
 from os import makedirs
 from os.path import exists, join
 from subprocess import check_call
@@ -37,18 +38,22 @@
       default = os.getcwd())
   parser.add_argument('--print-runtimeraw',
       metavar = 'BENCHMARKNAME',
-      help = 'Prints the line \'<BENCHMARKNAME>(RunTimeRaw): <elapsed>' +
+      help = 'Print the line \'<BENCHMARKNAME>(RunTimeRaw): <elapsed>' +
              ' ms\' at the end where <elapsed> is the elapsed time in' +
              ' milliseconds.')
   parser.add_argument('--print-memoryuse',
       metavar='BENCHMARKNAME',
-      help='Prints the line \'<BENCHMARKNAME>(MemoryUse):' +
+      help='Print the line \'<BENCHMARKNAME>(MemoryUse):' +
            ' <mem>\' at the end where <mem> is the peak' +
            ' peak resident set size (VmHWM) in bytes.')
   parser.add_argument('--compatdx',
       help = 'Use CompatDx (D8) instead of DX.',
       default = False,
       action = 'store_true')
+  parser.add_argument('--print-dexsegments',
+      metavar = 'BENCHMARKNAME',
+      help = 'Print the sizes of individual dex segments as ' +
+          '\'<BENCHMARKNAME>-<segment>(CodeSize): <bytes>\'')
   return parser.parse_args()
 
 def Main():
@@ -113,5 +118,9 @@
     print('{}(RunTimeRaw): {} ms'
         .format(options.print_runtimeraw, 1000.0 * (time.time() - t0)))
 
+  if options.print_dexsegments:
+    dex_files = glob(os.path.join(outdir, '*.dex'))
+    utils.print_dexsegments(options.print_dexsegments, dex_files)
+
 if __name__ == '__main__':
   sys.exit(Main())
diff --git a/tools/test_android_cts.py b/tools/test_android_cts.py
index 606611d..4ef8039 100755
--- a/tools/test_android_cts.py
+++ b/tools/test_android_cts.py
@@ -246,8 +246,7 @@
     print('Comparing test results to baseline:\n')
 
     passing_tests = consistently_passing_tests_from_test_results([results_xml])
-    baseline_results = \
-        [f for f in glob(join(CTS_BASELINE_FILES_DIR, '*.xml'))]
+    baseline_results = glob(join(CTS_BASELINE_FILES_DIR, '*.xml'))
     assert len(baseline_results) != 0
 
     passing_tests_in_baseline = \
diff --git a/tools/test_framework.py b/tools/test_framework.py
index 57279bf..04a12d3 100755
--- a/tools/test_framework.py
+++ b/tools/test_framework.py
@@ -35,9 +35,6 @@
     'goyt_160525751')
 FRAMEWORK_JAR = os.path.join('third_party', 'framework',
     'framework_160115954.jar')
-DEX_SEGMENTS_JAR = os.path.join(utils.REPO_ROOT, 'build', 'libs',
-    'dexsegments.jar')
-DEX_SEGMENTS_RESULT_PATTERN = re.compile('- ([^:]+): ([0-9]+)')
 MIN_SDK_VERSION = '24'
 
 def parse_arguments():
@@ -61,27 +58,6 @@
       action = 'store_true')
   return parser.parse_args()
 
-# Return a dictionary: {segment_name -> segments_size}
-def getDexSegmentSizes(dex_files):
-  assert len(dex_files) > 0
-  cmd = ['java', '-jar', DEX_SEGMENTS_JAR]
-  cmd.extend(dex_files)
-  utils.PrintCmd(cmd)
-  output = subprocess.check_output(cmd)
-
-  matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
-
-  if matches is None or len(matches) == 0:
-    raise Exception('DexSegments failed to return any output for' \
-        ' these files: {}'.format(dex_files))
-
-  result = {}
-
-  for match in matches:
-    result[match[0]] = int(match[1])
-
-  return result
-
 def Main():
   args = parse_arguments()
 
@@ -136,9 +112,7 @@
     print('{}-Total(CodeSize): {}'
       .format(args.name, code_size))
 
-    for segment_name, size in getDexSegmentSizes(dex_files).items():
-      print('{}-{}(CodeSize): {}'
-          .format(args.name, segment_name, size))
+    utils.print_dexsegments(args.name, dex_files)
 
 if __name__ == '__main__':
   sys.exit(Main())
diff --git a/tools/utils.py b/tools/utils.py
index 2564adc..dfc35d7 100644
--- a/tools/utils.py
+++ b/tools/utils.py
@@ -15,6 +15,9 @@
 TOOLS_DIR = os.path.abspath(os.path.normpath(os.path.join(__file__, '..')))
 REPO_ROOT = os.path.realpath(os.path.join(TOOLS_DIR, '..'))
 MEMORY_USE_TMP_FILE = 'memory_use.tmp'
+DEX_SEGMENTS_JAR = os.path.join(REPO_ROOT, 'build', 'libs',
+    'dexsegments.jar')
+DEX_SEGMENTS_RESULT_PATTERN = re.compile('- ([^:]+): ([0-9]+)')
 
 def PrintCmd(s):
   if type(s) is list:
@@ -140,4 +143,30 @@
                   .format(unit))
   if result is None:
     raise Exception('No memory usage found in log: {}'.format(logfile))
-  return result
\ No newline at end of file
+  return result
+
+# Return a dictionary: {segment_name -> segments_size}
+def getDexSegmentSizes(dex_files):
+  assert len(dex_files) > 0
+  cmd = ['java', '-jar', DEX_SEGMENTS_JAR]
+  cmd.extend(dex_files)
+  PrintCmd(cmd)
+  output = subprocess.check_output(cmd)
+
+  matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
+
+  if matches is None or len(matches) == 0:
+    raise Exception('DexSegments failed to return any output for' \
+        ' these files: {}'.format(dex_files))
+
+  result = {}
+
+  for match in matches:
+    result[match[0]] = int(match[1])
+
+  return result
+
+def print_dexsegments(prefix, dex_files):
+  for segment_name, size in getDexSegmentSizes(dex_files).items():
+    print('{}-{}(CodeSize): {}'
+        .format(prefix, segment_name, size))