forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
1625 lines (1361 loc) · 52.9 KB
/
models.py
File metadata and controls
1625 lines (1361 loc) · 52.9 KB
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
# 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.
"""Classes that comprise the data model for binary size analysis.
See docs/data_model.md for an explanation of what fields do.
"""
import collections
import functools
import logging
import os
import re
import match_util
BUILD_CONFIG_GIT_REVISION = 'git_revision'
BUILD_CONFIG_GN_ARGS = 'gn_args'
BUILD_CONFIG_TITLE = 'title'
BUILD_CONFIG_URL = 'url'
BUILD_CONFIG_OUT_DIRECTORY = 'out_directory'
METRICS_COUNT = 'COUNT'
METRICS_COUNT_RELOCATIONS = 'Relocations'
METRICS_SIZE = 'SIZE'
METRICS_SIZE_APK_FILE = 'APK File'
METADATA_APK_FILENAME = 'apk_file_name' # Path relative to output_directory.
METADATA_APK_SPLIT_NAME = 'apk_split_name' # Name of the split if applicable.
METADATA_ZIPALIGN_OVERHEAD = 'zipalign_padding' # Overhead from zipalign.
METADATA_SIGNING_BLOCK_SIZE = 'apk_signature_block_size' # Size in bytes.
METADATA_MAP_FILENAME = 'map_file_name' # Path relative to output_directory.
METADATA_ELF_ALGORITHM = 'elf_algorithm' # linker_map / dwarf / sections.
METADATA_ELF_APK_PATH = 'elf_apk_path' # Path of the .so within the .apk.
METADATA_ELF_ARCHITECTURE = 'elf_arch' # "arm", "arm64", "x86", or "x64".
METADATA_ELF_FILENAME = 'elf_file_name' # Path relative to output_directory.
METADATA_ELF_MTIME = 'elf_mtime' # int timestamp in utc.
METADATA_ELF_BUILD_ID = 'elf_build_id'
METADATA_PROGUARD_MAPPING_FILENAME = 'proguard_mapping_file_name'
# New sections should also be added to the SuperSize UI.
SECTION_ARSC = '.arsc'
SECTION_BSS = '.bss'
SECTION_BSS_REL_RO = '.bss.rel.ro'
SECTION_DATA = '.data'
SECTION_DATA_REL_RO = '.data.rel.ro'
SECTION_DATA_REL_RO_LOCAL = '.data.rel.ro.local'
SECTION_DEX = '.dex'
SECTION_DEX_METHOD = '.dex.method'
SECTION_OTHER = '.other'
SECTION_PAK_NONTRANSLATED = '.pak.nontranslated'
SECTION_PAK_TRANSLATIONS = '.pak.translations'
SECTION_PART_END = '.part.end'
SECTION_RELRO_PADDING = '.relro_padding'
SECTION_RODATA = '.rodata'
SECTION_TEXT = '.text'
# Used by SymbolGroup when they contain a mix of sections.
SECTION_MULTIPLE = '.*'
APK_PREFIX_PATH = '$APK'
NATIVE_PREFIX_PATH = '$NATIVE'
SYSTEM_PREFIX_PATH = '$SYSTEM'
DEX_SECTIONS = (
SECTION_DEX,
SECTION_DEX_METHOD,
)
NATIVE_SECTIONS = (
SECTION_BSS,
SECTION_BSS_REL_RO,
SECTION_DATA,
SECTION_DATA_REL_RO,
SECTION_DATA_REL_RO_LOCAL,
SECTION_PART_END,
SECTION_RODATA,
SECTION_TEXT,
)
BSS_SECTIONS = (
SECTION_BSS,
SECTION_BSS_REL_RO,
SECTION_PART_END,
SECTION_RELRO_PADDING,
)
PAK_SECTIONS = (
SECTION_PAK_NONTRANSLATED,
SECTION_PAK_TRANSLATIONS,
)
CONTAINER_MULTIPLE = '*'
CONTAINER_NAME_EMPTY = '(empty)'
SECTION_NAME_TO_SECTION = {
SECTION_ARSC: 'a',
SECTION_BSS: 'b',
SECTION_BSS_REL_RO: 'b',
SECTION_DATA: 'd',
SECTION_DATA_REL_RO_LOCAL: 'R',
SECTION_DATA_REL_RO: 'R',
SECTION_DEX: 'x',
SECTION_DEX_METHOD: 'm',
SECTION_OTHER: 'o',
SECTION_PART_END: 'b',
SECTION_PAK_NONTRANSLATED: 'P',
SECTION_PAK_TRANSLATIONS: 'p',
SECTION_RELRO_PADDING: 'b',
SECTION_RODATA: 'r',
SECTION_TEXT: 't',
SECTION_MULTIPLE: '*',
}
SECTION_TO_SECTION_NAME = collections.OrderedDict((
('a', SECTION_ARSC),
('t', SECTION_TEXT),
('r', SECTION_RODATA),
('R', SECTION_DATA_REL_RO),
('d', SECTION_DATA),
('b', SECTION_BSS),
('x', SECTION_DEX),
('m', SECTION_DEX_METHOD),
('p', SECTION_PAK_TRANSLATIONS),
('P', SECTION_PAK_NONTRANSLATED),
('o', SECTION_OTHER),
))
# Relevant for native symbols. All anonymous:: namespaces are removed during
# name normalization. This flag means that the name had one or more anonymous::
# namespaces stripped from it.
FLAG_ANONYMOUS = 1
# Relevant for .text symbols. The actual symbol name had a "startup." prefix on
# it, which was removed by name normalization.
FLAG_STARTUP = 2
# Relevant for .text symbols. The actual symbol name had a "unlikely." prefix on
# it, which was removed by name normalization.
FLAG_UNLIKELY = 4
# Relevant to .data & .rodata symbols. The actual symbol name had a "rel."
# prefix on it, which was removed by name normalization.
FLAG_REL = 8
# Relevant to .data & .rodata symbols. The actual symbol name had a "rel.local."
# prefix on it, which was removed by name normalization.
FLAG_REL_LOCAL = 16
# The source path did not have the usual "../.." prefix, but instead had a
# prefix of "gen", meaning that the symbol is from a source file that was
# generated during the build (the "gen" prefix is removed during normalization).
FLAG_GENERATED_SOURCE = 32
# Relevant for .text symbols. The actual symbol name had a " [clone .####]"
# suffix, which was removed by name normalization. Cloned symbols are created by
# compiler optimizations (e.g. partial inlining).
FLAG_CLONE = 64
# Relevant for .text symbols. The actual symbol name had a "hot." prefix on it,
# which was removed by name normalization. Occurs when an AFDO profile is
# supplied to the linker.
FLAG_HOT = 128
# Relevant for .text symbols. If a method has this flag, then it was run
# according to the code coverage.
FLAG_COVERED = 256
# Relevant for non-locale .pak symbols. Indicates a pak entry is stored
# uncompressed.
FLAG_UNCOMPRESSED = 512
DIFF_STATUS_UNCHANGED = 0
DIFF_STATUS_CHANGED = 1
DIFF_STATUS_ADDED = 2
DIFF_STATUS_REMOVED = 3
DIFF_PREFIX_BY_STATUS = ['= ', '~ ', '+ ', '- ']
DIFF_COUNT_DELTA = [0, 0, 1, -1]
STRING_LITERAL_NAME = 'string literal'
def ClassifySections(section_names):
"""Returns section names subsets classified by contribution to binary size.
Args:
section_names: A list of existing sections names.
Returns:
Tuple (unsummed_sections, summed_sections). |unsummed_sections| are sections
that don't contribute to binary size. |summed_sections| are sections that
*explicitly* contribute to binary size. What's excluded are sections that
*implicitly* contribute to binary size -- these get lumped into the .other
section.
"""
unsummed_sections = set(name for name in section_names
if name in BSS_SECTIONS or '(' in name)
summed_sections = (set(section_names)
& set(SECTION_NAME_TO_SECTION.keys()) - unsummed_sections)
return frozenset(unsummed_sections), frozenset(summed_sections)
class BaseContainer:
"""Base class for BaseContainer and DeltaContainer.
Fields:
short_name: Short container name for compact display. This, also needs to be
unique among containers in the same SizeInfo, and can be ''.
classified_sections: Cache for ClassifySections().
"""
__slots__ = (
'short_name',
'_classified_sections',
)
def __init__(self):
# name == '' hints that only one container exists, and there's no need to
# distinguish them. This can affect console output.
self.short_name = None # Assigned by AssignShortNames().
self._classified_sections = None
def __str__(self):
return self.name
def __repr__(self):
return '{}(name={}, short_name={})'.format(self.__class__.__name__,
self.name, self.short_name)
def ClassifySections(self):
if self._classified_sections is None:
self._classified_sections = ClassifySections(self.section_sizes.keys())
return self._classified_sections
@staticmethod
def AssignShortNames(containers):
for i, c in enumerate(containers):
c.short_name = str(i) if c.name else ''
@property
def name(self):
pass
@property
def section_sizes(self):
pass
class Container(BaseContainer):
"""Info for a single SuperSize input file (e.g., APK file).
Fields:
metadata: A dict.
name: Container name. Must be unique among (non-Diff) Containers.
section_sizes: A dict of section_name -> size.
"""
__slots__ = (
'metadata',
'name',
'section_sizes',
'metrics_by_file',
)
def __init__(self, name, metadata, section_sizes, metrics_by_file):
super().__init__()
self.name = name
self.metadata = metadata or {}
self.section_sizes = section_sizes # E.g. {SECTION_TEXT: 0}
self.metrics_by_file = metrics_by_file
def IsEmpty(self):
return self.name == CONTAINER_NAME_EMPTY
@staticmethod
def Empty():
"""Returns a placeholder Container that should be read-only.
For simplicity, we're not enforcing read-only checks (frozenmap does not
exist, unfortunately). Creating a new instance instead of using a global
singleton for robustness.
"""
return Container(name=CONTAINER_NAME_EMPTY,
metadata={},
section_sizes={},
metrics_by_file={})
class DeltaContainer(BaseContainer):
"""Delta version of Container."""
__slots__ = (
'before',
'after',
)
def __init__(self, before, after):
super().__init__()
self.before = before
self.after = after
@property
def name(self):
return self.after.name if self.before.IsEmpty() else self.before.name
@property
def section_sizes(self):
ret = collections.Counter(self.after.section_sizes)
ret.update({k: -v for k, v in self.before.section_sizes.items()})
return dict(ret)
@property
def metrics_by_file(self):
keys = (set(self.before.metrics_by_file.keys())
| set(self.after.metrics_by_file.keys()))
ret = {}
for key in keys:
before_contents = self.before.metrics_by_file.get(key, {})
after_contents = self.after.metrics_by_file.get(key, {})
delta_contents = collections.Counter(after_contents)
delta_contents.update({k: -v for k, v in before_contents.items()})
ret[key] = dict(delta_contents)
return ret
class BaseSizeInfo:
"""Base class for SizeInfo and DeltaSizeInfo.
Fields:
containers: A list of Containers.
raw_symbols: A SymbolGroup containing all top-level symbols (no groups).
symbols: A SymbolGroup of all symbols, where symbols have been
grouped by full_name (where applicable). May be re-assigned when it is
desirable to show custom groupings while still printing containers.
native_symbols: Subset of |symbols| that are from native code.
pak_symbols: Subset of |symbols| that are from pak files.
"""
__slots__ = (
'containers',
'raw_symbols',
'_symbols',
'_native_symbols',
'_pak_symbols',
)
def __init__(self, containers, raw_symbols, symbols=None):
if isinstance(raw_symbols, list):
raw_symbols = SymbolGroup(raw_symbols)
self.containers = containers
self.raw_symbols = raw_symbols
self._symbols = symbols
self._native_symbols = None
self._pak_symbols = None
BaseContainer.AssignShortNames(self.containers)
@property
def symbols(self):
if self._symbols is None:
logging.debug('Clustering symbols')
self._symbols = self.raw_symbols._Clustered()
logging.debug('Done clustering symbols')
return self._symbols
@symbols.setter
def symbols(self, value):
self._symbols = value
@property
def native_symbols(self):
if self._native_symbols is None:
# Use self.symbols rather than raw_symbols here so that _Clustered()
# is not performed twice (slow) if accessing both properties.
self._native_symbols = self.symbols.WhereIsNative()
return self._native_symbols
@property
def pak_symbols(self):
if self._pak_symbols is None:
self._pak_symbols = self.raw_symbols.WhereIsPak()
return self._pak_symbols
@property
def section_sizes(self):
ret = collections.Counter()
for c in self.containers:
ret.update(c.section_sizes)
return dict(ret)
def ContainerForName(self, name, default=None):
return next((c for c in self.containers if c.name == name), default)
class SizeInfo(BaseSizeInfo):
"""Represents all size information for a single binary.
Fields:
size_path: Path to .size file this was loaded from (or None).
is_sparse: Whether the list of symbols is sparse.
build_config: A dict of build configurations.
"""
__slots__ = (
'build_config',
'size_path',
'is_sparse',
)
def __init__(self,
build_config,
containers,
raw_symbols,
symbols=None,
size_path=None,
is_sparse=False):
super().__init__(containers, raw_symbols, symbols=symbols)
self.build_config = build_config
self.size_path = size_path
self.is_sparse = is_sparse
@property
def metadata_legacy(self):
"""Return |container[0].metadata| fused with |build_config|.
Supported only if there is one Container.
"""
assert len(self.containers) == 1
metadata = self.containers[0].metadata.copy()
for k, v in self.build_config.items():
assert k not in metadata
metadata[k] = v
return metadata
def MakeSparse(self, filtered_symbols):
"""Make this SizeInfo contain only a subset of symbols.
Args:
filtered_symbols: Which symbols to include.
"""
self.is_sparse = True
# Any aliases of sparse symbols must also be included, or else file
# parsing will attribute symbols that happen to follow an incomplete alias
# group to that alias group.
representative_symbols = set()
raw_symbols = []
logging.debug('Expanding filtered_symbols aliases')
for sym in filtered_symbols:
if sym.aliases:
num_syms = len(representative_symbols)
representative_symbols.add(sym.aliases[0])
if num_syms < len(representative_symbols):
raw_symbols.extend(sym.aliases)
else:
raw_symbols.append(sym)
logging.debug('Done expanding filtered_symbols')
self.raw_symbols = SymbolGroup(raw_symbols)
class DeltaSizeInfo(BaseSizeInfo):
"""What you get when you Diff() two SizeInfo objects.
Fields:
before: SizeInfo for "before".
after: SizeInfo for "after".
removed_sources: List of removed source files from "before".
added_sources: List of added source files from "after".
"""
__slots__ = (
'before',
'after',
'removed_sources',
'added_sources',
)
def __init__(self,
before,
after,
containers,
raw_symbols,
removed_sources=None,
added_sources=None):
super().__init__(containers, raw_symbols)
self.before = before
self.after = after
self.removed_sources = removed_sources or []
self.added_sources = added_sources or []
@property
def is_sparse(self):
return self.before.is_sparse or self.after.is_sparse
def MergeDeltaSizeInfo(self, other):
assert isinstance(other, DeltaSizeInfo), 'Found ' + type(other)
# The list of adds/removes might not be accurate anymore, so remove them.
# They could be re-computed if the need arises.
self.removed_sources = []
self.added_sources = []
# Assumes BUILD_CONFIG_GIT_REVISION is always present.
i = 1
while f'Merged{i}_{BUILD_CONFIG_GIT_REVISION}' in self.after.build_config:
i += 1
prefix = f'Merged{i}'
# TODO(agrieve): Merge container metadata & metrics_by_file.
for k, v in other.before.build_config.items():
self.before.build_config[f'{prefix}_{k}'] = v
for k, v in other.after.build_config.items():
self.after.build_config[f'{prefix}_{k}'] = v
for other_c in other.containers:
match = self.ContainerForName(other_c.name)
if match is None:
match = other_c
self.containers.append(other_c)
else:
if match.before.IsEmpty() and not other_c.before.IsEmpty():
match.before = other_c.before
if match.after.IsEmpty() and not other_c.after.IsEmpty():
match.after = other_c.after
if match.before not in self.before.containers:
self.before.containers.append(match.before)
if match.after and match.after not in self.after.containers:
self.after.containers.append(match.after)
BaseContainer.AssignShortNames(self.before.containers)
BaseContainer.AssignShortNames(self.after.containers)
BaseContainer.AssignShortNames(self.containers)
# Not updating symbol container references because doing so is not currently
# necessary.
self.raw_symbols += other.raw_symbols
self.before.raw_symbols += other.before.raw_symbols
self.after.raw_symbols += other.after.raw_symbols
def MakeSparse(self, filtered_symbols=None):
"""Make this DeltaSizeInfo contain only a subset of symbols.
Args:
filtered_symbols: Which symbols to include. Defaults to changed symbols.
"""
logging.info('Converting to sparse diff')
if filtered_symbols is None:
filtered_symbols = self.raw_symbols.WhereDiffStatusIs(
DIFF_STATUS_UNCHANGED).Inverted()
self.raw_symbols = filtered_symbols
self.before.MakeSparse(
SymbolGroup([
sym.before_symbol for sym in filtered_symbols if sym.before_symbol
]))
self.after.MakeSparse(
SymbolGroup(
[sym.after_symbol for sym in filtered_symbols if sym.after_symbol]))
class BaseSymbol:
"""Base class for Symbol and SymbolGroup."""
__slots__ = ()
@property
def container(self):
pass
@property
def section_name(self):
pass
@property
def size(self):
pass
@property
def padding(self):
pass
@property
def address(self):
pass
@property
def flags(self):
pass
@property
def aliases(self):
pass
@property
def full_name(self):
pass
@property
def name(self):
pass
@property
def container_name(self):
return self.container.name if self.container else ''
@property
def container_short_name(self):
return self.container.short_name if self.container else ''
@property
def section(self):
"""Returns the one-letter section."""
return SECTION_NAME_TO_SECTION[self.section_name]
@property
def size_without_padding(self):
return self.size - self.padding
@property
def end_address(self):
return self.address + self.size_without_padding
@property
def is_anonymous(self):
return bool(self.flags & FLAG_ANONYMOUS)
@property
def generated_source(self):
return bool(self.flags & FLAG_GENERATED_SOURCE)
@generated_source.setter
def generated_source(self, value):
if value:
self.flags |= FLAG_GENERATED_SOURCE
else:
self.flags &= ~FLAG_GENERATED_SOURCE
@property
def num_aliases(self):
return len(self.aliases) if self.aliases else 1
def FlagsString(self):
# Most flags are 0.
flags = self.flags
if not flags:
return '{}'
parts = []
if flags & FLAG_ANONYMOUS:
parts.append('anon')
if flags & FLAG_STARTUP:
parts.append('startup')
if flags & FLAG_UNLIKELY:
parts.append('unlikely')
if flags & FLAG_REL:
parts.append('rel')
if flags & FLAG_REL_LOCAL:
parts.append('rel.loc')
if flags & FLAG_GENERATED_SOURCE:
parts.append('gen')
if flags & FLAG_CLONE:
parts.append('clone')
if flags & FLAG_HOT:
parts.append('hot')
if flags & FLAG_COVERED:
parts.append('covered')
if flags & FLAG_UNCOMPRESSED:
parts.append('uncompressed')
return '{%s}' % ','.join(parts)
def IsArsc(self):
return self.section_name == SECTION_ARSC
def IsBss(self):
return self.section_name in BSS_SECTIONS
def IsDex(self):
return self.section_name in DEX_SECTIONS
def IsOther(self):
return self.section_name == SECTION_OTHER
def IsPak(self):
return self.section_name in PAK_SECTIONS
def IsNative(self):
return self.section_name in NATIVE_SECTIONS
def IsOverhead(self):
return self.full_name.startswith('Overhead: ')
def IsGroup(self):
return False
def IsDelta(self):
return False
def IsGeneratedByToolchain(self):
return '.' in self.name or (
self.name.endswith(']') and not self.name.endswith('[]'))
def IsStringLiteral(self):
# String literals have names like "string" or "very_long_str[...]", while
# non-ASCII strings are named STRING_LITERAL_NAME.
return self.full_name.startswith(
'"') or self.full_name == STRING_LITERAL_NAME
# Used for diffs to know whether or not it is accurate to consider two symbols
# with the same name as being the same.
def IsNameUnique(self):
return not (self.IsStringLiteral() or # "string literal"
self.IsOverhead() or # "Overhead: APK File"
self.full_name.startswith('*') or # "** outlined symbol"
(self.IsNative() and '.' in self.full_name)) # ".L__unnamed_11"
def IterLeafSymbols(self):
yield self
class Symbol(BaseSymbol):
"""Represents a single symbol within a binary."""
__slots__ = ('address', 'full_name', 'template_name', 'name', 'flags',
'object_path', 'aliases', 'padding', 'container', 'section_name',
'source_path', 'size', 'component', 'disassembly')
def __init__(self,
section_name,
size_without_padding,
address=None,
full_name=None,
template_name=None,
name=None,
source_path=None,
object_path=None,
flags=0,
aliases=None,
disassembly=None):
self.section_name = section_name
self.address = address or 0
self.full_name = full_name or ''
self.template_name = template_name or ''
self.name = name or ''
self.source_path = source_path or ''
self.object_path = object_path or ''
self.size = size_without_padding
self.flags = flags
self.aliases = aliases
self.padding = 0
self.container = None
self.component = ''
self.disassembly = disassembly or ''
def __repr__(self):
if self.container_name:
container_str = '<{}>'.format(self.container_name)
else:
container_str = ''
template = ('{}{}@{:x}(size_without_padding={},padding={},full_name={},'
'object_path={},source_path={},flags={},num_aliases={},'
'component={})')
return template.format(container_str, self.section_name, self.address,
self.size_without_padding, self.padding,
self.full_name, self.object_path, self.source_path,
self.FlagsString(), self.num_aliases, self.component)
def SetName(self, full_name, template_name=None, name=None):
# Note that _NormalizeNames() will clobber these values.
self.full_name = full_name
self.template_name = full_name if template_name is None else template_name
self.name = full_name if name is None else name
@property
def pss(self):
return float(self.size) / self.num_aliases
@property
def pss_without_padding(self):
return float(self.size_without_padding) / self.num_aliases
@property
def padding_pss(self):
return float(self.padding) / self.num_aliases
class DeltaSymbol(BaseSymbol):
"""Represents a changed symbol.
PSS is not just size / num_aliases, because aliases information is not
directly tracked. It is not directly tracked because a symbol may be an alias
to one symbol in the |before|, and then be an alias to another in |after|.
"""
__slots__ = ('before_symbol', 'after_symbol')
def __init__(self, before_symbol, after_symbol):
self.before_symbol = before_symbol
self.after_symbol = after_symbol
def __repr__(self):
before_container_name = (self.before_symbol.container_name
if self.before_symbol else None)
after_container_name = (self.after_symbol.container_name
if self.after_symbol else None)
if after_container_name:
if before_container_name != after_container_name:
container_str = '<~{}>'.format(after_container_name)
else:
container_str = '<{}>'.format(after_container_name)
else: # None or ''.
container_str = ''
template = ('{}{}{}@{:x}(size_without_padding={},padding={},full_name={},'
'object_path={},source_path={},flags={})')
return template.format(DIFF_PREFIX_BY_STATUS[self.diff_status],
container_str, self.section_name, self.address,
self.size_without_padding, self.padding,
self.full_name, self.object_path, self.source_path,
self.FlagsString())
def IsDelta(self):
return True
@property
def diff_status(self):
if self.before_symbol is None:
return DIFF_STATUS_ADDED
if self.after_symbol is None:
return DIFF_STATUS_REMOVED
# Use delta size and delta PSS as indicators of change. Delta size = 0 with
# delta PSS != 0 can be caused by:
# (1) Alias addition / removal without actual binary change.
# (2) Alias merging / splitting along with binary changes, where matched
# symbols all happen the same size (hence delta size = 0).
# The purpose of checking PSS is to account for (2). However, this means (1)
# would produce much more diffs than before!
if self.size != 0 or self.pss != 0:
return DIFF_STATUS_CHANGED
return DIFF_STATUS_UNCHANGED
@property
def address(self):
return self.after_symbol.address if self.after_symbol else 0
@property
def full_name(self):
return (self.after_symbol or self.before_symbol).full_name
@property
def template_name(self):
return (self.after_symbol or self.before_symbol).template_name
@property
def name(self):
return (self.after_symbol or self.before_symbol).name
@property
def flags(self):
# Compute the union of flags (|) instead of symmetric difference (^), as
# that is more useful when querying for symbols with flags.
before_flags = self.before_symbol.flags if self.before_symbol else 0
after_flags = self.after_symbol.flags if self.after_symbol else 0
return before_flags | after_flags
@property
def object_path(self):
return (self.after_symbol or self.before_symbol).object_path
@property
def source_path(self):
return (self.after_symbol or self.before_symbol).source_path
@property
def aliases(self):
return None
@property
def container(self):
return (self.after_symbol or self.before_symbol).container
@property
def section_name(self):
return (self.after_symbol or self.before_symbol).section_name
@property
def component(self):
return (self.after_symbol or self.before_symbol).component
@property
def padding_pss(self):
if self.after_symbol is None:
return -self.before_symbol.padding_pss
if self.before_symbol is None:
return self.after_symbol.padding_pss
# Padding tracked in aggregate, except for padding-only symbols.
if self.before_symbol.size_without_padding == 0:
return self.after_symbol.padding_pss - self.before_symbol.padding_pss
return 0
@property
def padding(self):
if self.after_symbol is None:
return -self.before_symbol.padding
if self.before_symbol is None:
return self.after_symbol.padding
# Padding tracked in aggregate, except for padding-only symbols.
if self.before_symbol.size_without_padding == 0:
return self.after_symbol.padding - self.before_symbol.padding
return 0
@property
def pss(self):
if self.after_symbol is None:
return -self.before_symbol.pss
if self.before_symbol is None:
return self.after_symbol.pss
# Padding tracked in aggregate, except for padding-only symbols.
if self.before_symbol.size_without_padding == 0:
return self.after_symbol.pss - self.before_symbol.pss
return (self.after_symbol.pss_without_padding -
self.before_symbol.pss_without_padding)
@property
def size(self):
if self.after_symbol is None:
return -self.before_symbol.size
if self.before_symbol is None:
return self.after_symbol.size
# Padding tracked in aggregate, except for padding-only symbols.
if self.before_symbol.size_without_padding == 0:
return self.after_symbol.padding - self.before_symbol.padding
return (self.after_symbol.size_without_padding -
self.before_symbol.size_without_padding)
@property
def pss_without_padding(self):
return self.pss - self.padding_pss
class SymbolGroup(BaseSymbol):
"""Represents a group of symbols using the same interface as Symbol.
SymbolGroups are immutable. All filtering / sorting will return new
SymbolGroups objects.
Overrides many __functions__. E.g. the following are all valid:
* len(group)
* iter(group)
* group[0]
* group['0x1234'] # By symbol address
* without_group2 = group1 - group2
* unioned = group1 + group2
"""
__slots__ = (
'_padding',
'_size',
'_pss',
'_symbols',
'_filtered_symbols',
'full_name',
'template_name',
'name',
'section_name',
'is_default_sorted', # True for groups created by Sorted()
)
# template_name and full_name are useful when clustering symbol clones.
def __init__(self,
symbols,
filtered_symbols=None,
full_name=None,
template_name=None,
name='',
section_name=None,
is_default_sorted=False):
assert isinstance(symbols, list) # Rejects non-reusable generators.
self._padding = None
self._size = None
self._pss = None
self._symbols = symbols
self._filtered_symbols = filtered_symbols or []
self.full_name = full_name if full_name is not None else name
self.template_name = template_name if template_name is not None else name
self.name = name or ''
self.section_name = section_name or SECTION_MULTIPLE
self.is_default_sorted = is_default_sorted
def __repr__(self):
return 'Group(full_name=%s,count=%d,size=%d)' % (
self.full_name, len(self), self.size)
def __iter__(self):
return iter(self._symbols)
def __len__(self):
return len(self._symbols)
def __eq__(self, other):
return isinstance(other, SymbolGroup) and self._symbols == other._symbols
def __contains__(self, sym):
return sym in self._symbols
def __getitem__(self, key):
"""|key| can be an index or an address.
Raises if multiple symbols map to the address.
"""
if isinstance(key, slice):
return self._CreateTransformed(self._symbols.__getitem__(key))
if isinstance(key, str) or key > len(self._symbols):
found = self.WhereAddressInRange(key)
if len(found) != 1:
raise KeyError('%d symbols found at address %s.' % (len(found), key))
return found[0]
return self._symbols[key]
def __sub__(self, other):