-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdu_obj.py
More file actions
executable file
·1366 lines (1256 loc) · 40.1 KB
/
Copy pathdu_obj.py
File metadata and controls
executable file
·1366 lines (1256 loc) · 40.1 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
#!/usr/bin/env python3
from __future__ import print_function
"Analyze debug info and report .text size contribution per directory/file/line"
import argparse, os, re, subprocess, sys, datetime, struct, difflib, json
take_off = datetime.datetime.now()
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--input", "-i", action='append', help="Input executable file")
parser.add_argument(
"--output", "-o", help="Output file")
parser.add_argument(
"--thorough", action='store_true',
help="Disregard line entry sizes, resolve every single byte!")
parser.add_argument(
"--verbose", "-v", action='store_true', help='Verbose')
parser.add_argument(
"--file", "-f", action='store_true',
help="""\
Line mode: print annotated contents of every file
(unnamed args must be file paths)
Use --git to get file list from git
""")
parser.add_argument(
"--instructions", "-g", action="store_true",
help="Print disassembled instructions under each line (implies -f)")
parser.add_argument(
"--unknown", action="store_true",
help="Try to resolve symbols for unresolvable locations")
parser.add_argument(
"--map", "-m", action="append", help="Parse link map")
parser.add_argument(
"--bydest", action="store_true", help="By destination section")
parser.add_argument(
"--idebug", action="store_true", help="Include debug sections")
parser.add_argument(
"--expand", "-x", action="append",
help="Hanlde object/lib names containing substring as separate sources")
parser.add_argument(
"--git", help="Get file list + contents from REVISION (-f)")
parser.add_argument(
"--calls", action="store_true", help="Get function calls (non virtual)")
parser.add_argument(
"--ctms", help="Call target maximum size")
parser.add_argument(
"--functions", action="store_true",
help="Get function symbol sizes and repeat counts")
parser.add_argument(
"--all", action="store_true", help="Print symbol data")
parser.add_argument(
"--data", action="store_true", help="Print non code symbols")
parser.add_argument("--ds", action="store_true", help="Dump symbols")
parser.add_argument(
"--sfp", action="store_true",
help="Print function that use push bp/mov bp, sp")
parser.add_argument(
"--types", "-T", action="store_true", help="Print type member layout")
parser.add_argument(
"--longtype", "-L", action="store_true",
help="Print type member layout as path expressions")
parser.add_argument(
"--onlybases", action="store_true", help="Print only bases")
parser.add_argument(
"--containing", "-I", action="store_true",
help="List all types whose names contain PREFIX")
parser.add_argument(
"--derived", "-d", action="store_true",
help="List all classes derived from PREFIX (1 arg)")
parser.add_argument(
"--md", action="store_true",
help="List all classes multiply derived from PREFIX (1 arg)")
parser.add_argument(
"--target", "-t", action="store_true",
help="TODO Find paths to targets in a call graph")
parser.add_argument(
"--show", action="store_true",
help="Print as much as possible debug info re: given line")
parser.add_argument(
"--diff", action="store_true", help="Compare section sizes (2 args)")
parser.add_argument(
"--info", action="store_true",
help="Print some data about debuginfo files")
parser.add_argument(
"--match", help="match debuginfo files to this file")
parser.add_argument(
"--f1", action="store_true",
help="Show files saved to -features_dir directory\
(-use_counters=0, 1 feature per PC)")
parser.add_argument(
"--features", "-F", action="store_true",
help="Show files saved to -features_dir directory\
(-use_counters=1, 8 features per PC)")
parser.add_argument(
"--pid", "-p", help="For --features: read counter values from a process")
parser.add_argument(
"--lldb", "-P", help="Path to lldb")
parser.add_argument(
"PREFIX", nargs="*",
help="Dir or file paths to count the code size for each")
args = parser.parse_args()
if args.lldb:
dir = subprocess.check_output([args.lldb, "-P"]).strip().decode()
print("Adding '%s'..." % dir)
sys.path.append(dir)
try:
import lldb
# SBError = lldb.SBError
from lldb import SBError
except ImportError:
if sys.platform.startswith("linux"):
importDirs = [
"/usr/lib/llvm-18/lib/python3.12/site-packages",
"/usr/lib/python2.7/dist-packages/lldb-3.8"]
else:
importDirs = ["\
/Library/Developer/CommandLineTools/Library/PrivateFrameworks/\
LLDB.framework/Resources/Python"]
print("Adding %s..." % (importDirs))
sys.path += importDirs
import lldb
from lldb import SBError
def nn(n):
return ",".join(re.findall(r"\d{1,3}", str(n)[::-1]))[::-1]
def xx(n):
n = "%X" % n
return ",".join(re.findall(r"[0-9a-fA-F]{1,4}", n[::-1]))[::-1]
def printComparison(s1, s2, name):
print(" %24s %s" % (
"%s(%s%s)" % (
nn(s1), (s2 > s1) and "+" or "-", nn(s2-s1)), name))
class Count:
__slots__ = ("name", "size", "occurences")
def __init__(self, value):
self.name = value
self.occurences = self.size = 0
def __lt__(self, other):
return self.size < other.size
class EntryFromBlock:
def __init__(self, block):
self.file = block.GetInlinedCallSiteFile()
self.line = block.GetInlinedCallSiteLine()
def IsValid(self):
return True
class Input:
def __init__(self, path, args):
self.path = path
self.args = args
self.error = lldb.SBError()
self.cs = None
self.sectionsDumped = False
d = lldb.SBDebugger.Create()
if self.args.verbose:
d.EnableLog("lldb", ["symbol"])
self.target = self.check(
d.CreateTarget(self.path, None, None, False, self.error))
self.module = self.target.GetModuleAtIndex(0)
pdb = self.path + ".pdb"
if not os.path.isfile(pdb):
pdb = re.sub("[.](dll|exe)$", ".pdb", self.path)
if pdb != self.path:
d.HandleCommand("target symbols add %s" % pdb)
if os.path.realpath(self.module.GetSymbolFileSpec().fullpath) !=\
os.path.realpath(pdb):
raise Exception("Symbol file path must be '%s' but is '%s'" % (
pdb, self.module.GetSymbolFileSpec().fullpath))
# This is needed for ResolveLoadAddress to work
sec = self.getCodeSection()
self.target.SetSectionLoadAddress(sec, sec.GetFileAddress())
sys.stderr.write("Module='%s' %d symbols in '%s' %d CUs\n" % (
self.module.GetFileSpec(),
self.module.GetNumSymbols(),
self.module.GetSymbolFileSpec(),
self.module.GetNumCompileUnits()))
# HACK & WORKAROUND!
# Without reading compile_units GetOrCreateCompiland doesn't get called
# and all the returned LineEntries are invalid on Windows targets!
for u in self.module.compile_units:
if 0 and self.args.verbose and u.file.IsValid():
print("CU path=%s" % (u.file.fullpath))
if self.args.verbose:
self.dumpSections()
def check(self, result):
if self.error.fail:
raise Exception(str(self.error))
return result
def getSubSections(self, sec):
for i in range(sec.GetNumSubSections()):
yield sec.GetSubSectionAtIndex(i)
for t in self.getSubSections(sec.GetSubSectionAtIndex(i)):
yield t
def getAllSections(self):
# "for sec in self.module.section" yields None sometimes
for i in range(self.module.GetNumSections()):
yield self.module.GetSectionAtIndex(i)
for u in self.getSubSections(self.module.GetSectionAtIndex(i)):
yield u
def dumpSections(self):
if self.sectionsDumped:
return
for sec in self.getAllSections():
self.printSec(sec)
self.sectionsDumped = True
def compareSections(self, other):
map1, map2 = {}, {}
names = []
for sec in self.getAllSections():
map1[sec.name] = sec
if sec.name in names:
print("Duplicate section '%s'" % sec.name)
names.append(sec.name)
for sec in other.getAllSections():
map2[sec.name] = sec
if sec.name in names:
continue
names.append(sec.name)
for name in names:
s1, s2 = (
m.get(name) and m.get(name).GetFileByteSize() or 0 for
m in (map1, map2))
printComparison(s1, s2, name)
def getCodeSection(self):
if self.cs:
return self.cs
for sec in self.getAllSections():
if sec.name == ".text" or sec.name == "__TEXT":
if self.cs:
self.printSec(sec)
self.printSec(self.cs)
raise KeyError("Too many .text sections!")
self.cs = sec
if not self.cs:
self.dumpSections()
raise KeyError("No .text section!")
return self.cs
def getSecContent(self, name):
sec = self.module.FindSection(name)
return self.check(sec.GetSectionData().ReadRawData(
self.error, 0, sec.GetFileByteSize()))
def getCodeSize(self):
return self.getCodeSection().GetFileByteSize()
def getFileSize(self):
return os.stat(self.path).st_size
def printSec(self, sec):
sys.stderr.write(
"%s: '%s' GetPermissions()=%X GetFileByteSize()=%s\n" % (
os.path.basename(self.path), sec.GetName(),
sec.GetPermissions(),
nn(sec.GetFileByteSize())))
def run(self, up):
if self.args.containing or self.args.derived or self.args.md or\
self.args.longtype or self.args.onlybases:
self.args.types = True
if self.args.types:
return self.printTypes(self.args.PREFIX)
# GetStartAddress()/GetEndAddress() can be .o section addresses
# before link, so only their difference is useful
text = self.getCodeSection()
addr = lldb.SBAddress(text, 0)
while addr.GetOffset() < text.GetFileByteSize():
c = addr.GetSymbolContext(
lldb.eSymbolContextLineEntry | lldb.eSymbolContextBlock |
lldb.eSymbolContextCompUnit)
e = c.GetLineEntry()
if 0:
print("%016X %s:%d" % (
addr.GetOffset(), e.GetFileSpec(), e.GetLine()))
size = 1
if e.IsValid() and not self.args.thorough:
size = e.GetEndAddress().GetOffset() -\
e.GetStartAddress().GetOffset()
# if c.comp_unit.IsValid():
# pass
if e.IsValid():
up.processEntry(e, size, self, addr)
up.entries.size += 1
else:
up.unknown.size += size
if self.args.unknown:
up.processUnknown(addr, size)
block = c.block
while block.IsValid():
if block.GetInlinedCallSiteFile().IsValid():
up.processEntry(EntryFromBlock(block), size, self, addr)
up.inlineEntries.size += 1
block = block.GetParent()
addr.OffsetAddress(size)
up.progress(size)
sys.stderr.write(" " * 40 + "\r")
return self
def run2(self, up):
for u in self.module.compile_unit:
for e in u:
if not e.IsValid():
raise ValueError("not e.IsValid()")
size = e.GetEndAddress().GetOffset() -\
e.GetStartAddress().GetOffset()
up.processEntry(e, size, self, None)
up.progress(size)
def printFields(self, prefix, deriveds, offset, type):
bases = [
type.GetDirectBaseClassAtIndex(i)
for i in range(type.GetNumberOfDirectBaseClasses())]
# Location of virtual base is determined by most derived class,
# virtual bases of bases are not present in final layout.
# If we have a virtual base, all derived classes contain it too
# TODO:
# The class that declares ": public virtual" has the base in
# the direct bases for some reason - although the offsets are
# used by other fields in bases. Need to filter that out
fields = []
if not self.args.onlybases:
for i in range(type.num_fields):
fl = type.GetFieldAtIndex(i)
fl.isVirt = ""
fl.deriveds = []
fields.append(fl)
if not deriveds:
for i in range(type.GetNumberOfVirtualBaseClasses()):
vb = type.GetVirtualBaseClassAtIndex(i)
vb.isVirt = "(v)";
vb.deriveds = []
fields.append(vb)
for fl in bases:
fl.isVirt = "";
fl.deriveds = deriveds + [type]
for fl in sorted(fields + bases, key=lldb.SBTypeMember.GetOffsetInBytes):
self.printOneField(prefix, fl.deriveds, offset, fl)
def printOneField(self, prefix, nds, offset, fl):
name = fl.name
ft = fl.GetType().GetCanonicalType()
if ft.name and name and name != ft.name:
name = "%s %s" % (ft.name, name)
if name:
name += fl.isVirt
start = offset + fl.GetOffsetInBytes()
if self.args.longtype:
prefix = "%s.%s" % (prefix, name)
print("%d-%d %s" % (start, start + ft.size, prefix))
self.printFields(prefix, nds, start, ft)
return
print("%s%-8s %s" % (
prefix, "%d-%d" % (start, start + ft.size), name))
self.printFields(prefix + "-", nds, start, ft)
def getDerivationPath(self, type, baseName, includeVirt=True):
# Include type itself so we see if the name can't be found
if type.name == baseName:
return [type]
for i in range(type.GetNumberOfDirectBaseClasses()):
bt = type.GetDirectBaseClassAtIndex(i).GetType().GetCanonicalType()
dp = self.getDerivationPath(bt, baseName)
if dp:
return dp + [type]
if not includeVirt:
return
for i in range(type.GetNumberOfVirtualBaseClasses()):
bt = type.GetVirtualBaseClassAtIndex(i).GetType().GetCanonicalType()
if bt.name == baseName:
return [bt, type]
def getForkedDerivationPaths(self, type, baseName):
if type.name == baseName:
return [[type]]
for i in range(type.GetNumberOfDirectBaseClasses()):
bt = type.GetDirectBaseClassAtIndex(i).GetType().GetCanonicalType()
p = self.getDerivationPath(bt, baseName, includeVirt=False)
if p:
yield p
def printTypes(self, strings):
if self.args.derived and len(strings) != 1:
raise Exception("Only 1 class name supported for --derived")
if self.args.md and len(strings) != 1:
raise Exception("Only 1 class name supported for --md")
printed = set()
if not (self.args.containing or self.args.derived or self.args.md):
for name in strings:
for t in self.module.FindTypes(name):
self.printOneType(t, printed, needFields=True)
return
for i in range(self.module.GetNumCompileUnits()):
u = self.module.GetCompileUnitAtIndex(i)
sys.stdout.write("\rCU %d/%d..." % (
i, self.module.GetNumCompileUnits()))
sys.stdout.flush()
for t in u.GetTypes():
if t.IsPointerType() or t.IsReferenceType() or t.size == 0:
continue
# Go from typedef name to real name
t = t.GetCanonicalType()
if self.args.derived:
dp = self.getDerivationPath(t, strings[0])
if dp:
self.printOneType(t, printed, dp=dp[:-1])
continue
if self.args.md:
dp = list(self.getForkedDerivationPaths(t, strings[0]))
if len(dp) > 1:
self.printOneType(t, printed, dps=dp)
continue
for st in strings:
found = st in t.name
if found:
self.printOneType(t, printed, needFields=True)
break
def wasTypePrinted(self, t, printed):
k = "%d:%s" % (t.size, t.name)
if k in printed:
return True
printed.add(k)
return False
def printOneType(self, t, printed, dp=[], needFields=False, dps=[]):
if self.wasTypePrinted(t, printed):
return
dpNames = "".join([(y.name + "/") for y in dp])
print("\rsize=%4d %s%s" % (t.size, dpNames, t.name))
for dp in dps:
print(" " + "".join([(y.name + "/") for y in dp]))
if needFields:
self.printFields("+", [], 0, t)
def descAddr(self, addr):
return "%s:%016X" % (
addr.GetSection().GetName(), addr.GetOffset())
def dumpEntry(self, e, addr):
sys.stderr.write(
"Entry at %016X: %s-%016X (%d bytes) %s:%d\n" % (
addr.GetOffset(), self.descAddr(e.GetStartAddress()),
e.GetEndAddress().GetOffset(),
e.GetEndAddress().GetOffset() - e.GetStartAddress().GetOffset(),
e.GetFileSpec(), e.GetLine()))
def getSymbols(self, context):
for s in self.module.symbols:
context.symbols.size += 1
if s.GetStartAddress().IsValid():
isFunc = int(s.GetStartAddress().GetSection().name == ".text")
context.functions.size += isFunc
if self.args.data:
if not isFunc:
context.processSymbol(s)
elif self.args.all or isFunc:
context.processSymbol(s)
else:
context.noAddress.size += 1
def getInstructions(self, context):
text = self.getCodeSection()
addr = lldb.SBAddress(text, 0)
while addr.GetOffset() < text.GetFileByteSize():
size = 0
code = self.target.ReadInstructions(addr, 100)
for ins in code:
context.processInstruction(ins, self)
size += ins.GetByteSize()
if size == 0:
size = 1 # idk?
addr.OffsetAddress(size);
context.progress(size)
def printContent(self, path, line):
for i in range(self.module.GetNumCompileUnits()):
cu = self.module.GetCompileUnitAtIndex(i)
if not path:
print(cu.GetFileSpec())
continue
# A CU has its path but it can contain line entries
# from other paths
# pp = str(cu.GetFileSpec()).split("/@/")[0]
self.printCu(cu, path, line)
def printCu(self, cu, path, line):
cuDataPrinted = False
if not line:
print("CU %s %s line entries" % (
cu.GetFileSpec(), cu.GetNumLineEntries()))
blocks = {}
for jj in range(cu.GetNumLineEntries()):
ee = cu.GetLineEntryAtIndex(jj)
if (str(ee.GetFileSpec()).endswith(path)) and\
(ee.GetLine() == line or line is None):
start = ee.GetStartAddress()
end = ee.GetEndAddress()
if line and not cuDataPrinted:
print("CU %s %s line entries" % (
cu.GetFileSpec(), cu.GetNumLineEntries()))
cuDataPrinted = True
print("LE %s-%s at %s:%s" % (
start.offset, end.offset,
ee.GetFileSpec(), ee.GetLine()))
bb = self.check(self.target.ReadMemory(
start, end.offset - start.offset, self.error))
ii = self.target.GetInstructions(start, bb)
for inn in ii:
print(inn)
blocks[describeBlock(start.block)] = start.block
for bl in blocks.values():
self.printBlock(bl)
def printBlock(self, bl):
level = 0
pb = bl.parent
# pb = bl.GetContainingInlinedBlock()
if pb.IsValid():
level = self.printBlock(pb) + 1
print("%sblock %s '%s'" % (
" " * level, describeBlock(bl), bl.GetInlinedName()))
return level
def describeBlock(bl):
return " ".join("%s-%s" % (
bl.GetRangeStartAddress(i).offset,
bl.GetRangeEndAddress(i).offset) for
i in range(bl.GetNumRanges()))
class FileSpecAndPrefixes:
def __init__(self):
self.spec = self.prefixes = None
class KeyFromSpec:
def __init__(self, context, spec):
self.context = context
self.spec = spec
def getPath(self):
return "%s/%s" % (
self.context.normalizePath(self.spec.GetDirectory()),
self.spec.GetFilename())
class Context:
__slots__ = (
"args", "other", "unknown", "accounted", "allCode", "allFiles",
"badSymbols", "processedBytes", "progressNext", "base",
"noSymbols", "symbols", "entries", "inlineEntries",
"prefixes", "index", "last", "output")
def __init__(self, args):
self.args = args
self.other = Count("<other>")
self.unknown = Count("<unknown>")
self.accounted = Count("<accounted>")
self.allCode = Count("<all code>")
self.allFiles = Count("<all files>")
self.badSymbols = Count("<bad symbols>")
self.output = None
self.processedBytes = 0
self.progressNext = 0
basePath = self.args.output and\
os.path.dirname(self.args.output) or os.getcwd()
self.base = basePath.split(os.sep)[-1]
self.noSymbols = Count("<no symbols>")
self.symbols = {}
self.entries = Count("<entries>")
self.inlineEntries = Count("<inline>")
if self.args.verbose:
print("LLDB version = '%s'" % lldb.SBDebugger.GetVersionString())
def progress(self, size):
self.processedBytes += size
if self.processedBytes <= self.progressNext:
return
sys.stderr.write(" %16s / %16s (%3d%%)" % (
nn(self.processedBytes), nn(self.allCode.size),
self.processedBytes * 100 / self.allCode.size))
if not self.args.calls:
sys.stderr.write(" %s=%16s" % (
self.args.unknown and "no symbols" or "other",
self.args.unknown and nn(self.noSymbols.size) or\
nn(self.other.size)))
sys.stderr.write(" unknown=%16s\r" % nn(self.unknown.size))
self.progressNext += 2048
def prepare(self, inputs):
self.prefixes = []
self.index = {}
self.last = FileSpecAndPrefixes()
for p in self.args.PREFIX:
parts = self.getParts(p)
c = Count("/".join(parts))
self.prefixes += [c]
for key in self.getPrefixStrings(parts):
self.index[key] = c
def getPrefixStrings(self, parts):
if not parts:
return
s = parts[0]
yield s
for p in parts[1:]:
s += "/" + p
yield s
def run(self):
if not self.args.input:
sys.stderr.write("No input files\n")
sys.exit(1)
self._run([Input(p, self.args) for p in self.args.input])
def _run(self, inputs):
for input in inputs:
self.allFiles.size += input.getFileSize()
self.allCode.size += input.getCodeSize()
self.prepare(inputs)
for input in inputs:
input.run(self)
self.report()
def processEntry(self, e, size, input, addr):
if self.last.spec and self.last.spec == e.file:
prefixes = self.last.prefixes
else:
prefixes = []
for key in self.getPrefixStrings(self.getParts(e.file.fullpath)):
try:
prefixes += [self.index[key]]
except KeyError:
pass
self.last.spec = e.file
self.last.prefixes = prefixes
for p in prefixes or [self.other]:
p.size += size
self.accounted.size += size
def report(self):
if not self.args.types:
self.reportCounts(self.prefixes + self.getCounts())
def getCounts(self):
counts = [
self.unknown, self.other, self.accounted,
self.allCode, self.allFiles, self.badSymbols]
if not self.args.unknown:
return counts
return list(self.symbols.values()) + [self.noSymbols] + counts
def reportCounts(self, counts):
for count in counts:
print(" %16s %s" % (nn(count.size), count.name))
if self.output:
self.output.write(" %16s %s\n" % (
nn(count.size), count.name))
def getParts(self, path):
parts = re.split(r"[/\\]+", path)
# Apparently lldb gets rid of ".."s in LineEntries
try:
parts = parts[parts.index(self.base) + 1:]
except ValueError:
pass
return [p.lower() for p in parts]
def normalizePath(self, path):
return "/".join(self.getParts(path))
def processUnknown2(self, addr, size):
c = addr.GetSymbolContext(lldb.eSymbolContextSymbol)
if c.symbol.IsValid():
s = self.symbols.get(c.symbol.name, Count(c.symbol.name))
s.size += size
self.symbols[c.symbol.name] = s
else:
self.noSymbols.size += size
def processUnknown(self, addr, size):
return self.processUnknown2(addr, size)
# eSymbolContextSymbol/c.symbol give us only exports which is no use
c = addr.GetSymbolContext(lldb.eSymbolContextFunction)
if c.function.IsValid():
s = self.symbols.get(c.function.name, Count(c.function.name))
s.size += size
self.symbols[c.function.name] = s
else:
self.noSymbols.size += size
class InstructionSpan:
def __init__(self, ilist, finished):
self.ilist, self.finished = ilist, finished
def print(self, output):
for i in self.ilist:
output.print(" %s: %s" % (i.addr.module.file.basename, i))
if not self.finished:
output.print(" %s: ..." % i.addr.module.file.basename)
return self
class SourceLine:
__slots__ = ("text", "number", "codeSize", "instructionSpans")
def __init__(self, text, number):
self.text = text
self.number = number
self.codeSize = 0
self.instructionSpans = []
class SourceFile:
__slots__ = (
"path", "name", "args", "lines", "lastHash", "lastDirHash",
"lastSpec", "gitId")
def __init__(self, path, name, args):
self.path = path
self.name = name
self.args = args
self.gitId = None
def load(self):
# python2:
# lines = open(self.path).read().decode("windows-1251").splitlines()
if self.gitId:
lines = subprocess.check_output(
["git", "cat-file", "blob", self.gitId])
if lines.decode:
lines = lines.decode("utf-8")
lines = lines.splitlines()
else:
lines = open(self.path, encoding="utf-8").read().splitlines()
self.lines = [SourceLine(s, i) for i, s in enumerate(lines)]
return self
def printLines(self, output):
output.print("%s:0: New file -----------------------------" %
self.name)
for line in self.lines:
m = "%03d %s" % (
line.codeSize, line.text)
if line.number != 0 and line.number % 10 == 0:
m += " // at %s:%d" % (self.name, line.number)
if sys.version_info < (3, 0):
m = m.encode("utf-8")
output.print(m)
if self.args.instructions:
for s in line.instructionSpans:
s.print(output)
class Lines(Context):
__slots__ = ("files", "lastFile", "nameMap", "lookups")
def prepare(self, inputs):
self.files = {}
self.lastFile = None
self.nameMap = {}
output = self.args.output or self.args.git and\
"%s-du.txt" % self.args.git[:8]
if output:
self.output = open(output, "wt")
self.output.write(" -*- mode: compilation -*-\n")
self.output.write(" (highlight-regexp \"000\" 'hi-green)\n")
else:
raise Exception("Must have output file")
if self.args.git:
lines = subprocess.check_output([
"git", "ls-tree", "-r", self.args.git]).splitlines();
for line in lines:
if not line:
break
if line.decode:
line = line.decode("utf-8")
params, path = line.split("\t", 2)
_, _, id = params.split(" ")
if re.match(r".+[.](c|cc|cpp|h|H|C|qx)$", path):
self.addPath(path, gitId=id)
if self.args.verbose:
sys.stderr.write("Added '%s'\n" % path)
for path in self.args.PREFIX:
self.addPath(path)
if len(self.files) == 0:
raise Exception("No source files")
self.lookups = [0, 0, 0]
def addPath(self, path, gitId=None):
np = self.normalizePath(path)
self.files[np] = SourceFile(path, np, self.args)
self.files[np].gitId = gitId
self.files[np].load()
def report(self):
for file in set(self.files.values()):
if file:
file.printLines(self)
self.reportCounts(self.getCounts() + [
self.entries, self.inlineEntries])
sys.stderr.write("lookups=%s " % " ".join(
[nn(x) for x in self.lookups]))
def print(self, s):
self.output.write(s + "\n")
def processEntry(self, e, size, input, addr):
# Optimization
cache = self
f = cache.lastFile
h = hash(e.file.GetFilename())
d = hash(e.file.GetDirectory())
if f:
if f.lastHash != h or\
f.lastSpec.basename != e.file.basename or\
f.lastSpec.dirname != e.file.dirname:
f = None
if not f:
self.lookups[1] += 1
f = cache.nameMap.get(e.file.GetFilename())
if not f or f.lastDirHash != d or\
f.lastSpec.GetDirectory() != e.file.GetDirectory():
self.lookups[2] += 1
f = self.files.get(self.normalizePath(e.file.fullpath))
if not f:
self.other.size += size
return
cache.nameMap[e.file.GetFilename()] = f
f.lastHash = h
f.lastDirHash = d
f.lastSpec = e.file
cache.lastFile = f
# End of optimization
self.accounted.size += size
try:
try:
f.lines[e.line - 1].codeSize += size
except IndexError:
self.badSymbols.size += size
return
if not self.args.instructions:
return
icount = 0
finished = False
while icount < 100 and not finished:
icount += 1
instrs = input.target.ReadInstructions(addr, icount)
finished = (instrs.GetSize() >= size)
f.lines[e.line - 1].instructionSpans += [
InstructionSpan(instrs, finished)]
except Exception:
sys.stderr.write("path='%s' line=%d\n" % (
e.file.fullpath, e.line))
raise
class SymbolStat:
tpl1 = re.compile(r"<(\w+)>")
def __init__(self, symbol, args):
self.name = symbol.name
if 1:
id = "A"
map = {}
for m in self.tpl1.finditer(self.name):
arg = m.group(1)
if not arg in map:
map[arg] = id
for arg in map.keys():
self.name = self.name.replace(arg, map[arg])
self.size = Calls.getSize(None, symbol)
self.count = 0
def getCumulativeSize(self):
return self.count * self.size
def getCount(self):
return self.count
class Calls(Context):
def prepare(self, inputs):
self.targets = []
if self.args.PREFIX:
for px in self.args.PREFIX:
self.targets.append(Count(px))
self.callTargetMaxSize = 0
if self.args.ctms:
self.callTargetMaxSize = int(self.args.ctms)
self.symbolInfo = {}
self.unknown = self.unknownSrc = Count("<unknown source>")
self.unknownTgt = Count("<unknown target>")
self.calls = Count("<call instructions>")
self.instructions = Count("<total instructions>")
self.noName = Count("<no name>")
self.symbols = Count("<symbols>")
self.noAddress = Count("<no address>")
self.functions = Count("<functions>")
self.endbr = Count("<endbr>")
self.sfp = Count("<stack frame used>")
for input in inputs:
if self.args.functions or self.args.all or\
self.args.ds or self.args.sfp or self.args.data:
input.run = input.getSymbols
else:
input.run = input.getInstructions
def dumpSymbol(self, s):
addr = s.GetStartAddress()
print("%6d %s+%s %2d %s%s loc='%s'" % (
self.getSize(s),
addr.section.name, xx(addr.GetOffset()),
s.GetType(), s.name, s.IsSynthetic() and " synthetic" or "",
self.getLocation(addr, "%s:%d")))
def processSymbol(self, s):
if not s.name:
self.noName.size += 1
return
if self.args.ds:
self.dumpSymbol(s)
return
if self.args.PREFIX:
found = None
for str in self.args.PREFIX:
if str in s.name:
found = str
break
if not found:
return
ss = SymbolStat(s, self.args)
key = "%d %s" % (self.getSize(s), ss.name)
t = self.symbolInfo.get(key)
if not t:
self.symbolInfo[key] = t = ss
t.count += 1
# Look for endbr and stack frame prologue
addr = s.GetStartAddress()
if addr.section.name != ".text":
return
err = lldb.SBError()
bytes = addr.section.GetSectionData().ReadRawData(
err, addr.offset, 8)
if err.fail:
self.unreadable.size += 1
return
if bytes[0:4] == b"\xF3\x0F\x1E\xFA":
self.endbr.size += 1
bytes = bytes[4:]
if bytes == b"\x55\x48\x89\xE5":
if self.args.sfp:
self.dumpSymbol(s)
self.sfp.size += 1
def printCall(self, src, ins, arg):
target = self.getLocation(arg, " at %s:%d")
if not target:
target = ""
print("%s %s -> %s%s" % (
src, ins.addr.symbol.name, arg.symbol.name, target))
sys.stdout.flush()
def processInstruction(self, ins, input):
self.instructions.size += 1
command = ins.GetMnemonic(input.target)
if command != "callq":
return
right = ins.GetOperands(input.target)
if "%" in right:
return
self.calls.size += 1
v = int(right, 16)
arg = lldb.SBAddress(v, input.target)
src = self.getLocation(ins.addr, "%s:%d:")
if not src:
self.unknownSrc.size += 1
src = ins.addr.symbol.name or "<unknown>"
if not arg.symbol.name:
self.unknownTgt.size += 1
if not self.targets and not self.callTargetMaxSize:
self.printCall(src, ins, arg)
return
if arg.symbol.name:
if self.callTargetMaxSize:
if self.getSize(arg.symbol) <= self.callTargetMaxSize:
found = False
for count in self.targets:
if count.name in arg.symbol.name:
found = True
break
if not found:
self.targets.append(Count(arg.symbol.name))