File: diagnose_bloat.py

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (1012 lines) | stat: -rwxr-xr-x 36,912 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
#!/usr/bin/env python3
# Copyright 2017 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Tool for finding the cause of binary size bloat.

See //tools/binary_size/README.md for example usage.

Note: this tool will perform gclient sync/git checkout on your local repo.
"""

import argparse
import atexit
import collections
from contextlib import contextmanager
import json
import logging
import os
import re
import shutil
import subprocess
import sys


_COMMIT_COUNT_WARN_THRESHOLD = 15
_ALLOWED_CONSECUTIVE_FAILURES = 2
_SRC_ROOT = os.path.abspath(
    os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
_DEFAULT_ARCHIVE_DIR = os.path.join(_SRC_ROOT, 'out', 'binary-size-results')
_DEFAULT_OUT_DIR = os.path.join(_SRC_ROOT, 'out', 'binary-size-build')
_SUPERSIZE_PATH = os.path.join(_SRC_ROOT, 'tools', 'binary_size', 'supersize')
_RESOURCE_SIZES_PATH = os.path.join(
    _SRC_ROOT, 'build', 'android', 'resource_sizes.py')
_AUTONINJA_PATH = shutil.which('autoninja')
_GN_PATH = shutil.which('gn')
_LLVM_TOOLS_DIR = os.path.join(_SRC_ROOT, 'third_party', 'llvm-build',
                               'Release+Asserts', 'bin')
_CLANG_UPDATE_PATH = os.path.join(_SRC_ROOT, 'tools', 'clang', 'scripts',
                                  'update.py')


_DiffResult = collections.namedtuple('DiffResult', ['name', 'value', 'units'])


class BaseDiff:
  """Base class capturing binary size diffs."""
  def __init__(self, name):
    self.name = name
    self.banner = '\n' + '*' * 30 + name + '*' * 30

  def AppendResults(self, logfiles):
    """Print and write diff results to an open |logfile|."""
    full, short = logfiles
    _WriteToFile(full, self.banner)
    _WriteToFile(short, self.banner)

    for s in self.Summary():
      _WriteToFile(short, s)
    _WriteToFile(short, '')

    for s in self.DetailedResults():
      full.write(s + '\n')

  @property
  def summary_stat(self):
    """Returns a tuple of (name, value, units) for the most important metric."""
    raise NotImplementedError()

  def Summary(self):
    """A short description that summarizes the source of binary size bloat."""
    raise NotImplementedError()

  def DetailedResults(self):
    """An iterable description of the cause of binary size bloat."""
    raise NotImplementedError()

  def ProduceDiff(self, before_dir, after_dir):
    """Prepare a binary size diff with ready to print results."""
    raise NotImplementedError()

  def RunDiff(self, logfiles, before_dir, after_dir):
    logging.info('Creating: %s', self.name)
    self.ProduceDiff(before_dir, after_dir)
    self.AppendResults(logfiles)


class NativeDiff(BaseDiff):
  # E.g.: Section Sizes (Total=1.2 kb (1222 bytes)):
  _RE_SUMMARY_STAT = re.compile(
      r'Section Sizes \(Total=(?P<value>-?[0-9\.]+) ?(?P<units>\w+)')
  _SUMMARY_STAT_NAME = 'Native Library Delta'

  def __init__(self, size_name):
    self._size_name = size_name
    self._diff = []
    super().__init__('Native Diff')

  @property
  def summary_stat(self):
    m = NativeDiff._RE_SUMMARY_STAT.search(self._diff)
    if m:
      return _DiffResult(
          NativeDiff._SUMMARY_STAT_NAME, m.group('value'), m.group('units'))
    raise Exception('Could not extract total from:\n' + self._diff)

  def DetailedResults(self):
    return self._diff.splitlines()

  def Summary(self):
    return self.DetailedResults()[:100]

  def ProduceDiff(self, before_dir, after_dir):
    before_size = os.path.join(before_dir, self._size_name)
    after_size = os.path.join(after_dir, self._size_name)
    cmd = [_SUPERSIZE_PATH, 'diff', before_size, after_size]
    self._diff = _RunCmd(cmd)[0].replace('{', '{{').replace('}', '}}')


class ResourceSizesDiff(BaseDiff):
  # Ordered by output appearance.
  _SUMMARY_SECTIONS = (
      'Specifics', 'InstallSize', 'InstallBreakdown', 'Dex')
  # Sections where it makes sense to sum subsections into a section total.
  _AGGREGATE_SECTIONS = (
      'InstallBreakdown', 'Breakdown', 'MainLibInfo', 'Uncompressed')

  def __init__(self, filename='results-chart.json', include_sections=None):
    self._diff = None  # Set by |ProduceDiff()|
    self._filename = filename
    self._include_sections = include_sections
    super().__init__('Resource Sizes Diff')

  @property
  def summary_stat(self):
    items = []
    for section_name, results in self._diff.items():
      for subsection_name, value, units in results:
        if 'normalized' in subsection_name:
          items.append([section_name, subsection_name, value, units])
    if len(items) > 1:  # Handle Trichrome.
      items = [item for item in items if 'Combined_normalized' in item[1]]
    if len(items) == 1:
      [section_name, subsection_name, value, units] = items[0]
      full_name = '{} {}'.format(section_name, subsection_name)
      return _DiffResult(full_name, value, units)
    raise Exception('Could not find canonical "normalized" in: %r' % self._diff)

  def CombinedSizeChangeForSection(self, section):
    for subsection_name, value, _ in self._diff[section]:
      if 'Combined' in subsection_name:
        return value
    raise Exception('Could not find "Combined" in: ' +
                    repr(self._diff[section]))

  def DetailedResults(self):
    return self._ResultLines()

  def Summary(self):
    footer_lines = [
        '',
        'For an explanation of these metrics, see:',
        ('https://chromium.googlesource.com/chromium/src/+/main/docs/speed/'
         'binary_size/metrics.md#Metrics-for-Android')]
    return self._ResultLines(
        include_sections=ResourceSizesDiff._SUMMARY_SECTIONS) + footer_lines

  def ProduceDiff(self, before_dir, after_dir):
    before = self._LoadResults(before_dir)
    after = self._LoadResults(after_dir)
    self._diff = collections.defaultdict(list)
    for section, section_dict in after.items():
      if self._include_sections and section not in self._include_sections:
        continue
      for subsection, v in section_dict.items():
        # Ignore entries when resource_sizes.py chartjson format has changed.
        if (section not in before or
            subsection not in before[section] or
            v['units'] != before[section][subsection]['units']):
          logging.warning(
              'Found differing dict structures for resource_sizes.py, '
              'skipping %s %s', section, subsection)
        else:
          self._diff[section].append(_DiffResult(
              subsection,
              v['value'] - before[section][subsection]['value'],
              v['units']))

  def _ResultLines(self, include_sections=None):
    """Generates diff lines for the specified sections (defaults to all)."""
    section_lines = collections.defaultdict(list)
    for section_name, section_results in self._diff.items():
      if not include_sections or section_name in include_sections:
        subsection_lines = []
        section_sum = 0
        units = ''
        for name, value, units in section_results:
          # Omit subsections with no changes for summaries.
          if value == 0 and include_sections:
            continue
          section_sum += value
          subsection_lines.append('{:>+14,} {} {}'.format(value, units, name))
        section_header = section_name
        if section_name in ResourceSizesDiff._AGGREGATE_SECTIONS:
          section_header += ' ({:+,} {})'.format(section_sum, units)
        section_header += ':'
        # Omit sections with empty subsections.
        if subsection_lines:
          section_lines[section_name].append(section_header)
          section_lines[section_name].extend(subsection_lines)
    if not section_lines:
      return ['Empty ' + self.name]
    ret = []
    for k in include_sections or sorted(section_lines):
      ret.extend(section_lines[k])
    return ret

  def _LoadResults(self, archive_dir):
    chartjson_file = os.path.join(archive_dir, self._filename)
    with open(chartjson_file) as f:
      chartjson = json.load(f)
    charts = chartjson['charts']
    # Older versions of resource_sizes.py prefixed the apk onto section names.
    ret = {}
    for section, section_dict in charts.items():
      section_no_target = re.sub(r'^.*_', '', section)
      ret[section_no_target] = section_dict
    return ret


class _BuildHelper:
  """Helper class for generating and building targets."""
  def __init__(self, args):
    self.clean = args.clean
    self.enable_chrome_android_internal = args.enable_chrome_android_internal
    self.extra_gn_args_str = args.gn_args
    self.apply_patch = args.extra_rev
    self.output_directory = args.output_directory
    self.target = args.target
    self.target_os = args.target_os
    self.use_reclient = args.use_reclient
    self.apk_name_override = args.custom_apk_name
    self.main_lib_path_override = args.custom_main_lib_path
    self._SetDefaults()
    self.is_bundle = 'minimal' in self.target

  def _MaybeAddGoogleSuffix(self, path):
    if self.IsTrichrome() and '_google' in self.target:
      return path.replace('.', 'Google.', 1)
    return path

  @property
  def abs_apk_paths(self):
    return [os.path.join(self.output_directory, x) for x in self.apk_paths]

  @property
  def abs_mapping_paths(self):
    def to_mapping_path(p):
      return p.replace('.minimal.apks', '.aab') + '.mapping'

    return [to_mapping_path(x) for x in self.abs_apk_paths]

  @property
  def abs_extra_paths(self):
    def to_extra_paths(p):
      aab_path = p.replace('.minimal.apks', '.aab')
      return [aab_path + '.unused_resources', aab_path + '.R.txt']

    return [p for x in self.abs_apk_paths for p in to_extra_paths(x)]

  @property
  def apk_name(self):
    if self.apk_name_override:
      return self.apk_name_override
    # my_great_apk -> MyGreat.apk
    apk_name = ''.join(s.title() for s in self.target.split('_')[:-1]) + '.apk'
    if self.is_bundle:
      # trichrome_32_minimal_apks -> Trichrome32Minimal.apk
      #                           -> Trichrome32.minimal.apks
      apk_name = apk_name.replace('Minimal.apk', '.minimal.apks')
    return apk_name.replace('Webview', 'WebView')

  @property
  def supersize_input(self):
    if self.IsTrichrome():
      return self._MaybeAddGoogleSuffix(
          os.path.join(self.output_directory, 'apks', 'Trichrome.ssargs'))
    return self.abs_apk_paths[0]

  @property
  def apk_paths(self):
    if self.IsTrichrome():
      ret = [
          os.path.join('apks', 'TrichromeChrome.minimal.apks'),
          os.path.join('apks', 'TrichromeWebView.minimal.apks'),
          os.path.join('apks', 'TrichromeLibrary.apk'),
      ]
      return [self._MaybeAddGoogleSuffix(x) for x in ret]

    return [os.path.join('apks', self.apk_name)]

  @property
  def main_lib_path(self):
    # TODO(agrieve): Could maybe extract from .apk or GN?
    if self.main_lib_path_override:
      return self.main_lib_path_override
    if self.IsLinux():
      return 'chrome'
    if 'monochrome' in self.target or 'trichrome' in self.target:
      ret = 'lib.unstripped/libmonochrome.so'
    elif 'webview' in self.target:
      ret = 'lib.unstripped/libwebviewchromium.so'
    else:
      ret = 'lib.unstripped/libchrome.so'
    return ret

  @property
  def abs_main_lib_path(self):
    return os.path.join(self.output_directory, self.main_lib_path)

  @property
  def map_file_path(self):
    return self.main_lib_path + '.map.gz'

  @property
  def size_name(self):
    if self.IsLinux():
      return os.path.basename(self.main_lib_path) + '.size'
    return self.apk_name + '.size'

  def _SetDefaults(self):
    has_internal = os.path.exists(os.path.join(_SRC_ROOT, 'internal'))
    if has_internal:
      self.extra_gn_args_str = (
          'is_chrome_branded=true ' + self.extra_gn_args_str)
    else:
      self.extra_gn_args_str = (
          'ffmpeg_branding="Chrome" proprietary_codecs=true' +
          self.extra_gn_args_str)
    if self.IsLinux():
      self.extra_gn_args_str = (
          'is_cfi=false generate_linker_map=true ' + self.extra_gn_args_str)
    self.extra_gn_args_str = ' ' + self.extra_gn_args_str.strip()

    if not self.target:
      if self.IsLinux():
        self.target = 'chrome'
      elif self.enable_chrome_android_internal:
        self.target = 'trichrome_google_32_minimal_apks'
      else:
        self.target = 'trichrome_32_minimal_apks'

  def _GenGnCmd(self):
    gn_args = 'is_official_build=true'
    gn_args += ' android_channel="stable"'
    # Variables often become unused when experimenting with macros to reduce
    # size, so don't fail on warnings.
    gn_args += ' treat_warnings_as_errors=false'
    # Speed things up a bit by skipping lint & errorprone.
    gn_args += ' disable_android_lint=true'
    # Down from default of 2 to speed up compile and use less disk.
    # Compiles need at least symbol_level=1 for pak allowlist to work.
    gn_args += ' symbol_level=1'
    gn_args += ' use_errorprone_java_compiler=false'
    gn_args += ' use_remoteexec=%s' % str(self.use_reclient).lower()
    gn_args += ' target_os="%s"' % self.target_os
    if self.IsAndroid():
      gn_args += (' enable_chrome_android_internal=%s' %
                  str(self.enable_chrome_android_internal).lower())
    gn_args += self.extra_gn_args_str
    return [_GN_PATH, 'gen', self.output_directory, '--args=%s' % gn_args]

  def _GenNinjaCmd(self):
    cmd = [_AUTONINJA_PATH, '-C', self.output_directory]
    cmd += [self.target]
    return cmd

  def Run(self):
    """Run GN gen/ninja build and return the process returncode."""
    logging.info('Building %s within %s (this might take a while).',
                 self.target, os.path.relpath(self.output_directory))
    if self.clean:
      _RunCmd([_GN_PATH, 'clean', self.output_directory], cwd=_SRC_ROOT)
    retcode = _RunCmd(self._GenGnCmd(),
                      cwd=_SRC_ROOT,
                      verbose=True,
                      exit_on_failure=False)[1]
    if retcode:
      return retcode
    return _RunCmd(self._GenNinjaCmd(),
                   cwd=_SRC_ROOT,
                   verbose=True,
                   exit_on_failure=False)[1]

  def IsAndroid(self):
    return self.target_os == 'android'

  def IsTrichrome(self):
    return 'trichrome' in self.target

  def IsLinux(self):
    return self.target_os == 'linux'


class _BuildArchive:
  """Class for managing a directory with build results and build metadata."""

  def __init__(self, rev, base_archive_dir, build, subrepo, save_unstripped,
               supersize_archive_args):
    self.build = build
    self.dir = os.path.join(base_archive_dir, rev)
    metadata_path = os.path.join(self.dir, 'metadata.txt')
    self.rev = rev
    self.metadata = _Metadata([self], build, metadata_path, subrepo)
    self._save_unstripped = save_unstripped
    self._supersize_archive_args = supersize_archive_args

  def ArchiveBuildResults(self):
    """Save build artifacts necessary for diffing."""
    logging.info('Saving build results to: %s', self.dir)
    _EnsureDirsExist(self.dir)
    if self.build.IsAndroid():
      for path in self.build.abs_apk_paths:
        self._ArchiveFile(path)
      for path in self.build.abs_mapping_paths:
        # Some apks have no .mapping files.
        self._ArchiveFile(path, missing_ok=True)
      for path in self.build.abs_extra_paths:
        # These are useful for debugging but not necessary.
        self._ArchiveFile(path, missing_ok=True)
      self._ArchiveResourceSizes()
    self._ArchiveSizeFile()
    if self._save_unstripped:
      self._ArchiveFile(self.build.abs_main_lib_path)
    self.metadata.Write()
    assert self.Exists()

  def Exists(self):
    ret = self.metadata.Exists() and os.path.exists(self.archived_size_path)
    if self._save_unstripped:
      ret = ret and os.path.exists(self.archived_unstripped_path)
    return ret

  @property
  def archived_unstripped_path(self):
    return os.path.join(self.dir, os.path.basename(self.build.main_lib_path))

  @property
  def archived_size_path(self):
    return os.path.join(self.dir, self.build.size_name)

  def _ArchiveResourceSizes(self):
    cmd = [
        _RESOURCE_SIZES_PATH, '--output-dir', self.dir, '--chartjson',
        '--chromium-output-dir', self.build.output_directory
    ]
    if self.build.IsTrichrome():
      get_apk = lambda t: next(x for x in self.build.abs_apk_paths if t in x)
      cmd += ['--trichrome-chrome', get_apk('Chrome')]
      cmd += ['--trichrome-webview', get_apk('WebView')]
      cmd += ['--trichrome-library', get_apk('Library')]
      cmd += [self.build.apk_name]
    else:
      cmd += [self.build.abs_apk_paths[0]]
    _RunCmd(cmd)

  def _ArchiveFile(self, filename, missing_ok=False):
    if not os.path.exists(filename):
      if missing_ok:
        return
      _Die('missing expected file: %s', filename)
    shutil.copy(filename, self.dir)

  def _ArchiveSizeFile(self):
    supersize_cmd = [_SUPERSIZE_PATH, 'archive', self.archived_size_path]
    if self.build.IsAndroid():
      supersize_cmd += ['-f', self.build.supersize_input]
      if os.path.exists(self.build.abs_main_lib_path):
        supersize_cmd += ['--aux-elf-file', self.build.abs_main_lib_path]
    else:
      supersize_cmd += ['--elf-file', self.build.abs_main_lib_path]
    supersize_cmd += ['--output-directory', self.build.output_directory]
    if self._supersize_archive_args:
      supersize_cmd.extend(self._supersize_archive_args.split())
    logging.info('Creating .size file')
    _RunCmd(supersize_cmd)


class _DiffArchiveManager:
  """Class for maintaining BuildArchives and their related diff artifacts."""

  def __init__(self, revs, archive_dir, diffs, build, subrepo, save_unstripped,
               supersize_archive_args, share):
    self.archive_dir = archive_dir
    self.build = build
    self.build_archives = [
        _BuildArchive(rev, archive_dir, build, subrepo, save_unstripped,
                      supersize_archive_args) for rev in revs
    ]
    self.diffs = diffs
    self.subrepo = subrepo
    self.share = share
    self._summary_stats = []

  def MaybeDiff(self, before_id, after_id):
    """Perform diffs given two build archives."""
    before = self.build_archives[before_id]
    after = self.build_archives[after_id]
    diff_path, short_diff_path = self._DiffFilePaths(before, after)
    if not self._CanDiff(before, after):
      logging.info(
          'Skipping diff for %s due to missing build archives.', diff_path)
      return

    metadata_path = self._DiffMetadataPath(before, after)
    metadata = _Metadata(
        [before, after], self.build, metadata_path, self.subrepo)
    if metadata.Exists():
      logging.info(
          'Skipping diff for %s and %s. Matching diff already exists: %s',
          before.rev, after.rev, diff_path)
    else:
      with open(diff_path, 'w') as diff_file, \
           open(short_diff_path, 'w') as summary_file:
        for d in self.diffs:
          d.RunDiff((diff_file, summary_file), before.dir, after.dir)
      metadata.Write()
      self._AddDiffSummaryStat(before, after)
    if os.path.exists(short_diff_path):
      _PrintFile(short_diff_path)
    logging.info('See detailed diff results here: %s',
                 os.path.relpath(diff_path))

  def GenerateHtmlReport(self, before_id, after_id, is_internal=False):
    """Generate HTML report given two build archives."""
    before = self.build_archives[before_id]
    after = self.build_archives[after_id]
    diff_path = self._DiffDir(before, after)
    if not self._CanDiff(before, after):
      logging.info(
          'Skipping HTML report for %s due to missing build archives.',
          diff_path)
      return

    report_path = os.path.join(diff_path, 'diff.sizediff')

    supersize_cmd = [
        _SUPERSIZE_PATH, 'save_diff', before.archived_size_path,
        after.archived_size_path, report_path
    ]

    logging.info('Creating .sizediff')
    _RunCmd(supersize_cmd)
    gsutil_cmd = ['gsutil.py', 'cp']
    if is_internal:
      oneoffs_dir = 'private-oneoffs'
    else:
      oneoffs_dir = 'oneoffs'
      gsutil_cmd += ['-a', 'public-read']
    unique_name = '{}_{}.sizediff'.format(before.rev, after.rev)
    local = os.path.relpath(report_path)
    gsutil_cmd += [local, f'gs://chrome-supersize/{oneoffs_dir}/{unique_name}']

    if self.share:
      msg = 'Automatically uploaded, '
      _RunCmd(gsutil_cmd)
    else:
      msg = (f'Saved locally to {local}. To view, upload to '
             'https://chrome-supersize.firebaseapp.com/viewer.html.\n'
             'To share, run:\n'
             f'> {" ".join(gsutil_cmd)}\n\n'
             'Then ')
    msg = '\n=====================\n' + msg + (
        'view it at https://chrome-supersize.firebaseapp.com/viewer.html'
        '?load_url=https://storage.googleapis.com/chrome-supersize/'
        f'{oneoffs_dir}/{unique_name}'
        '\n=====================\n')
    logging.info(msg)

  def Summarize(self):
    path = os.path.join(self.archive_dir, 'last_diff_summary.txt')
    if self._summary_stats:
      with open(path, 'w') as f:
        stats = sorted(
            self._summary_stats, key=lambda x: x[0].value, reverse=True)
        _WriteToFile(f, '\nDiff Summary')
        for s, before, after in stats:
          _WriteToFile(f, '{:>+10} {} {} for range: {}..{}',
                               s.value, s.units, s.name, before, after)

    # Print cached file if all builds were cached.
    num_archives = len(self.build_archives)
    if os.path.exists(path) and num_archives > 1:
      _PrintFile(path)
    if num_archives <= 2:
      if not all(a.Exists() for a in self.build_archives):
        return
      size2 = ''
      if num_archives == 2:
        size2 = os.path.relpath(self.build_archives[-1].archived_size_path)
      logging.info('Enter supersize console via: %s console %s %s',
                   os.path.relpath(_SUPERSIZE_PATH),
                   os.path.relpath(self.build_archives[0].archived_size_path),
                   size2)


  def _AddDiffSummaryStat(self, before, after):
    stat = None
    if self.build.IsAndroid():
      summary_diff_type = ResourceSizesDiff
    else:
      summary_diff_type = NativeDiff
    for d in self.diffs:
      if isinstance(d, summary_diff_type):
        stat = d.summary_stat
    if stat:
      self._summary_stats.append((stat, before.rev, after.rev))

  def _CanDiff(self, before, after):
    return before.Exists() and after.Exists()

  def _DiffFilePaths(self, before, after):
    ret = os.path.join(self._DiffDir(before, after), 'diff_results')
    return ret + '.txt', ret + '.short.txt'

  def _DiffMetadataPath(self, before, after):
    return os.path.join(self._DiffDir(before, after), 'metadata.txt')

  def _DiffDir(self, before, after):
    archive_range = '%s..%s' % (before.rev, after.rev)
    diff_path = os.path.join(self.archive_dir, 'diffs', archive_range)
    _EnsureDirsExist(diff_path)
    return diff_path


class _Metadata:

  def __init__(self, archives, build, path, subrepo):
    self.data = {
      'revs': [a.rev for a in archives],
      'apply_patch': build.apply_patch,
      'archive_dirs': [a.dir for a in archives],
      'target': build.target,
      'target_os': build.target_os,
      'subrepo': subrepo,
      'path': path,
      'gn_args': {
        'extra_gn_args_str': build.extra_gn_args_str,
        'enable_chrome_android_internal': build.enable_chrome_android_internal,
      }
    }

  def Exists(self):
    path = self.data['path']
    if os.path.exists(path):
      with open(path, 'r') as f:
        return self.data == json.load(f)
    return False

  def Write(self):
    with open(self.data['path'], 'w') as f:
      json.dump(self.data, f)


def _EnsureDirsExist(path):
  if not os.path.exists(path):
    os.makedirs(path)


def _RunCmd(cmd, cwd=None, verbose=False, exit_on_failure=True):
  """Convenience function for running commands.

  Args:
    cmd: the command to run.
    verbose: if this is True, then the stdout and stderr of the process will be
        printed. If it's false, the stdout will be returned.
    exit_on_failure: die if an error occurs when this is True.

  Returns:
    Tuple of (process stdout, process returncode).
  """
  assert not (verbose and exit_on_failure)
  cmd_str = ' '.join(c for c in cmd)
  logging.debug('Running: %s', cmd_str)
  proc_stdout = proc_stderr = subprocess.PIPE
  if verbose:
    proc_stdout, proc_stderr = sys.stdout, subprocess.STDOUT

  # pylint: disable=unexpected-keyword-arg
  proc = subprocess.Popen(cmd,
                          cwd=cwd,
                          stdout=proc_stdout,
                          stderr=proc_stderr,
                          encoding='utf-8')
  stdout, stderr = proc.communicate()

  if proc.returncode and exit_on_failure:
    _Die('command failed: %s\nstderr:\n%s', cmd_str, stderr)

  stdout = stdout.strip() if stdout else ''
  return stdout, proc.returncode


def _GitCmd(args, subrepo):
  return _RunCmd(['git', '-C', subrepo] + args)[0]


def _GclientSyncCmd(rev, subrepo):
  cwd = os.getcwd()
  os.chdir(subrepo)
  _, retcode = _RunCmd(['gclient', 'sync', '-r', 'src@' + rev],
                       verbose=True, exit_on_failure=False)
  os.chdir(cwd)
  return retcode


def _SyncAndBuild(archive, build, subrepo, no_gclient, extra_rev):
  """Sync, build and return non 0 if any commands failed."""
  # Simply do a checkout if subrepo is used.
  if _CurrentGitHash(subrepo) == archive.rev:
    if subrepo != _SRC_ROOT:
      logging.info('Skipping git checkout since already at desired rev')
    else:
      logging.info('Skipping gclient sync since already at desired rev')
  elif subrepo != _SRC_ROOT or no_gclient:
    _GitCmd(['checkout',  archive.rev], subrepo)
  else:
    # Move to a detached state since gclient sync doesn't work with local
    # commits on a branch.
    _GitCmd(['checkout', '--detach'], subrepo)
    logging.info('Syncing to %s', archive.rev)
    ret = _GclientSyncCmd(archive.rev, subrepo)
    if ret:
      return ret
  with _ApplyPatch(extra_rev, subrepo):
    return build.Run()


@contextmanager
def _ApplyPatch(rev, subrepo):
  if not rev:
    yield
  else:
    restore_func = _GenRestoreFunc(subrepo)
    try:
      _GitCmd(['cherry-pick', rev, '--strategy-option', 'theirs'], subrepo)
      yield
    finally:
      restore_func()


def _GenerateRevList(rev, reference_rev, all_in_range, subrepo, step):
  """Normalize and optionally generate a list of commits in the given range.

  Returns:
    A list of revisions ordered from oldest to newest.
  """
  rev_seq = '%s^..%s' % (reference_rev, rev)
  stdout = _GitCmd(['rev-list', rev_seq], subrepo)
  all_revs = stdout.splitlines()[::-1]
  if all_in_range or len(all_revs) < 2 or step:
    revs = all_revs
    if step:
      revs = revs[::step]
  else:
    revs = [all_revs[0], all_revs[-1]]
  num_revs = len(revs)
  if num_revs >= _COMMIT_COUNT_WARN_THRESHOLD:
    _VerifyUserAccepts(
        'You\'ve provided a commit range that contains %d commits.' % num_revs)
  logging.info('Processing %d commits', num_revs)
  return revs


def _ValidateRevs(rev, reference_rev, subrepo, extra_rev):
  def git_fatal(args, message):
    devnull = open(os.devnull, 'wb')
    retcode = subprocess.call(
        ['git', '-C', subrepo] + args, stdout=devnull, stderr=subprocess.STDOUT)
    if retcode:
      _Die(message)

  no_obj_message = ('%s either doesn\'t exist or your local repo is out of '
                    'date, try "git fetch origin master"')
  git_fatal(['cat-file', '-e', rev], no_obj_message % rev)
  git_fatal(['cat-file', '-e', reference_rev], no_obj_message % reference_rev)
  if extra_rev:
    git_fatal(['cat-file', '-e', extra_rev], no_obj_message % extra_rev)
  git_fatal(['merge-base', '--is-ancestor', reference_rev, rev],
            f'reference-rev ({reference_rev}) is not an ancestor of '
            f'rev ({rev})')


def _VerifyUserAccepts(message):
  print(message + ' Do you want to proceed? [y/n]')
  if input('> ').lower() != 'y':
    sys.exit()


def _EnsureDirectoryClean(subrepo):
  logging.info('Checking source directory')
  stdout = _GitCmd(['status', '--porcelain'], subrepo)
  # Ignore untracked files.
  if stdout and stdout[:2] != '??':
    logging.error('Failure: please ensure working directory is clean.')
    sys.exit()


def _Die(s, *args):
  logging.error('Failure: ' + s, *args)
  sys.exit(1)


def _WriteToFile(logfile, s, *args, **kwargs):
  if isinstance(s, str):
    data = s.format(*args, **kwargs) + '\n'
  else:
    data = '\n'.join(s) + '\n'
  logfile.write(data)


def _PrintFile(path):
  with open(path) as f:
    sys.stdout.write(f.read())


def _CurrentGitHash(subrepo):
  return _GitCmd(['rev-parse', 'HEAD'], subrepo)


def _GenRestoreFunc(subrepo):
  branch = _GitCmd(['rev-parse', '--abbrev-ref', 'HEAD'], subrepo)
  # Happens when the repo didn't start on a named branch.
  if branch == 'HEAD':
    branch = _GitCmd(['rev-parse', 'HEAD'], subrepo)
  def _RestoreFunc():
    logging.warning('Restoring original git checkout')
    _GitCmd(['checkout', branch], subrepo)
  return _RestoreFunc


def _SetRestoreFunc(subrepo):
  atexit.register(_GenRestoreFunc(subrepo))


def main():
  parser = argparse.ArgumentParser(
      description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  parser.add_argument('rev',
                      help='Find binary size bloat for this commit.')
  parser.add_argument('--archive-directory',
                      default=_DEFAULT_ARCHIVE_DIR,
                      help='Where results are stored.')
  parser.add_argument('--reference-rev',
                      help='Older rev to diff against. If not supplied, '
                           'the previous commit to rev will be used.')
  parser.add_argument('--all',
                      action='store_true',
                      help='Build/download all revs from --reference-rev to '
                           'rev and diff the contiguous revisions.')
  parser.add_argument('--single',
                      action='store_true',
                      help='Sets --reference-rev=rev.')
  parser.add_argument('--unstripped',
                      action='store_true',
                      help='Save the unstripped native library when archiving.')
  parser.add_argument(
      '--subrepo',
      help='Specify a subrepo directory to use. Implies '
      '--no-gclient. All git commands will be executed '
      'from the subrepo directory.')
  parser.add_argument('--no-gclient',
                      action='store_true',
                      help='Do not perform gclient sync steps.')
  parser.add_argument('--apply-patch', dest='extra_rev',
                      help='A local commit to cherry-pick before each build. '
                           'This can leave your repo in a broken state if '
                           'the cherry-pick fails.')
  parser.add_argument('--step', type=int,
                      help='Assumes --all and only builds/downloads every '
                           '--step\'th revision.')
  parser.add_argument('-v',
                      '--verbose',
                      action='store_true',
                      help='Show commands executed, extra debugging output'
                           ', and Ninja/GN output.')
  parser.add_argument('--supersize-archive-args',
                      help='Args to pass through to the supersize archive '
                      'command (e.g. --java-only, --no-output-directory, etc).')
  parser.add_argument('--share',
                      action='store_true',
                      help='Automatically upload using gsutil.py.')

  build_group = parser.add_argument_group('build arguments')
  build_group.add_argument('--no-reclient',
                           action='store_false',
                           dest='use_reclient',
                           default=True,
                           help='Do not use reclient when building with ninja.')
  build_group.add_argument('--clean',
                           action='store_true',
                           help='Do a clean build for each revision.')
  build_group.add_argument('--gn-args',
                           default='',
                           help='Extra GN args to set.')
  build_group.add_argument('--target-os',
                           default='android',
                           choices=['android', 'linux'],
                           help='target_os gn arg. Default: android.')
  build_group.add_argument('--output-directory',
                           default=_DEFAULT_OUT_DIR,
                           help='ninja output directory. '
                                'Default: %s.' % _DEFAULT_OUT_DIR)
  build_group.add_argument('--enable-chrome-android-internal',
                           action='store_true',
                           help='Allow downstream targets to be built.')
  build_group.add_argument('--target',
                           help='GN target to build. Linux default: chrome. '
                           'Android default: trichrome_32_minimal_apks or '
                           'trichrome_google_32_minimal_apks (depending on '
                           '--enable-chrome-android-internal).')
  build_group.add_argument('--custom-apk-name',
                           help='The apk name by default is derived from the '
                           'target name, but occasionally targets set a custom '
                           'apk name in GN. In those cases use this flag to '
                           'specify the actual apk name (e.g. '
                           '--custom-apk-name=ChromiumNetTestSupport.apk for '
                           'net_test_support_apk).')
  build_group.add_argument('--custom-main-lib-path',
                           help='The main lib path by default is derived from '
                           'the target name. Set this if your target has its '
                           'own main lib path (e.g. '
                           '--custom-main-lib-path=lib.unstripped/'
                           'libnet_java_test_native_support.so for '
                           'net_test_support_apk).')
  if len(sys.argv) == 1:
    parser.print_help()
    return 1

  args = parser.parse_args()
  log_level = logging.DEBUG if args.verbose else logging.INFO
  logging.basicConfig(level=log_level,
                      format='%(levelname).1s %(relativeCreated)6d %(message)s')
  if args.target and args.target.endswith('_bundle'):
    parser.error('Bundle targets must use _minimal_apks variants')

  if _GN_PATH is None:
    parser.error('Could not find "gn" on your PATH')
  if _AUTONINJA_PATH is None:
    parser.error('Could not find "autoninja" on your PATH')

  build = _BuildHelper(args)
  subrepo = args.subrepo or _SRC_ROOT
  _EnsureDirectoryClean(subrepo)
  _SetRestoreFunc(subrepo)

  if build.IsLinux():
    _VerifyUserAccepts('Linux diffs have known deficiencies (crbug/717550).')

  # llvm-objdump always exists for android checkouts, which run it as DEPS hook,
  # but not for linux.
  if not os.path.exists(os.path.join(_LLVM_TOOLS_DIR, 'llvm-objdump')):
    _RunCmd([_CLANG_UPDATE_PATH, '--package=objdump'])

  reference_rev = args.reference_rev or args.rev + '^'
  if args.single:
    reference_rev = args.rev
  _ValidateRevs(args.rev, reference_rev, subrepo, args.extra_rev)
  revs = _GenerateRevList(args.rev, reference_rev, args.all, subrepo, args.step)

  diffs = [NativeDiff(build.size_name)]
  if build.IsAndroid():
    diffs += [ResourceSizesDiff()]
  diff_mngr = _DiffArchiveManager(revs, args.archive_directory, diffs, build,
                                  subrepo, args.unstripped,
                                  args.supersize_archive_args, args.share)
  consecutive_failures = 0
  i = 0
  for i, archive in enumerate(diff_mngr.build_archives):
    if archive.Exists():
      logging.info('Found matching metadata for %s, skipping build step.',
                   archive.rev)
    else:
      build_failure = _SyncAndBuild(archive, build, subrepo, args.no_gclient,
                                    args.extra_rev)
      if build_failure:
        logging.info(
            'Build failed for %s, diffs using this rev will be skipped.',
            archive.rev)
        consecutive_failures += 1
        if len(diff_mngr.build_archives) <= 2:
          _Die('Stopping due to build failure.')
        elif consecutive_failures > _ALLOWED_CONSECUTIVE_FAILURES:
          _Die('%d builds failed in a row, last failure was %s.',
               consecutive_failures, archive.rev)
      else:
        archive.ArchiveBuildResults()
        consecutive_failures = 0

    if i != 0:
      diff_mngr.MaybeDiff(i - 1, i)

  diff_mngr.GenerateHtmlReport(0,
                               i,
                               is_internal=args.enable_chrome_android_internal)
  diff_mngr.Summarize()

  return 0


if __name__ == '__main__':
  sys.exit(main())