-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmachine-code-analyzer.py
More file actions
executable file
·4657 lines (3930 loc) · 183 KB
/
Copy pathmachine-code-analyzer.py
File metadata and controls
executable file
·4657 lines (3930 loc) · 183 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
#
# Email: Hagen Paul Pfeifer <hagen@jauu.net>
# Machine-Code-Analyzer is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# MachineCodeAnalyzer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MachineCodeAnalyzer. If not, see <http://www.gnu.org/licenses/>.
import sys
import os
import argparse
import array
import json
import re
import math
import shutil
import subprocess
import textwrap
import time
try:
import capstone
except ImportError:
sys.stderr.write("Capstone is not installed! Install via pip install capstone\n")
sys.exit(1)
try:
from elftools.elf.elffile import ELFFile
from elftools.elf.constants import SH_FLAGS
except ImportError:
sys.stderr.write("Pyelftools is not installed! Install via pip install pyelftools\n")
sys.exit(1)
# Optional package, only required for graph generation (-g)
try:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.colors
import matplotlib.patches
except ImportError:
plt = None
__programm__ = "machine-code-analyzer"
__author__ = "Hagen Paul Pfeifer"
__version__ = "1"
__license__ = "GPLv3"
# custom exceptions
class ArgumentException(Exception): pass
class InternalSequenceException(Exception): pass
class InternalException(Exception): pass
class SequenceContainerException(InternalException): pass
class NotImplementedException(InternalException): pass
class SkipProcessStepException(Exception): pass
class UnitException(Exception): pass
GRAPH_DESCRIPTIONS = {
'function-sizes': ("""The largest functions of the binary, ranked by machine code size.
Each bar is one function, the length is its size in byte as recorded in the
ELF symbol table, the percentage is its share of the whole analyzed code.
Large functions are the first candidates for a closer look: heavy inlining,
huge switch statements or generated code show up here immediately.""",
"Function size in byte",
"Function names, largest on top"),
'function-histogram': ("""How the function sizes are distributed, in power of two buckets.
Each bar counts the functions whose size falls into the bucket, "<= 64"
collects everything from 33 to 64 byte. Most code bases peak in the low
hundreds of bytes. A fat tail of huge functions or a spike of tiny wrapper
functions is worth investigating.""",
"Function size bucket in byte, power of two upper bound",
"Number of functions in the bucket"),
'function-cumulative': ("""How much of the total code is covered by the largest functions.
Functions are sorted by size, largest first, and summed up along the x axis.
The marked points show where 50 and 90 percent of the code is reached: "50%
of the code in 5% of the functions" means half the binary lives in a handful
of big functions. Useful to judge how top heavy a code base is and where
size optimizations would pay off.""",
"Share of functions in percent, sorted by size, largest first",
"Cumulative share of the total code size in percent"),
'function-alignment': ("""On which address boundaries the functions start.
Each bar counts the functions whose start address is divisible by the given
alignment. Compilers usually align function entries to 16 or 32 byte for
fetch efficiency, so the small alignments should be rare. A large
"Unaligned" share hints at handwritten assembly or unusual build flags.""",
"Number of functions",
"Start address alignment in byte"),
'instruction-categories': ("""Which instruction categories dominate the binary.
Every decoded instruction is classified (data transfer, control transfer,
arithmetic, SSE, ...) and counted. Typical compiler output is dominated by
data and control transfer. A visible SIMD share reveals vectorized code,
fat arithmetic buckets point to computation heavy loops.""",
"Number of instructions",
"Instruction category"),
'instruction-mnemonics': ("""The most frequent instruction mnemonics.
Counts per mnemonic in AT&T syntax including the size suffix, the
percentage relates to all instructions of the binary. The mov family leads
in almost every binary, the interesting information is what follows it:
many call/ret pairs mean small functions, many conditional jumps mean
branchy code.""",
"Number of instructions",
"Mnemonic in AT&T syntax, most frequent on top"),
'instruction-lengths': ("""How long the instruction encodings are.
x86 instructions are variable length, one to fifteen byte. The distribution
shows the encoding density of the binary: many short instructions mean
compact code that fits well into the instruction cache, long encodings come
from SIMD prefixes, large immediates and complex addressing.""",
"Instruction length in byte",
"Number of instructions with this length"),
'instruction-ranges': ("""How much the encoding length varies per mnemonic.
The dot marks the average encoding length of the mnemonic, the line spans
from the shortest to the longest encoding observed in the binary. Wide
spans (mov, cmp) come from the many operand forms - register, immediate,
memory with small or large offsets. Mnemonics without a span (ret) always
encode to the same size.""",
"Encoding length in byte, dot = average, line = min to max",
"Mnemonic in AT&T syntax, most frequent on top"),
'branch-histogram': ("""How far local jumps go, split into forward and backward.
The distance is measured in byte from the jump instruction to its target
inside the same function, bucketed by powers of two. Forward jumps skip
code (if/else, error checks), backward jumps close loops. Long distances
usually come from very large functions, interpreter loops and big switch
dispatchers show up as a far tail.""",
"Jump distance bucket in byte, power of two upper bound",
"Number of jumps in the bucket"),
'branch-direction': ("""The share of jump directions and jump conditions.
Two proportion bars over all local jumps. Forward jumps dominate in most
compiler output because error checks jump forward past the hot path. The
conditional share shows how much of the local control flow actually depends
on data at runtime.""",
"Share of all local jumps, one 100 percent bar per row",
"Two rows: jump direction and jump condition"),
'branch-percentiles': ("""Percentile curves of the local jump distances.
Read it like a latency plot: each curve shows the share of jumps that stay
within x byte. p50 is the median jump distance, p99 catches the outliers.
Backward (loop) jumps are systematically longer than forward jumps in most
binaries; the log axis shows both the short skips and the huge outliers.""",
"Jump distance in byte, log scale",
"Share of jumps within this distance in percent"),
'stack-histogram': ("""How much stack the functions allocate, in power of two buckets.
Counts functions per static stack allocation bucket. Most functions get by
with well below 128 byte. The 4096 byte bucket is typically filled by
PATH_MAX sized buffers.""",
"Static stack allocation bucket in byte, power of two",
"Number of functions in the bucket"),
'stack-allocation': ("""The share of functions that allocate stack at all.
Functions with a static or dynamic stack frame versus functions that run
entirely in registers (leaf functions, small helpers). A high allocation
share is normal for unoptimized builds, optimized code keeps many small
functions frameless.""",
"Share of all functions, one 100 percent bar",
"Single row: functions with versus without stack allocation"),
'stack-sizes': ("""Which exact static allocation sizes occur and how often.
Largest allocation sizes first, each bar counts the functions that allocate
exactly this amount. Repeated identical sizes usually come from the same
buffer pattern, dozens of functions with exactly 4096 byte point to
PATH_MAX arrays on the stack.""",
"Number of functions with exactly this allocation size",
"Static allocation size in byte, largest on top"),
'atomic-operations': ("""The mix of atomic operations, fences and spin wait hints.
Locked read-modify-write instructions split into compare-and-swap,
fetch-and-add, atomic swap and the rest, plus memory fences and pause
hints. The profile reveals the synchronization style: CAS heavy code
implements lock free structures, plain locked RMW dominates in reference
counting, many pause hints mean spin waiting.""",
"Number of operations",
"Operation class"),
'atomic-functions': ("""The functions with the most atomic operations and fences.
The synchronization hot spots of the binary. Functions that concentrate
many atomics are the places where locking strategy, cache line contention
and memory ordering deserve a review.""",
"Number of atomic operations and fences",
"Function names, most atomics on top"),
'layout-map': ("""Where each function switches from hot to cold code.
The largest functions as normalized strips: the orange head is the linear
path from the function entry to the first ret, the purple tail is code the
compiler moved out of the hot path - error handling, unlikely branches,
cleanup. The ticks mark conditional jumps into the tail. A tiny head with a
huge tail means either a very early return or a lot of outlined error
handling.""",
"Relative position within the function, 0 to 100 percent",
"Function names, largest on top"),
'layout-split': ("""How the code splits into hot and cold overall.
Three proportion bars: hot versus cold bytes over the whole binary, how
many functions have a cold tail at all, and how many functions keep a
frame pointer (push %rbp; mov %rsp,%rbp prologue) versus frame pointer
omission. The cold share is code the compiler considered unlikely to
run - a rough measure of how much error handling the binary carries.""",
"Share, one 100 percent bar per row",
"Three rows: code bytes, cold tail functions, frame pointer"),
'layout-histogram': ("""How large the cold tails are relative to their functions.
Buckets of the cold tail share: "70-80%" counts functions where most bytes
sit behind the first ret. The left edge holds the functions that are
essentially all hot path, the right edge functions that are mostly error
handling.""",
"Cold tail share bucket in percent of the function size",
"Number of functions in the bucket"),
'layout-scatter': ("""Function size versus cold tail share, one dot per function.
The x axis is logarithmic. The usual pattern: small functions have no cold
tail at all (the row at 0%), and the bigger a function gets the larger the
share of code the compiler moves out of its hot path.""",
"Function size in byte, log scale",
"Cold tail share in percent, one dot per function"),
'diff-changes': ("""Which functions grew or shrank between the two binaries.
Diverging bars, growth to the right in warm, shrinkage to the left in
teal, including functions that only exist in one of the binaries. Sorted
by the size of the change. Useful to see what a compiler flag or a patch
really did to the generated code.""",
"Code size delta in byte, negative means shrunk",
"Function names, largest change on top"),
'diff-categories': ("""How the instruction mix shifted between the two binaries.
Per category delta of the instruction counts. A drop in control transfer
with stable arithmetic usually means better branch elimination, a jump in
SIMD categories means the vectorizer kicked in.""",
"Instruction count delta, negative means fewer",
"Instruction category"),
'idiom-pairs': ("""The most frequent instruction pairs.
Counts how often one instruction directly follows another inside the
same function, mnemonics normalized without their size suffixes. The
top pairs are the compiler's idioms: cmp -> je is a comparison branch,
test -> je a null or flag check, xor -> ret returns zero. The pair
profile is a fingerprint of the code generator.""",
"Number of occurrences",
"Instruction pair, most frequent on top"),
'idiom-matrix': ("""Which instruction follows which, as a transition matrix.
Rows are the current instruction, columns the following one. A cell
shows how often the column instruction comes next, in percent of all
successors of the row instruction. Bright cells are strong couples:
after a cmp almost always follows a conditional jump. Only the most
frequent mnemonics are shown.""",
"Next instruction",
"Current instruction"),
'idiom-flow': ("""What each instruction is followed by, one bar per instruction.
For the most frequent instructions, the bar is split into the instructions
that follow it, widest share first and labelled inline. Reads left to right
as "after this instruction, this is what comes next": after a cmp almost
always a conditional jump, after a push another push. A simpler, more
tangible view of the same data as the transition matrix.""",
"Share of the next instruction in percent",
"Current instruction, most frequent on top"),
'idiom-trigrams': ("""The most frequent instruction triples.
Like the pairs, one step longer: three instructions in a row. Triples
expose larger building blocks, the function epilogue pop -> pop -> ret,
argument setup before calls or unrolled copy sequences.""",
"Number of occurrences",
"Instruction triple, most frequent on top"),
'call-called': ("""The most called functions.
Counts the direct call sites that target each function (fan-in). The
top entries are the work horses of the binary: allocation, locking,
error and string handling. Calls that leave the binary through the PLT
are summed into one external entry in the text report.""",
"Number of call sites targeting the function",
"Function names, most called on top"),
'call-fanout': ("""How many calls the functions make.
Buckets of call sites per function (fan-out). The zero bucket holds the
leaf functions that call nothing at all - the more of them, the flatter
the call graph. Functions with dozens of call sites are coordinators
that mostly orchestrate other code.""",
"Call sites per function, bucketed",
"Number of functions in the bucket"),
'call-kinds': ("""The mix of call kinds and the leaf share.
Direct internal calls stay inside the binary, external calls leave
through the PLT into shared libraries, indirect calls go through a
register or memory pointer - function pointers and vtables. A high
indirect share makes static analysis and branch prediction harder. The
second row shows how many functions are leaves.""",
"Share, one 100 percent bar per row",
"Two rows: call kinds and leaf functions"),
'hardening-card': ("""The full mitigation status of the binary, one row
per layer of defense.
PIE/ASLR, NX, RELRO, the stack canary, CET/IBT and FORTIFY, read from
the ELF headers and the instruction stream. Green means the mitigation
is on, amber means partial (partial RELRO, incomplete CET, no FORTIFY),
red means off. It is the checksec view of a single binary, at a
glance.""",
"Mitigation status (green on, amber partial, red off)",
"One row per mitigation layer"),
'hardening-coverage': ("""How much of the binary is covered by mitigations.
CET/IBT: functions starting with endbr64, a jump target barrier
against ROP/JOP attacks - near 100% means the binary was built with
-fcf-protection. Stack protector: functions that load the canary from
%fs:0x28; only functions with buffers get a canary under
-fstack-protector-strong, so well below 100% is normal there.""",
"Share of functions",
"One row per mitigation"),
'hardening-unprotected': ("""The largest functions without a stack canary.
Big functions without a canary load either have no stack buffers at
all (fine) or were compiled without stack protection (worth a look).
Function size is a rough proxy for attack surface, review from the
top.""",
"Function size in byte",
"Function names, largest on top"),
'register-usage': ("""How often each general purpose register is used.
Counts every register mention in the operands, sub-registers (eax, ax,
al) folded into their family (rax). The classic picture: rax dominates
as return and scratch register, then the argument registers rdi, rsi,
rdx, rcx. The drop towards r8-r15 shows how much the compiler avoids
the REX prefixed upper half.""",
"Register mentions in operands",
"Register family, architectural order"),
'register-classes': ("""Register class shares.
Caller-saved registers are free scratch, callee-saved ones must be
preserved across calls - heavy callee-saved use means functions with a
lot of live state. The second row shows how many mentions need a REX
prefix (r8-r15), the third the SIMD register share.""",
"Share of register mentions, one 100 percent bar per row",
"Three rows: save class, REX need, GP versus SIMD"),
'register-addressing': ("""Which operand forms the instructions use.
Register operands are the fastest, immediates encode constants inline,
memory operands go through the cache hierarchy. RIP-relative addressing
is the position independent way to reach globals, SIB forms
(base + index * scale) are typically array accesses.""",
"Number of operands",
"Operand form"),
}
def module_parser(module, description=None, no_exclude=True):
parser = argparse.ArgumentParser(
prog="%s %s" % (os.path.basename(sys.argv[0]), module),
description=description,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
help='show verbose messages')
parser.add_argument('--json-out', dest='json_out', metavar='FILE',
default=None,
help='write the analysis results as JSON to FILE, '
'parent directories are created')
if no_exclude:
parser.add_argument('-x', '--no-exclude', dest='no_exclude',
action='store_true',
help='do *not* exclude glibc/gcc runtime helper functions '
'like _start or __do_global_dtors_aux')
return parser
def add_graph_arguments(parser, graphs):
# graphs: list of (name, default filename, help text)
parser.add_argument('-g', '--graphs', dest='graphs_all', action='store_true',
help='generate all module graphs')
parser.add_argument('--graph-style', dest='graph_style',
choices=('light', 'dark'), default='light',
help='color style of the graphs, e.g. for dark slides (default: light)')
parser.add_argument('--graph-transparent', dest='graph_transparent',
action='store_true',
help='render with a transparent background, e.g. to embed on a '
'web page (pair with --graph-style dark for a dark page)')
lines = ["available graphs:"]
for name, default_filename, helptext in graphs:
parser.add_argument('--graph-%s' % (name), action='store_true',
help='generate the %s graph' % (helptext))
parser.add_argument('--graph-%s-filename' % (name), metavar='FILE',
default=None,
help='PNG output file, implies --graph-%s (default: %s)' %
(name, default_filename))
summary = helptext
key = default_filename[:-len('.png')]
if key in GRAPH_DESCRIPTIONS:
summary = GRAPH_DESCRIPTIONS[key][0].strip().split('\n')[0]
lines.append(" --graph-%-12s %s" % (name, summary))
lines.append("")
lines.append("every graph is written as PNG at 300 dpi together with a")
lines.append("<name>.png.txt sidecar explaining the picture and its axes")
parser.epilog = '\n'.join(lines)
def finish_graph_arguments(opts, graphs):
# a given filename implies the graph option itself, -g selects all
requested = False
for name, default_filename, helptext in graphs:
attr = 'graph_%s' % (name)
filename_attr = '%s_filename' % (attr)
if getattr(opts, filename_attr):
setattr(opts, attr, True)
elif opts.graphs_all:
setattr(opts, attr, True)
if not getattr(opts, filename_attr):
setattr(opts, filename_attr, default_filename)
requested = requested or getattr(opts, attr)
if requested and not plt:
sys.stderr.write("Want graphs but no matplotlib given!\n")
sys.exit(1)
class FunctionExcluder:
def __init__(self):
self.exclude_files = ['_start', '_fini', '__libc_csu_fini',
'__do_global_dtors_aux', '__libc_csu_init',
'register_tm_clones', 'frame_dummy',
'__init', 'deregister_tm_clones', '_init']
def is_excluded(self, function_name):
if function_name.endswith("@plt"):
return True
if function_name.endswith("@plt-0x10"):
return True
if function_name in self.exclude_files:
return True
return False
class RetObj:
STATIC = 0
DYNAMIC = 1
NO_STACK = 2
def __init__(self, stack_type):
self.stack_type = stack_type
self.register = None
class InstructionCategory:
UNKNOWN = 0
# E.g. http://flint.cs.yale.edu/cs422/doc/24547012.pdf
BINARY_ARITHMETIC = 32
DECIMAL_ARITHMETIC = 33
LOGICAL = 34
SHIFT_ROTATE = 35
BIT_BYTE = 36
CONTROL_TRANSFER = 37
STRING = 38
FLAG_CONTROL = 39
SEGMENT_REGISTER = 40
MISC = 41
DATA_TRANSFER = 42
FLOATING_POINT = 43
SYSTEM = 44
SIMD = 9
MMX = 10
SSE = 11
E3DN = 12
SSE2 = 13
SSE3 = 14
SSSE3 = 15
SSE41 = 16
SSE42 = 17
SSE4A = 18
AES = 19
AVX = 20
FMA = 21
FMA4 = 22
CPUID = 23
MMXEXT = 24
# external lookup table, filled from the JSON database
lookup_table = dict()
@staticmethod
def _cat_from_string(name):
# map JSON category names to the existing enum
mapping = {
"UNKNOWN": InstructionCategory.UNKNOWN,
"DATA_TRANSFER": InstructionCategory.DATA_TRANSFER,
"BINARY_ARITHMETIC": InstructionCategory.BINARY_ARITHMETIC,
"DECIMAL_ARITHMETIC": InstructionCategory.DECIMAL_ARITHMETIC,
"LOGICAL": InstructionCategory.LOGICAL,
"SHIFT_ROTATE": InstructionCategory.SHIFT_ROTATE,
"BIT_BYTE": InstructionCategory.BIT_BYTE,
"CONTROL_TRANSFER": InstructionCategory.CONTROL_TRANSFER,
"STRING": InstructionCategory.STRING,
"FLAG_CONTROL": InstructionCategory.FLAG_CONTROL,
"SEGMENT_REGISTER": InstructionCategory.SEGMENT_REGISTER,
"MISC": InstructionCategory.MISC,
"FLOATING_POINT": InstructionCategory.FLOATING_POINT,
"SYSTEM": InstructionCategory.SYSTEM,
# instruction family mapping
"SIMD": InstructionCategory.SIMD,
"MMX": InstructionCategory.MMX,
"MMXEXT": InstructionCategory.MMXEXT,
"SSE": InstructionCategory.SSE,
"E3DN": InstructionCategory.E3DN,
"SSE2": InstructionCategory.SSE2,
"SSE3": InstructionCategory.SSE3,
"SSSE3": InstructionCategory.SSSE3,
"SSE41": InstructionCategory.SSE41,
"SSE42": InstructionCategory.SSE42,
"SSE4A": InstructionCategory.SSE4A,
"AES": InstructionCategory.AES,
"PCLMULQDQ": InstructionCategory.AES, # crypto related
"AVX": InstructionCategory.AVX,
"AVX2": InstructionCategory.AVX,
"AVX512": InstructionCategory.AVX,
"FMA": InstructionCategory.FMA,
"FMA4": InstructionCategory.FMA4,
"BMI1": InstructionCategory.LOGICAL,
"BMI2": InstructionCategory.LOGICAL,
"SHA": InstructionCategory.AES,
"GFNI": InstructionCategory.LOGICAL,
"AMX": InstructionCategory.AVX,
"CPUID": InstructionCategory.CPUID
}
return mapping.get(name, InstructionCategory.UNKNOWN)
@staticmethod
def init_instruction_table(db_path=None):
"""
Load the mnemonic database from JSON. If the database is
missing or broken the lookup table stays empty and the
heuristic guesser handles all mnemonics.
"""
InstructionCategory.lookup_table.clear()
if db_path is not None:
path = db_path
else:
base = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(base, "data", "instruction-db.json")
try:
with open(path, "r", encoding="utf-8") as f:
doc = json.load(f)
except FileNotFoundError:
sys.stderr.write("No instruction database (%s), "
"falling back to heuristics\n" % (path))
return
except (ValueError, OSError) as e:
sys.stderr.write("Broken instruction database %s: %s, "
"falling back to heuristics\n" % (path, e))
return
cats = doc.get("categories", {})
for cat_name, mnems in cats.items():
cat_enum = InstructionCategory._cat_from_string(cat_name)
for m in mnems:
m_lower = m.strip().lower()
if not m_lower:
continue
InstructionCategory.lookup_table[m_lower] = [cat_enum, None]
@staticmethod
def _heuristic_guess(k):
# simple suffix/prefix based classification
def anyprefix(s, ps): return any(s.startswith(p) for p in ps)
base = re.sub(r'(b|w|l|q)$', '', k) # strip size suffix (addl -> add)
# control flow
if k in ("call","ret","jmp") or k.startswith("j"):
return InstructionCategory.CONTROL_TRANSFER
if k in ("endbr","endbr64","endbr32","notrack"):
return InstructionCategory.CONTROL_TRANSFER
# conditional moves / sets
if base.startswith("cmov"):
return InstructionCategory.DATA_TRANSFER
if base.startswith("set"):
return InstructionCategory.BIT_BYTE
# data movement
if base.startswith("mov") or base in ("xchg","bswap","lea","push","pop"):
return InstructionCategory.DATA_TRANSFER
# logic and tests
if base in ("and","or","xor","not","bt","bts","btr","btc","bsr","tzcnt","lzcnt"):
return InstructionCategory.LOGICAL
if base == "test":
return InstructionCategory.BIT_BYTE
# arithmetic
if anyprefix(base, ("add","sub","adc","sbb","mul","imul","div","idiv","inc","dec","neg","cmp")):
return InstructionCategory.BINARY_ARITHMETIC
# shift/rotate
if anyprefix(base, ("shl","sal","shr","sar","rol","ror","rcl","rcr","shld","shrd")):
return InstructionCategory.SHIFT_ROTATE
# typical SSE/SSE2 mnemonics
if anyprefix(k, ("addps","subps","mulps","divps","movaps","movups","shufps","movss","cvtss2sd")):
return InstructionCategory.SSE
if anyprefix(k, (
"addpd","subpd","mulpd","divpd","addsd","subsd","mulsd","divsd",
"ucomisd","comisd","shufpd","movapd","movupd","movsd","xorpd","orpd","andnpd",
"cvtsi2sd","cvttsd2si","cvtdq2pd","pshufd","psrldq","unpcklpd"
)):
return InstructionCategory.SSE2
# MMX/packed
if anyprefix(k, ("pcmpeq","pcmpgt","padd","psub","psll","psrl","psra","punpck","pmov","por","pand","pxor","pack")):
return InstructionCategory.MMX
# classic x87 FPU
if anyprefix(k, ("fld","fst","fstp","fnstsw","fadd","fsub","fmul","fdiv","fprem","fchs","fabs","fsqrt")):
return InstructionCategory.FLOATING_POINT
# system/misc
if k in ("ud2","hlt","nop","nopl","nopw"):
return InstructionCategory.MISC
return InstructionCategory.UNKNOWN
@staticmethod
def guess(instructon):
# capstone encodes prefixes into the mnemonic ("lock addl",
# "notrack jmpq"), the instruction itself is the last token
k = instructon.lower().split()[-1]
if k in InstructionCategory.lookup_table:
return InstructionCategory.lookup_table[k][0]
# retry with AT&T size suffixes stripped (fildll -> fild)
base = re.sub(r'[bwlq]+$', '', k)
if base in InstructionCategory.lookup_table:
return InstructionCategory.lookup_table[base][0]
return InstructionCategory._heuristic_guess(k)
@staticmethod
def str(cat):
if cat == InstructionCategory.UNKNOWN: return "unknown"
if cat == InstructionCategory.DATA_TRANSFER: return "DATA_TRANSFER"
if cat == InstructionCategory.BINARY_ARITHMETIC: return "BINARY_ARITHMETIC"
if cat == InstructionCategory.DECIMAL_ARITHMETIC: return "DECIMAL_ARITHMETIC"
if cat == InstructionCategory.LOGICAL: return "LOGICAL"
if cat == InstructionCategory.SHIFT_ROTATE: return "SHIFT_ROTATE"
if cat == InstructionCategory.BIT_BYTE: return "BIT_BYTE"
if cat == InstructionCategory.CONTROL_TRANSFER: return "CONTROL_TRANSFER"
if cat == InstructionCategory.STRING: return "STRING"
if cat == InstructionCategory.FLAG_CONTROL: return "FLAG_CONTROL"
if cat == InstructionCategory.SEGMENT_REGISTER: return "SEGMENT_REGISTER"
if cat == InstructionCategory.MISC: return "MISC"
if cat == InstructionCategory.FLOATING_POINT: return "FLOATING_POINT"
if cat == InstructionCategory.SYSTEM: return "SYSTEM"
if cat == InstructionCategory.SIMD: return "SIMD"
if cat == InstructionCategory.MMX: return "MMX"
if cat == InstructionCategory.SSE: return "SSE"
if cat == InstructionCategory.E3DN: return "E3DN"
if cat == InstructionCategory.SSE2: return "SSE2"
if cat == InstructionCategory.SSE3: return "SSE3"
if cat == InstructionCategory.SSSE3: return "SSSE3"
if cat == InstructionCategory.SSE41: return "SSE41"
if cat == InstructionCategory.SSE42: return "SSE42"
if cat == InstructionCategory.SSE4A: return "SSE4A"
if cat == InstructionCategory.AES: return "AES"
if cat == InstructionCategory.AVX: return "AVX"
if cat == InstructionCategory.FMA: return "FMA"
if cat == InstructionCategory.FMA4: return "FMA4"
if cat == InstructionCategory.CPUID: return "CPUID"
if cat == InstructionCategory.MMXEXT: return "MMXEXT"
raise Exception("Programmed error - no string repr defined")
class Context:
def __init__(self):
self.function_name = None
self.function_start_address = None
self.function_size = None
self.section_name = None
class BinaryAtom:
TYPE_1 = 1
TYPE_2 = 2
TYPE_3 = 3
TYPE_4 = 4
TYPE_5 = 5
TYPE_6 = 6
def __init__(self, b_type, line, addr, opcode, kwargs):
self.line = line
self.addr = addr
self.opcode_str = opcode
self.opcode_len = len(opcode.replace(" ", "")) // 2
self.type = b_type
self.category = InstructionCategory.UNKNOWN
self.src = self.dst = self.jmp_addr = self.jmp_sym = None
self.is_jump = False
self.mnemonic = kwargs['mnemonic']
if b_type == BinaryAtom.TYPE_1:
self.src = kwargs['src']
self.dst = kwargs['dst']
self.jmp_addr = kwargs['jmp-addr']
self.jmp_sym = kwargs['jmp-sym']
elif b_type == BinaryAtom.TYPE_2:
self.src = kwargs['src']
self.dst = kwargs['dst']
elif b_type == BinaryAtom.TYPE_3:
self.src = kwargs['src']
self.jmp_addr = kwargs['jmp-addr']
self.jmp_sym = kwargs['jmp-sym']
elif b_type == BinaryAtom.TYPE_4:
self.src = kwargs['src']
self.jmp_addr = kwargs['jmp-addr']
elif b_type == BinaryAtom.TYPE_5:
self.src = kwargs['src']
elif b_type == BinaryAtom.TYPE_6:
pass
else:
raise Exception("unknown code")
def print(self):
sys.stderr.write("%s\n" % (self.line))
sys.stderr.write("MNEMONIC: %s SRC:%s DST:%s [OPCODE: %s, LEN:%d]\n" %
(self.mnemonic, self.src, self.dst, self.opcode_str, self.opcode_len))
class Common:
def err(self, msg):
sys.stderr.write(msg)
def verbose(self, msg):
if not self.opts.verbose:
return
sys.stderr.write(msg)
def msg(self, msg):
return sys.stdout.write(msg) - 1
def line(self, length, char='-'):
sys.stdout.write(char * length + "\n")
def msg_underline(self, msg, pre_news=0, post_news=0):
str_len = len(msg)
if pre_news:
self.msg("\n" * pre_news)
self.msg(msg)
self.msg("\n" + '=' * str_len)
if post_news:
self.msg("\n" * post_news)
def debug(self, msg):
# remove next line for debuging purpose
return
sys.stderr.write(msg)
def next_power_of_two(self, n):
return int(math.pow(2, math.ceil(math.log(n, 2))))
# graph styles: no chart junk, muted modern palette, one for light
# and one for dark slides
GRAPH_STYLES = {
'light': {
'bg': '#ffffff',
'ink': '#30343b',
'frame': '#565b63',
'grid': '#d5d8dc',
'primary': '#8b0aa5',
'secondary': '#f89441',
'good': '#3f9b8c',
'bad': '#c65f5f',
'ramp': (0.03, 0.82),
},
'dark': {
'bg': '#15171c',
'ink': '#d7dae0',
'frame': '#8f95a0',
'grid': '#3a3e46',
'primary': '#c65ddb',
'secondary': '#f9a860',
'good': '#63bfae',
'bad': '#e08585',
'ramp': (0.22, 0.94),
},
}
def graph_style(self):
return Common.GRAPH_STYLES[self.opts.graph_style]
def graph_axes(self, xlabel=None, ylabel=None, figsize=(8.0, 4.5)):
style = self.graph_style()
fig, ax = plt.subplots(figsize=figsize, layout='constrained')
fig.patch.set_facecolor(style['bg'])
ax.set_facecolor(style['bg'])
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color(style['frame'])
ax.spines['bottom'].set_color(style['frame'])
ax.tick_params(colors=style['frame'], labelcolor=style['ink'],
labelsize=8)
if xlabel:
ax.set_xlabel(xlabel, color=style['ink'], fontsize=9)
if ylabel:
ax.set_ylabel(ylabel, color=style['ink'], fontsize=9)
return fig, ax
def graph_blend(self, color, other, fraction):
a = matplotlib.colors.to_rgb(color)
b = matplotlib.colors.to_rgb(other)
return tuple(x * (1.0 - fraction) + y * fraction for x, y in zip(a, b))
def graph_value_colors(self, values, base=None):
# the longer the bar the deeper the color, square root scaled
# so small bars stay distinguishable next to a dominating one
style = self.graph_style()
vmax = float(max(values)) if values and max(values) > 0 else 1.0
colors = []
if base is not None:
# multi series charts keep their identity hue
pale = self.graph_blend(base, style['bg'], 0.55)
deep = self.graph_blend(base, style['ink'], 0.25)
for value in values:
t = 0.15 + 0.85 * math.sqrt(max(value, 0) / vmax)
colors.append(self.graph_blend(pale, deep, min(t, 1.0)))
return colors
# single series ride the plasma colormap, largest value in
# deep purple, smallest towards yellow
cmap = matplotlib.colormaps['plasma']
lo, hi = style['ramp']
for value in values:
t = math.sqrt(max(value, 0) / vmax)
colors.append(cmap(hi - t * (hi - lo)))
return colors
def graph_grid(self, ax, axis):
style = self.graph_style()
ax.grid(True, axis=axis, color=style['grid'], linewidth=0.7)
ax.set_axisbelow(True)
# the grid axis carries the counters, integers only
locator = matplotlib.ticker.MaxNLocator(integer=True)
if axis == 'y':
ax.yaxis.set_major_locator(locator)
else:
ax.xaxis.set_major_locator(locator)
def graph_bar_labels(self, ax, bars, horizontal=False, fmt='%d', total=None):
style = self.graph_style()
for bar in bars:
if horizontal:
value, xy = bar.get_width(), \
(bar.get_width(), bar.get_y() + bar.get_height() / 2)
if value < 0:
offset, ha, va = (-3, 0), 'right', 'center'
else:
offset, ha, va = (3, 0), 'left', 'center'
else:
value, xy = bar.get_height(), \
(bar.get_x() + bar.get_width() / 2, bar.get_height())
offset, ha, va = (0, 2), 'center', 'bottom'
label = fmt % (value)
if total:
# two lines for vertical bars, neighbor labels collide else
separator = ' ' if horizontal else '\n'
label += "%s(%.1f%%)" % (separator, (float(value) / total) * 100.0)
ax.annotate(label, xy, xytext=offset,
textcoords='offset points', ha=ha, va=va,
fontsize=7, color=style['ink'], zorder=4)
def graph_proportion_row(self, ax, y, parts, labels, colors, caption):
# one horizontal 100 percent bar, segments labeled inline
style = self.graph_style()
total = sum(parts)
if total == 0:
return
left = 0.0
for part, label, color in zip(parts, labels, colors):
fraction = float(part) / total
ax.barh(y, fraction, left=left, height=0.42, color=color, zorder=2)
if fraction > 0.08:
ax.text(left + fraction / 2, y,
"%s %d (%.0f%%)" % (label, part, fraction * 100.0),
ha='center', va='center', fontsize=8,
color=style['bg'], zorder=3)
left += fraction
ax.text(0.0, y + 0.34, caption, ha='left', va='bottom', fontsize=8,
color=style['ink'])
def graph_render(self, fig, filename, description=None):
style = self.graph_style()
if getattr(self.opts, 'graph_transparent', False):
fig.savefig(filename, dpi=300, transparent=True)
else:
fig.savefig(filename, dpi=300, facecolor=style['bg'])
plt.close(fig)
sys.stderr.write("# graph written: %s\n" % (filename))
if description:
text, x_axis, y_axis = description
paragraphs = [textwrap.fill(' '.join(p.split()), width=72)
for p in text.strip().split('\n\n')]
paragraphs.append('\n'.join((
textwrap.fill("X axis: %s" % (x_axis), width=72,
subsequent_indent=' '),
textwrap.fill("Y axis: %s" % (y_axis), width=72,
subsequent_indent=' '))))
with open('%s.txt' % (filename), 'w', encoding='utf-8') as f:
f.write('\n\n'.join(paragraphs) + '\n')
sys.stderr.write("# graph description: %s.txt\n" % (filename))
def write_json(self, module, data, binary=None):
if not getattr(self.opts, 'json_out', None):
return
path = self.opts.json_out
directory = os.path.dirname(path)
if directory:
os.makedirs(directory, exist_ok=True)
document = { 'module': module, 'data': data }
if binary is None:
binary = getattr(self.opts, 'filename', None)
if binary is not None:
document['binary'] = os.path.abspath(binary)
with open(path, 'w', encoding='utf-8') as f:
json.dump(document, f, indent=2, sort_keys=True)
f.write('\n')