1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
|
# Copyright (c) 2015-2016 Vector 35 LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import traceback
import ctypes
import abc
# Binary Ninja components
import _binaryninjacore as core
from enums import (Endianness, ImplicitRegisterExtend, BranchType,
InstructionTextTokenType, LowLevelILFlagCondition, FlagRole)
import startup
import function
import lowlevelil
import callingconvention
import platform
import log
import databuffer
import types
class _ArchitectureMetaClass(type):
@property
def list(self):
startup._init_plugins()
count = ctypes.c_ulonglong()
archs = core.BNGetArchitectureList(count)
result = []
for i in xrange(0, count.value):
result.append(Architecture(archs[i]))
core.BNFreeArchitectureList(archs)
return result
def __iter__(self):
startup._init_plugins()
count = ctypes.c_ulonglong()
archs = core.BNGetArchitectureList(count)
try:
for i in xrange(0, count.value):
yield Architecture(archs[i])
finally:
core.BNFreeArchitectureList(archs)
def __getitem__(cls, name):
startup._init_plugins()
arch = core.BNGetArchitectureByName(name)
if arch is None:
raise KeyError("'%s' is not a valid architecture" % str(name))
return Architecture(arch)
def register(cls):
startup._init_plugins()
if cls.name is None:
raise ValueError("architecture 'name' is not defined")
arch = cls()
cls._registered_cb = arch._cb
arch.handle = core.BNRegisterArchitecture(cls.name, arch._cb)
def __setattr__(self, name, value):
try:
type.__setattr__(self, name, value)
except AttributeError:
raise AttributeError("attribute '%s' is read only" % name)
class Architecture(object):
"""
``class Architecture`` is the parent class for all CPU architectures. Subclasses of Architecture implement assembly,
disassembly, IL lifting, and patching.
``class Architecture`` has a ``__metaclass__`` with the additional methods ``register``, and supports
iteration::
>>> #List the architectures
>>> list(Architecture)
[<arch: aarch64>, <arch: armv7>, <arch: armv7eb>, <arch: mipsel32>, <arch: mips32>, <arch: powerpc>,
<arch: x86>, <arch: x86_64>]
>>> #Register a new Architecture
>>> class MyArch(Architecture):
... name = "MyArch"
...
>>> MyArch.register()
>>> list(Architecture)
[<arch: aarch64>, <arch: armv7>, <arch: armv7eb>, <arch: mipsel32>, <arch: mips32>, <arch: powerpc>,
<arch: x86>, <arch: x86_64>, <arch: MyArch>]
>>>
For the purposes of this documentation the variable ``arch`` will be used in the following context ::
>>> from binaryninja import *
>>> arch = Architecture['x86']
"""
name = None
endianness = Endianness.LittleEndian
address_size = 8
default_int_size = 4
max_instr_length = 16
opcode_display_length = 8
regs = {}
stack_pointer = None
link_reg = None
flags = []
flag_write_types = []
flag_roles = {}
flags_required_for_flag_condition = {}
flags_written_by_flag_write_type = {}
__metaclass__ = _ArchitectureMetaClass
next_address = 0
def __init__(self, handle=None):
if handle is not None:
self.handle = core.handle_of_type(handle, core.BNArchitecture)
self.__dict__["name"] = core.BNGetArchitectureName(self.handle)
self.__dict__["endianness"] = Endianness(core.BNGetArchitectureEndianness(self.handle)).name
self.__dict__["address_size"] = core.BNGetArchitectureAddressSize(self.handle)
self.__dict__["default_int_size"] = core.BNGetArchitectureDefaultIntegerSize(self.handle)
self.__dict__["max_instr_length"] = core.BNGetArchitectureMaxInstructionLength(self.handle)
self.__dict__["opcode_display_length"] = core.BNGetArchitectureOpcodeDisplayLength(self.handle)
self.__dict__["stack_pointer"] = core.BNGetArchitectureRegisterName(self.handle,
core.BNGetArchitectureStackPointerRegister(self.handle))
self.__dict__["link_reg"] = core.BNGetArchitectureRegisterName(self.handle,
core.BNGetArchitectureLinkRegister(self.handle))
count = ctypes.c_ulonglong()
regs = core.BNGetAllArchitectureRegisters(self.handle, count)
self.__dict__["regs"] = {}
for i in xrange(0, count.value):
name = core.BNGetArchitectureRegisterName(self.handle, regs[i])
info = core.BNGetArchitectureRegisterInfo(self.handle, regs[i])
full_width_reg = core.BNGetArchitectureRegisterName(self.handle, info.fullWidthRegister)
self.regs[name] = function.RegisterInfo(full_width_reg, info.size, info.offset,
ImplicitRegisterExtend(info.extend).name, regs[i])
core.BNFreeRegisterList(regs)
count = ctypes.c_ulonglong()
flags = core.BNGetAllArchitectureFlags(self.handle, count)
self._flags = {}
self._flags_by_index = {}
self.__dict__["flags"] = []
for i in xrange(0, count.value):
name = core.BNGetArchitectureFlagName(self.handle, flags[i])
self._flags[name] = flags[i]
self._flags_by_index[flags[i]] = name
self.flags.append(name)
core.BNFreeRegisterList(flags)
count = ctypes.c_ulonglong()
types = core.BNGetAllArchitectureFlagWriteTypes(self.handle, count)
self._flag_write_types = {}
self._flag_write_types_by_index = {}
self.__dict__["flag_write_types"] = []
for i in xrange(0, count.value):
name = core.BNGetArchitectureFlagWriteTypeName(self.handle, types[i])
self._flag_write_types[name] = types[i]
self._flag_write_types_by_index[types[i]] = name
self.flag_write_types.append(name)
core.BNFreeRegisterList(types)
self._flag_roles = {}
self.__dict__["flag_roles"] = {}
for flag in self.__dict__["flags"]:
role = FlagRole(core.BNGetArchitectureFlagRole(self.handle, self._flags[flag]))
self.__dict__["flag_roles"][flag] = role
self._flag_roles[self._flags[flag]] = role
self._flags_required_for_flag_condition = {}
self.__dict__["flags_required_for_flag_condition"] = {}
for cond in LowLevelILFlagCondition:
count = ctypes.c_ulonglong()
flags = core.BNGetArchitectureFlagsRequiredForFlagCondition(self.handle, cond, count)
flag_indexes = []
flag_names = []
for i in xrange(0, count.value):
flag_indexes.append(flags[i])
flag_names.append(self._flags_by_index[flags[i]])
core.BNFreeRegisterList(flags)
self._flags_required_for_flag_condition[cond] = flag_indexes
self.__dict__["flags_required_for_flag_condition"][cond] = flag_names
self._flags_written_by_flag_write_type = {}
self.__dict__["flags_written_by_flag_write_type"] = {}
for write_type in self.flag_write_types:
count = ctypes.c_ulonglong()
flags = core.BNGetArchitectureFlagsWrittenByFlagWriteType(self.handle,
self._flag_write_types[write_type], count)
flag_indexes = []
flag_names = []
for i in xrange(0, count.value):
flag_indexes.append(flags[i])
flag_names.append(self._flags_by_index[flags[i]])
core.BNFreeRegisterList(flags)
self._flags_written_by_flag_write_type[self._flag_write_types[write_type]] = flag_indexes
self.__dict__["flags_written_by_flag_write_type"][write_type] = flag_names
else:
startup._init_plugins()
if self.__class__.opcode_display_length > self.__class__.max_instr_length:
self.__class__.opcode_display_length = self.__class__.max_instr_length
self._cb = core.BNCustomArchitecture()
self._cb.context = 0
self._cb.init = self._cb.init.__class__(self._init)
self._cb.getEndianness = self._cb.getEndianness.__class__(self._get_endianness)
self._cb.getAddressSize = self._cb.getAddressSize.__class__(self._get_address_size)
self._cb.getDefaultIntegerSize = self._cb.getDefaultIntegerSize.__class__(self._get_default_integer_size)
self._cb.getMaxInstructionLength = self._cb.getMaxInstructionLength.__class__(self._get_max_instruction_length)
self._cb.getOpcodeDisplayLength = self._cb.getOpcodeDisplayLength.__class__(self._get_opcode_display_length)
self._cb.getAssociatedArchitectureByAddress = \
self._cb.getAssociatedArchitectureByAddress.__class__(self._get_associated_arch_by_address)
self._cb.getInstructionInfo = self._cb.getInstructionInfo.__class__(self._get_instruction_info)
self._cb.getInstructionText = self._cb.getInstructionText.__class__(self._get_instruction_text)
self._cb.freeInstructionText = self._cb.freeInstructionText.__class__(self._free_instruction_text)
self._cb.getInstructionLowLevelIL = self._cb.getInstructionLowLevelIL.__class__(
self._get_instruction_low_level_il)
self._cb.getRegisterName = self._cb.getRegisterName.__class__(self._get_register_name)
self._cb.getFlagName = self._cb.getFlagName.__class__(self._get_flag_name)
self._cb.getFlagWriteTypeName = self._cb.getFlagWriteTypeName.__class__(self._get_flag_write_type_name)
self._cb.getFullWidthRegisters = self._cb.getFullWidthRegisters.__class__(self._get_full_width_registers)
self._cb.getAllRegisters = self._cb.getAllRegisters.__class__(self._get_all_registers)
self._cb.getAllFlags = self._cb.getAllRegisters.__class__(self._get_all_flags)
self._cb.getAllFlagWriteTypes = self._cb.getAllRegisters.__class__(self._get_all_flag_write_types)
self._cb.getFlagRole = self._cb.getFlagRole.__class__(self._get_flag_role)
self._cb.getFlagsRequiredForFlagCondition = self._cb.getFlagsRequiredForFlagCondition.__class__(
self._get_flags_required_for_flag_condition)
self._cb.getFlagsWrittenByFlagWriteType = self._cb.getFlagsWrittenByFlagWriteType.__class__(
self._get_flags_written_by_flag_write_type)
self._cb.getFlagWriteLowLevelIL = self._cb.getFlagWriteLowLevelIL.__class__(
self._get_flag_write_low_level_il)
self._cb.getFlagConditionLowLevelIL = self._cb.getFlagConditionLowLevelIL.__class__(
self._get_flag_condition_low_level_il)
self._cb.freeRegisterList = self._cb.freeRegisterList.__class__(self._free_register_list)
self._cb.getRegisterInfo = self._cb.getRegisterInfo.__class__(self._get_register_info)
self._cb.getStackPointerRegister = self._cb.getStackPointerRegister.__class__(
self._get_stack_pointer_register)
self._cb.getLinkRegister = self._cb.getLinkRegister.__class__(self._get_link_register)
self._cb.assemble = self._cb.assemble.__class__(self._assemble)
self._cb.isNeverBranchPatchAvailable = self._cb.isNeverBranchPatchAvailable.__class__(
self._is_never_branch_patch_available)
self._cb.isAlwaysBranchPatchAvailable = self._cb.isAlwaysBranchPatchAvailable.__class__(
self._is_always_branch_patch_available)
self._cb.isInvertBranchPatchAvailable = self._cb.isInvertBranchPatchAvailable.__class__(
self._is_invert_branch_patch_available)
self._cb.isSkipAndReturnZeroPatchAvailable = self._cb.isSkipAndReturnZeroPatchAvailable.__class__(
self._is_skip_and_return_zero_patch_available)
self._cb.isSkipAndReturnValuePatchAvailable = self._cb.isSkipAndReturnValuePatchAvailable.__class__(
self._is_skip_and_return_value_patch_available)
self._cb.convertToNop = self._cb.convertToNop.__class__(self._convert_to_nop)
self._cb.alwaysBranch = self._cb.alwaysBranch.__class__(self._always_branch)
self._cb.invertBranch = self._cb.invertBranch.__class__(self._invert_branch)
self._cb.skipAndReturnValue = self._cb.skipAndReturnValue.__class__(self._skip_and_return_value)
self._all_regs = {}
self._full_width_regs = {}
self._regs_by_index = {}
self.__dict__["regs"] = self.__class__.regs
reg_index = 0
for reg in self.regs:
info = self.regs[reg]
if reg not in self._all_regs:
self._all_regs[reg] = reg_index
self._regs_by_index[reg_index] = reg
self.regs[reg].index = reg_index
reg_index += 1
if info.full_width_reg not in self._all_regs:
self._all_regs[info.full_width_reg] = reg_index
self._regs_by_index[reg_index] = info.full_width_reg
self.regs[info.full_width_reg].index = reg_index
reg_index += 1
if info.full_width_reg not in self._full_width_regs:
self._full_width_regs[info.full_width_reg] = self._all_regs[info.full_width_reg]
self._flags = {}
self._flags_by_index = {}
self.__dict__["flags"] = self.__class__.flags
flag_index = 0
for flag in self.__class__.flags:
if flag not in self._flags:
self._flags[flag] = flag_index
self._flags_by_index[flag_index] = flag
flag_index += 1
self._flag_write_types = {}
self._flag_write_types_by_index = {}
self.__dict__["flag_write_types"] = self.__class__.flag_write_types
write_type_index = 0
for write_type in self.__class__.flag_write_types:
if write_type not in self._flag_write_types:
self._flag_write_types[write_type] = write_type_index
self._flag_write_types_by_index[write_type_index] = write_type
write_type_index += 1
self._flag_roles = {}
self.__dict__["flag_roles"] = self.__class__.flag_roles
for flag in self.__class__.flag_roles:
role = self.__class__.flag_roles[flag]
if isinstance(role, str):
role = FlagRole[role]
self._flag_roles[self._flags[flag]] = role
self._flags_required_for_flag_condition = {}
self.__dict__["flags_required_for_flag_condition"] = self.__class__.flags_required_for_flag_condition
for cond in self.__class__.flags_required_for_flag_condition:
flags = []
for flag in self.__class__.flags_required_for_flag_condition[cond]:
flags.append(self._flags[flag])
self._flags_required_for_flag_condition[cond] = flags
self._flags_written_by_flag_write_type = {}
self.__dict__["flags_written_by_flag_write_type"] = self.__class__.flags_written_by_flag_write_type
for write_type in self.__class__.flags_written_by_flag_write_type:
flags = []
for flag in self.__class__.flags_written_by_flag_write_type[write_type]:
flags.append(self._flags[flag])
self._flags_written_by_flag_write_type[self._flag_write_types[write_type]] = flags
self._pending_reg_lists = {}
self._pending_token_lists = {}
@property
def full_width_regs(self):
"""List of full width register strings (read-only)"""
count = ctypes.c_ulonglong()
regs = core.BNGetFullWidthArchitectureRegisters(self.handle, count)
result = []
for i in xrange(0, count.value):
result.append(core.BNGetArchitectureRegisterName(self.handle, regs[i]))
core.BNFreeRegisterList(regs)
return result
@property
def calling_conventions(self):
"""Dict of CallingConvention objects (read-only)"""
count = ctypes.c_ulonglong()
cc = core.BNGetArchitectureCallingConventions(self.handle, count)
result = {}
for i in xrange(0, count.value):
obj = callingconvention.CallingConvention(None, core.BNNewCallingConventionReference(cc[i]))
result[obj.name] = obj
core.BNFreeCallingConventionList(cc, count)
return result
@property
def standalone_platform(self):
"""Architecture standalone platform (read-only)"""
pl = core.BNGetArchitectureStandalonePlatform(self.handle)
return platform.Platform(self, pl)
def __setattr__(self, name, value):
if ((name == "name") or (name == "endianness") or (name == "address_size") or
(name == "default_int_size") or (name == "regs") or (name == "get_max_instruction_length")):
raise AttributeError("attribute '%s' is read only" % name)
else:
try:
object.__setattr__(self, name, value)
except AttributeError:
raise AttributeError("attribute '%s' is read only" % name)
def __repr__(self):
return "<arch: %s>" % self.name
def _init(self, ctxt, handle):
self.handle = handle
def _get_endianness(self, ctxt):
try:
return self.__class__.endianness
except:
log.log_error(traceback.format_exc())
return Endianness.LittleEndian
def _get_address_size(self, ctxt):
try:
return self.__class__.address_size
except:
log.log_error(traceback.format_exc())
return 8
def _get_default_integer_size(self, ctxt):
try:
return self.__class__.default_int_size
except:
log.log_error(traceback.format_exc())
return 4
def _get_max_instruction_length(self, ctxt):
try:
return self.__class__.max_instr_length
except:
log.log_error(traceback.format_exc())
return 16
def _get_opcode_display_length(self, ctxt):
try:
return self.__class__.opcode_display_length
except:
log.log_error(traceback.format_exc())
return 8
def _get_associated_arch_by_address(self, ctxt, addr):
try:
result, new_addr = self.perform_get_associated_arch_by_address(addr[0])
addr[0] = new_addr
return ctypes.cast(result.handle, ctypes.c_void_p).value
except:
log.log_error(traceback.format_exc())
return ctypes.cast(self.handle, ctypes.c_void_p).value
def _get_instruction_info(self, ctxt, data, addr, max_len, result):
try:
buf = ctypes.create_string_buffer(max_len)
ctypes.memmove(buf, data, max_len)
info = self.perform_get_instruction_info(buf.raw, addr)
if info is None:
return False
result[0].length = info.length
result[0].branchDelay = info.branch_delay
result[0].branchCount = len(info.branches)
for i in xrange(0, len(info.branches)):
if isinstance(info.branches[i].type, str):
result[0].branchType[i] = BranchType[info.branches[i].type]
else:
result[0].branchType[i] = info.branches[i].type
result[0].branchTarget[i] = info.branches[i].target
if info.branches[i].arch is None:
result[0].branchArch[i] = None
else:
result[0].branchArch[i] = info.branches[i].arch.handle
return True
except (KeyError, OSError):
log.log_error(traceback.format_exc())
return False
def _get_instruction_text(self, ctxt, data, addr, length, result, count):
try:
buf = ctypes.create_string_buffer(length[0])
ctypes.memmove(buf, data, length[0])
info = self.perform_get_instruction_text(buf.raw, addr)
if info is None:
return False
tokens = info[0]
length[0] = info[1]
count[0] = len(tokens)
token_buf = (core.BNInstructionTextToken * len(tokens))()
for i in xrange(0, len(tokens)):
if isinstance(tokens[i].type, str):
token_buf[i].type = InstructionTextTokenType[tokens[i].type]
else:
token_buf[i].type = tokens[i].type
token_buf[i].text = tokens[i].text
token_buf[i].value = tokens[i].value
token_buf[i].size = tokens[i].size
token_buf[i].operand = tokens[i].operand
result[0] = token_buf
ptr = ctypes.cast(token_buf, ctypes.c_void_p)
self._pending_token_lists[ptr.value] = (ptr.value, token_buf)
return True
except (KeyError, OSError):
log.log_error(traceback.format_exc())
return False
def _free_instruction_text(self, tokens, count):
try:
buf = ctypes.cast(tokens, ctypes.c_void_p)
if buf.value not in self._pending_token_lists:
raise ValueError("freeing token list that wasn't allocated")
del self._pending_token_lists[buf.value]
except KeyError:
log.log_error(traceback.format_exc())
def _get_instruction_low_level_il(self, ctxt, data, addr, length, il):
try:
buf = ctypes.create_string_buffer(length[0])
ctypes.memmove(buf, data, length[0])
result = self.perform_get_instruction_low_level_il(buf.raw, addr,
lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il)))
if result is None:
return False
length[0] = result
return True
except OSError:
log.log_error(traceback.format_exc())
return False
def _get_register_name(self, ctxt, reg):
try:
if reg in self._regs_by_index:
return core.BNAllocString(self._regs_by_index[reg])
return core.BNAllocString("")
except (KeyError, OSError):
log.log_error(traceback.format_exc())
return core.BNAllocString("")
def _get_flag_name(self, ctxt, flag):
try:
if flag in self._flags_by_index:
return core.BNAllocString(self._flags_by_index[flag])
return core.BNAllocString("")
except (KeyError, OSError):
log.log_error(traceback.format_exc())
return core.BNAllocString("")
def _get_flag_write_type_name(self, ctxt, write_type):
try:
if write_type in self._flag_write_types_by_index:
return core.BNAllocString(self._flag_write_types_by_index[write_type])
return core.BNAllocString("")
except (KeyError, OSError):
log.log_error(traceback.format_exc())
return core.BNAllocString("")
def _get_full_width_registers(self, ctxt, count):
try:
regs = self._full_width_regs.values()
count[0] = len(regs)
reg_buf = (ctypes.c_uint * len(regs))()
for i in xrange(0, len(regs)):
reg_buf[i] = regs[i]
result = ctypes.cast(reg_buf, ctypes.c_void_p)
self._pending_reg_lists[result.value] = (result, reg_buf)
return result.value
except KeyError:
log.log_error(traceback.format_exc())
count[0] = 0
return None
def _get_all_registers(self, ctxt, count):
try:
regs = self._regs_by_index.keys()
count[0] = len(regs)
reg_buf = (ctypes.c_uint * len(regs))()
for i in xrange(0, len(regs)):
reg_buf[i] = regs[i]
result = ctypes.cast(reg_buf, ctypes.c_void_p)
self._pending_reg_lists[result.value] = (result, reg_buf)
return result.value
except KeyError:
log.log_error(traceback.format_exc())
count[0] = 0
return None
def _get_all_flags(self, ctxt, count):
try:
flags = self._flags_by_index.keys()
count[0] = len(flags)
flag_buf = (ctypes.c_uint * len(flags))()
for i in xrange(0, len(flags)):
flag_buf[i] = flags[i]
result = ctypes.cast(flag_buf, ctypes.c_void_p)
self._pending_reg_lists[result.value] = (result, flag_buf)
return result.value
except KeyError:
log.log_error(traceback.format_exc())
count[0] = 0
return None
def _get_all_flag_write_types(self, ctxt, count):
try:
types = self._flag_write_types_by_index.keys()
count[0] = len(types)
type_buf = (ctypes.c_uint * len(types))()
for i in xrange(0, len(types)):
type_buf[i] = types[i]
result = ctypes.cast(type_buf, ctypes.c_void_p)
self._pending_reg_lists[result.value] = (result, type_buf)
return result.value
except KeyError:
log.log_error(traceback.format_exc())
count[0] = 0
return None
def _get_flag_role(self, ctxt, flag):
try:
if flag in self._flag_roles:
return self._flag_roles[flag]
return FlagRole.SpecialFlagRole
except KeyError:
log.log_error(traceback.format_exc())
return None
def _get_flags_required_for_flag_condition(self, ctxt, cond, count):
try:
if cond in self._flags_required_for_flag_condition:
flags = self._flags_required_for_flag_condition[cond]
else:
flags = []
count[0] = len(flags)
flag_buf = (ctypes.c_uint * len(flags))()
for i in xrange(0, len(flags)):
flag_buf[i] = flags[i]
result = ctypes.cast(flag_buf, ctypes.c_void_p)
self._pending_reg_lists[result.value] = (result, flag_buf)
return result.value
except KeyError:
log.log_error(traceback.format_exc())
count[0] = 0
return None
def _get_flags_written_by_flag_write_type(self, ctxt, write_type, count):
try:
if write_type in self._flags_written_by_flag_write_type:
flags = self._flags_written_by_flag_write_type[write_type]
else:
flags = []
count[0] = len(flags)
flag_buf = (ctypes.c_uint * len(flags))()
for i in xrange(0, len(flags)):
flag_buf[i] = flags[i]
result = ctypes.cast(flag_buf, ctypes.c_void_p)
self._pending_reg_lists[result.value] = (result, flag_buf)
return result.value
except (KeyError, OSError):
log.log_error(traceback.format_exc())
count[0] = 0
return None
def _get_flag_write_low_level_il(self, ctxt, op, size, write_type, flag, operands, operand_count, il):
try:
write_type_name = None
if write_type != 0:
write_type_name = self._flag_write_types_by_index[write_type]
flag_name = self._flags_by_index[flag]
operand_list = []
for i in xrange(operand_count):
if operands[i].constant:
operand_list.append(("const", operands[i].value))
elif lowlevelil.LLIL_REG_IS_TEMP(operands[i].reg):
operand_list.append(("reg", operands[i].reg))
else:
operand_list.append(("reg", self._regs_by_index[operands[i].reg]))
return self.perform_get_flag_write_low_level_il(op, size, write_type_name, flag_name, operand_list,
lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il))).index
except (KeyError, OSError):
log.log_error(traceback.format_exc())
return False
def _get_flag_condition_low_level_il(self, ctxt, cond, il):
try:
return self.perform_get_flag_condition_low_level_il(cond,
lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il))).index
except OSError:
log.log_error(traceback.format_exc())
return 0
def _free_register_list(self, ctxt, regs):
try:
buf = ctypes.cast(regs, ctypes.c_void_p)
if buf.value not in self._pending_reg_lists:
raise ValueError("freeing register list that wasn't allocated")
del self._pending_reg_lists[buf.value]
except (ValueError, KeyError):
log.log_error(traceback.format_exc())
def _get_register_info(self, ctxt, reg, result):
try:
if reg not in self._regs_by_index:
result[0].fullWidthRegister = 0
result[0].offset = 0
result[0].size = 0
result[0].extend = ImplicitRegisterExtend.NoExtend
return
info = self.__class__.regs[self._regs_by_index[reg]]
result[0].fullWidthRegister = self._all_regs[info.full_width_reg]
result[0].offset = info.offset
result[0].size = info.size
if isinstance(info.extend, str):
result[0].extend = ImplicitRegisterExtend[info.extend]
else:
result[0].extend = info.extend
except KeyError:
log.log_error(traceback.format_exc())
result[0].fullWidthRegister = 0
result[0].offset = 0
result[0].size = 0
result[0].extend = ImplicitRegisterExtend.NoExtend
def _get_stack_pointer_register(self, ctxt):
try:
return self._all_regs[self.__class__.stack_pointer]
except KeyError:
log.log_error(traceback.format_exc())
return 0
def _get_link_register(self, ctxt):
try:
if self.__class__.link_reg is None:
return 0xffffffff
return self._all_regs[self.__class__.link_reg]
except KeyError:
log.log_error(traceback.format_exc())
return 0
def _assemble(self, ctxt, code, addr, result, errors):
try:
data, error_str = self.perform_assemble(code, addr)
errors[0] = core.BNAllocString(str(error_str))
if data is None:
return False
data = str(data)
buf = ctypes.create_string_buffer(len(data))
ctypes.memmove(buf, data, len(data))
core.BNSetDataBufferContents(result, buf, len(data))
return True
except:
log.log_error(traceback.format_exc())
errors[0] = core.BNAllocString("Unhandled exception during assembly.\n")
return False
def _is_never_branch_patch_available(self, ctxt, data, addr, length):
try:
buf = ctypes.create_string_buffer(length)
ctypes.memmove(buf, data, length)
return self.perform_is_never_branch_patch_available(buf.raw, addr)
except:
log.log_error(traceback.format_exc())
return False
def _is_always_branch_patch_available(self, ctxt, data, addr, length):
try:
buf = ctypes.create_string_buffer(length)
ctypes.memmove(buf, data, length)
return self.perform_is_always_branch_patch_available(buf.raw, addr)
except:
log.log_error(traceback.format_exc())
return False
def _is_invert_branch_patch_available(self, ctxt, data, addr, length):
try:
buf = ctypes.create_string_buffer(length)
ctypes.memmove(buf, data, length)
return self.perform_is_invert_branch_patch_available(buf.raw, addr)
except:
log.log_error(traceback.format_exc())
return False
def _is_skip_and_return_zero_patch_available(self, ctxt, data, addr, length):
try:
buf = ctypes.create_string_buffer(length)
ctypes.memmove(buf, data, length)
return self.perform_is_skip_and_return_zero_patch_available(buf.raw, addr)
except:
log.log_error(traceback.format_exc())
return False
def _is_skip_and_return_value_patch_available(self, ctxt, data, addr, length):
try:
buf = ctypes.create_string_buffer(length)
ctypes.memmove(buf, data, length)
return self.perform_is_skip_and_return_value_patch_available(buf.raw, addr)
except:
log.log_error(traceback.format_exc())
return False
def _convert_to_nop(self, ctxt, data, addr, length):
try:
buf = ctypes.create_string_buffer(length)
ctypes.memmove(buf, data, length)
result = self.perform_convert_to_nop(buf.raw, addr)
if result is None:
return False
result = str(result)
if len(result) > length:
result = result[0:length]
ctypes.memmove(data, result, len(result))
return True
except:
log.log_error(traceback.format_exc())
return False
def _always_branch(self, ctxt, data, addr, length):
try:
buf = ctypes.create_string_buffer(length)
ctypes.memmove(buf, data, length)
result = self.perform_always_branch(buf.raw, addr)
if result is None:
return False
result = str(result)
if len(result) > length:
result = result[0:length]
ctypes.memmove(data, result, len(result))
return True
except:
log.log_error(traceback.format_exc())
return False
def _invert_branch(self, ctxt, data, addr, length):
try:
buf = ctypes.create_string_buffer(length)
ctypes.memmove(buf, data, length)
result = self.perform_invert_branch(buf.raw, addr)
if result is None:
return False
result = str(result)
if len(result) > length:
result = result[0:length]
ctypes.memmove(data, result, len(result))
return True
except:
log.log_error(traceback.format_exc())
return False
def _skip_and_return_value(self, ctxt, data, addr, length, value):
try:
buf = ctypes.create_string_buffer(length)
ctypes.memmove(buf, data, length)
result = self.perform_skip_and_return_value(buf.raw, addr, value)
if result is None:
return False
result = str(result)
if len(result) > length:
result = result[0:length]
ctypes.memmove(data, result, len(result))
return True
except:
log.log_error(traceback.format_exc())
return False
def perform_get_associated_arch_by_address(self, addr):
return self, addr
@abc.abstractmethod
def perform_get_instruction_info(self, data, addr):
"""
``perform_get_instruction_info`` implements a method which interpretes the bytes passed in ``data`` as an
:py:Class:`InstructionInfo` object. The InstructionInfo object should have the length of the current instruction.
If the instruction is a branch instruction the method should add a branch of the proper type:
===================== ===================================================
BranchType Description
===================== ===================================================
UnconditionalBranch Branch will always be taken
FalseBranch False branch condition
TrueBranch True branch condition
CallDestination Branch is a call instruction (Branch with Link)
FunctionReturn Branch returns from a function
SystemCall System call instruction
IndirectBranch Branch destination is a memory address or register
UnresolvedBranch Call instruction that isn't
===================== ===================================================
:param str data: bytes to decode
:param int addr: virtual address of the byte to be decoded
:return: a :py:class:`InstructionInfo` object containing the length and branche types for the given instruction
:rtype: InstructionInfo
"""
raise NotImplementedError
@abc.abstractmethod
def perform_get_instruction_text(self, data, addr):
"""
``perform_get_instruction_text`` implements a method which interpretes the bytes passed in ``data`` as a
list of :py:class:`InstructionTextToken` objects.
:param str data: bytes to decode
:param int addr: virtual address of the byte to be decoded
:return: a tuple of list(InstructionTextToken) and length of instruction decoded
:rtype: tuple(list(InstructionTextToken), int)
"""
raise NotImplementedError
@abc.abstractmethod
def perform_get_instruction_low_level_il(self, data, addr, il):
"""
``perform_get_instruction_low_level_il`` implements a method to interpret the bytes passed in ``data`` to
low-level IL instructions. The il instructions must be appended to the :py:class:`LowLevelILFunction`.
.. note:: Architecture subclasses should implement this method.
:param str data: bytes to be interpreted as low-level IL instructions
:param int addr: virtual address of start of ``data``
:param LowLevelILFunction il: LowLevelILFunction object to append LowLevelILExpr objects to
:rtype: None
"""
raise NotImplementedError
@abc.abstractmethod
def perform_get_flag_write_low_level_il(self, op, size, write_type, flag, operands, il):
"""
.. note:: Architecture subclasses should implement this method.
.. warning:: This method should never be called directly.
:param LowLevelILOperation op:
:param int size:
:param int write_type:
:param int flag:
:param list(int_or_str):
:param LowLevelILFunction il:
:rtype: LowLevelILExpr
"""
return il.unimplemented()
@abc.abstractmethod
def perform_get_flag_condition_low_level_il(self, cond, il):
"""
.. note:: Architecture subclasses should implement this method.
.. warning:: This method should never be called directly.
:param LowLevelILFlagCondition cond:
:param LowLevelILFunction il:
:rtype: LowLevelILExpr
"""
return il.unimplemented()
@abc.abstractmethod
def perform_assemble(self, code, addr):
"""
``perform_assemble`` implements a method to convert the string of assembly instructions ``code`` loaded at
virtual address ``addr`` to the byte representation of those instructions. This can be done by simply shelling
out to an assembler like yasm or llvm-mc, since this method isn't performance sensitive.
.. note:: Architecture subclasses should implement this method.
.. note :: It is important that the assembler used accepts a syntax identical to the one emitted by the \
disassembler. This will prevent confusing the user.
.. warning:: This method should never be called directly.
:param str code: string representation of the instructions to be assembled
:param int addr: virtual address that the instructions will be loaded at
:return: the bytes for the assembled instructions or error string
:rtype: (a tuple of instructions and empty string) or (or None and error string)
"""
return None, "Architecture does not implement an assembler.\n"
@abc.abstractmethod
def perform_is_never_branch_patch_available(self, data, addr):
"""
``perform_is_never_branch_patch_available`` implements a check to determine if the instruction represented by
the bytes contained in ``data`` at address addr is a branch instruction that can be made to never branch.
.. note:: Architecture subclasses should implement this method.
.. warning:: This method should never be called directly.
:param str data: bytes to be checked
:param int addr: the virtual address of the instruction to be patched
:return: True if the instruction can be patched, False otherwise
:rtype: bool
"""
return False
@abc.abstractmethod
def perform_is_always_branch_patch_available(self, data, addr):
"""
``perform_is_always_branch_patch_available`` implements a check to determine if the instruction represented by
the bytes contained in ``data`` at address addr is a conditional branch that can be made unconditional.
.. note:: Architecture subclasses should implement this method.
.. warning:: This method should never be called directly.
:param str data: bytes to be checked
:param int addr: the virtual address of the instruction to be patched
:return: True if the instruction can be patched, False otherwise
:rtype: bool
"""
return False
@abc.abstractmethod
def perform_is_invert_branch_patch_available(self, data, addr):
"""
``perform_is_invert_branch_patch_available`` implements a check to determine if the instruction represented by
the bytes contained in ``data`` at address addr is a conditional branch which can be inverted.
.. note:: Architecture subclasses should implement this method.
.. warning:: This method should never be called directly.
:param int addr: the virtual address of the instruction to be patched
:return: True if the instruction can be patched, False otherwise
:rtype: bool
"""
return False
@abc.abstractmethod
def perform_is_skip_and_return_zero_patch_available(self, data, addr):
"""
``perform_is_skip_and_return_zero_patch_available`` implements a check to determine if the instruction represented by
the bytes contained in ``data`` at address addr is a *call-like* instruction which can made into instructions
that are equivilent to "return 0". For example if ``data`` was the x86 instruction ``call eax`` which could be
converted into ``xor eax,eax`` thus this function would return True.
.. note:: Architecture subclasses should implement this method.
.. warning:: This method should never be called directly.
:param str data: bytes to be checked
:param int addr: the virtual address of the instruction to be patched
:return: True if the instruction can be patched, False otherwise
:rtype: bool
"""
return False
@abc.abstractmethod
def perform_is_skip_and_return_value_patch_available(self, data, addr):
"""
``perform_is_skip_and_return_value_patch_available`` implements a check to determine if the instruction represented by
the bytes contained in ``data`` at address addr is a *call-like* instruction which can made into instructions
that are equivilent to "return 0". For example if ``data`` was the x86 instruction ``call 0xdeadbeef`` which could be
converted into ``mov eax, 42`` thus this function would return True.
.. note:: Architecture subclasses should implement this method.
.. warning:: This method should never be called directly.
:param str data: bytes to be checked
:param int addr: the virtual address of the instruction to be patched
:return: True if the instruction can be patched, False otherwise
:rtype: bool
"""
return False
@abc.abstractmethod
def perform_convert_to_nop(self, data, addr):
"""
``perform_convert_to_nop`` implements a method which returns a nop sequence of len(data) bytes long.
.. note:: Architecture subclasses should implement this method.
.. warning:: This method should never be called directly.
:param str data: bytes at virtual address ``addr``
:param int addr: the virtual address of the instruction to be patched
:return: nop sequence of same length as ``data`` or None
:rtype: str or None
"""
return None
@abc.abstractmethod
def perform_always_branch(self, data, addr):
"""
``perform_always_branch`` implements a method which converts the branch represented by the bytes in ``data`` to
at ``addr`` to an unconditional branch.
.. note:: Architecture subclasses should implement this method.
.. warning:: This method should never be called directly.
:param str data: bytes to be checked
:param int addr: the virtual address of the instruction to be patched
:return: The bytes of the replacement unconditional branch instruction
:rtype: str
"""
return None
@abc.abstractmethod
def perform_invert_branch(self, data, addr):
"""
``perform_invert_branch`` implements a method which inverts the branch represented by the bytes in ``data`` to
at ``addr``.
.. note:: Architecture subclasses should implement this method.
.. warning:: This method should never be called directly.
:param str data: bytes to be checked
:param int addr: the virtual address of the instruction to be patched
:return: The bytes of the replacement unconditional branch instruction
:rtype: str
"""
return None
@abc.abstractmethod
def perform_skip_and_return_value(self, data, addr, value):
"""
``perform_skip_and_return_value`` implements a method which converts a *call-like* instruction represented by
the bytes in ``data`` at ``addr`` to one or more instructions that are equivilent to a function returning a
value.
.. note:: Architecture subclasses should implement this method.
.. warning:: This method should never be called directly.
:param str data: bytes to be checked
:param int addr: the virtual address of the instruction to be patched
:param int value: value to be returned
:return: The bytes of the replacement unconditional branch instruction
:rtype: str
"""
return None
def get_associated_arch_by_address(self, addr):
new_addr = ctypes.c_ulonglong()
new_addr.value = addr
result = core.BNGetAssociatedArchitectureByAddress(self.handle, new_addr)
return Architecture(handle = result), new_addr.value
def get_instruction_info(self, data, addr):
"""
``get_instruction_info`` returns an InstructionInfo object for the instruction at the given virtual address
``addr`` with data ``data``.
.. note :: The instruction info object should always set the InstructionInfo.length to the instruction length, \
and the branches of the proper types shoulde be added if the instruction is a branch.
:param str data: max_instruction_length bytes from the binary at virtual address ``addr``
:param int addr: virtual address of bytes in ``data``
:return: the InstructionInfo for the current instruction
:rtype: InstructionInfo
"""
info = core.BNInstructionInfo()
data = str(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
if not core.BNGetInstructionInfo(self.handle, buf, addr, len(data), info):
return None
result = function.InstructionInfo()
result.length = info.length
result.branch_delay = info.branchDelay
for i in xrange(0, info.branchCount):
branch_type = BranchType(info.branchType[i]).name
target = info.branchTarget[i]
if info.branchArch[i]:
arch = Architecture(info.branchArch[i])
else:
arch = None
result.add_branch(branch_type, target, arch)
return result
def get_instruction_text(self, data, addr):
"""
``get_instruction_text`` returns a list of InstructionTextToken objects for the instruction at the given virtual
address ``addr`` with data ``data``.
:param str data: max_instruction_length bytes from the binary at virtual address ``addr``
:param int addr: virtual address of bytes in ``data``
:return: an InstructionTextToken list for the current instruction
:rtype: list(InstructionTextToken)
"""
data = str(data)
count = ctypes.c_ulonglong()
length = ctypes.c_ulonglong()
length.value = len(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
tokens = ctypes.POINTER(core.BNInstructionTextToken)()
if not core.BNGetInstructionText(self.handle, buf, addr, length, tokens, count):
return None, 0
result = []
for i in xrange(0, count.value):
token_type = InstructionTextTokenType(tokens[i].type)
text = tokens[i].text
value = tokens[i].value
size = tokens[i].size
operand = tokens[i].operand
result.append(function.InstructionTextToken(token_type, text, value, size, operand))
core.BNFreeInstructionText(tokens, count.value)
return result, length.value
def get_instruction_low_level_il_instruction(self, bv, addr):
il = lowlevelil.LowLevelILFunction(self)
data = bv.read(addr, self.max_instr_length)
self.get_instruction_low_level_il(data, addr, il)
return il[0]
def get_instruction_low_level_il(self, data, addr, il):
"""
``get_instruction_low_level_il`` appends LowLevelILExpr objects for the instruction at the given virtual
address ``addr`` with data ``data``.
:param str data: max_instruction_length bytes from the binary at virtual address ``addr``
:param int addr: virtual address of bytes in ``data``
:param LowLevelILFunction il: The function the current instruction belongs to
:return: the length of the current instruction
:rtype: int
"""
data = str(data)
length = ctypes.c_ulonglong()
length.value = len(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
core.BNGetInstructionLowLevelIL(self.handle, buf, addr, length, il.handle)
return length.value
def get_reg_name(self, reg):
"""
``get_reg_name`` gets a register name from a register number.
:param int reg: register number
:return: the corresponding register string
:rtype: str
"""
return core.BNGetArchitectureRegisterName(self.handle, reg)
def get_flag_name(self, flag):
"""
``get_flag_name`` gets a flag name from a flag number.
:param int reg: register number
:return: the corresponding register string
:rtype: str
"""
return core.BNGetArchitectureFlagName(self.handle, flag)
def get_flag_write_type_name(self, write_type):
"""
``get_flag_write_type_name`` gets the flag write type name for the given flag.
:param int write_type: flag
:return: flag write type name
:rtype: str
"""
return core.BNGetArchitectureFlagWriteTypeName(self.handle, write_type)
def get_flag_by_name(self, flag):
"""
``get_flag_by_name`` get flag name for flag index.
:param int flag: flag index
:return: flag name for flag index
:rtype: str
"""
return self._flags[flag]
def get_flag_write_type_by_name(self, write_type):
"""
``get_flag_write_type_by_name`` gets the flag write type name for the flage write type.
:param int write_type: flag write type
:return: flag write type
:rtype: str
"""
return self._flag_write_types[write_type]
def get_flag_write_low_level_il(self, op, size, write_type, operands, il):
"""
:param LowLevelILOperation op:
:param int size:
:param str write_type:
:param list(str or int) operands: a list of either items that are either string register names or constant \
integer values
:param LowLevelILFunction il:
:rtype: LowLevelILExpr
"""
operand_list = (core.BNRegisterOrConstant * len(operands))()
for i in xrange(len(operands)):
if isinstance(operands[i], str):
operand_list[i].constant = False
operand_list[i].reg = self._flags[operands[i]]
else:
operand_list[i].constant = True
operand_list[i].value = operands[i]
return lowlevelil.LowLevelILExpr(core.BNGetArchitectureFlagWriteLowLevelIL(self.handle, op, size,
self._flag_write_types[write_type], operand_list, len(operand_list), il.handle))
def get_default_flag_write_low_level_il(self, op, size, write_type, operands, il):
"""
:param LowLevelILOperation op:
:param int size:
:param str write_type:
:param list(str or int) operands: a list of either items that are either string register names or constant \
integer values
:param LowLevelILFunction il:
:rtype: LowLevelILExpr index
"""
operand_list = (core.BNRegisterOrConstant * len(operands))()
for i in xrange(len(operands)):
if isinstance(operands[i], str):
operand_list[i].constant = False
operand_list[i].reg = self._flags[operands[i]]
else:
operand_list[i].constant = True
operand_list[i].value = operands[i]
return lowlevelil.LowLevelILExpr(core.BNGetDefaultArchitectureFlagWriteLowLevelIL(self.handle, op, size,
self._flag_write_types[write_type], operand_list, len(operand_list), il.handle))
def get_flag_condition_low_level_il(self, cond, il):
"""
:param LowLevelILFlagCondition cond:
:param LowLevelILFunction il:
:rtype: LowLevelILExpr
"""
return lowlevelil.LowLevelILExpr(core.BNGetArchitectureFlagConditionLowLevelIL(self.handle, cond, il.handle))
def get_modified_regs_on_write(self, reg):
"""
``get_modified_regs_on_write`` returns a list of register names that are modified when ``reg`` is written.
:param str reg: string register name
:return: list of register names
:rtype: list(str)
"""
reg = core.BNGetArchitectureRegisterByName(self.handle, str(reg))
count = ctypes.c_ulonglong()
regs = core.BNGetModifiedArchitectureRegistersOnWrite(self.handle, reg, count)
result = []
for i in xrange(0, count.value):
result.append(core.BNGetArchitectureRegisterName(self.handle, regs[i]))
core.BNFreeRegisterList(regs)
return result
def assemble(self, code, addr=0):
"""
``assemble`` converts the string of assembly instructions ``code`` loaded at virtual address ``addr`` to the
byte representation of those instructions.
:param str code: string representation of the instructions to be assembled
:param int addr: virtual address that the instructions will be loaded at
:return: the bytes for the assembled instructions or error string
:rtype: (a tuple of instructions and empty string) or (or None and error string)
:Example:
>>> arch.assemble("je 10")
('\\x0f\\x84\\x04\\x00\\x00\\x00', '')
>>>
"""
result = databuffer.DataBuffer()
errors = ctypes.c_char_p()
if not core.BNAssemble(self.handle, code, addr, result.handle, errors):
return None, errors.value
return str(result), errors.value
def is_never_branch_patch_available(self, data, addr):
"""
``is_never_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be made to **never branch**.
:param str data: bytes for the instruction to be checked
:param int addr: the virtual address of the instruction to be patched
:return: True if the instruction can be patched, False otherwise
:rtype: bool
:Example:
>>> arch.is_never_branch_patch_available(arch.assemble("je 10")[0], 0)
True
>>> arch.is_never_branch_patch_available(arch.assemble("nop")[0], 0)
False
>>>
"""
data = str(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
return core.BNIsArchitectureNeverBranchPatchAvailable(self.handle, buf, addr, len(data))
def is_always_branch_patch_available(self, data, addr):
"""
``is_always_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be made to
**always branch**.
:param str data: bytes for the instruction to be checked
:param int addr: the virtual address of the instruction to be patched
:return: True if the instruction can be patched, False otherwise
:rtype: bool
:Example:
>>> arch.is_always_branch_patch_available(arch.assemble("je 10")[0], 0)
True
>>> arch.is_always_branch_patch_available(arch.assemble("nop")[0], 0)
False
>>>
"""
data = str(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
return core.BNIsArchitectureAlwaysBranchPatchAvailable(self.handle, buf, addr, len(data))
def is_invert_branch_patch_available(self, data, addr):
"""
``is_always_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be inverted.
:param str data: bytes for the instruction to be checked
:param int addr: the virtual address of the instruction to be patched
:return: True if the instruction can be patched, False otherwise
:rtype: bool
:Example:
>>> arch.is_invert_branch_patch_available(arch.assemble("je 10")[0], 0)
True
>>> arch.is_invert_branch_patch_available(arch.assemble("nop")[0], 0)
False
>>>
"""
data = str(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
return core.BNIsArchitectureInvertBranchPatchAvailable(self.handle, buf, addr, len(data))
def is_skip_and_return_zero_patch_available(self, data, addr):
"""
``is_skip_and_return_zero_patch_available`` determines if the instruction ``data`` at ``addr`` is a *call-like*
instruction that can be made into an instruction *returns zero*.
:param str data: bytes for the instruction to be checked
:param int addr: the virtual address of the instruction to be patched
:return: True if the instruction can be patched, False otherwise
:rtype: bool
:Example:
>>> arch.is_skip_and_return_zero_patch_available(arch.assemble("call 0")[0], 0)
True
>>> arch.is_skip_and_return_zero_patch_available(arch.assemble("call eax")[0], 0)
True
>>> arch.is_skip_and_return_zero_patch_available(arch.assemble("jmp eax")[0], 0)
False
>>>
"""
data = str(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
return core.BNIsArchitectureSkipAndReturnZeroPatchAvailable(self.handle, buf, addr, len(data))
def is_skip_and_return_value_patch_available(self, data, addr):
"""
``is_skip_and_return_zero_patch_available`` determines if the instruction ``data`` at ``addr`` is a *call-like*
instruction that can be made into an instruction *returns a value*.
:param str data: bytes for the instruction to be checked
:param int addr: the virtual address of the instruction to be patched
:return: True if the instruction can be patched, False otherwise
:rtype: bool
:Example:
>>> arch.is_skip_and_return_zero_patch_available(arch.assemble("call 0")[0], 0)
True
>>> arch.is_skip_and_return_zero_patch_available(arch.assemble("jmp eax")[0], 0)
False
>>>
"""
data = str(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
return core.BNIsArchitectureSkipAndReturnValuePatchAvailable(self.handle, buf, addr, len(data))
def convert_to_nop(self, data, addr):
"""
``convert_to_nop`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of nop
instructions of the same length as data.
:param str data: bytes for the instruction to be converted
:param int addr: the virtual address of the instruction to be patched
:return: string containing len(data) worth of no-operation instructions
:rtype: str
:Example:
>>> arch.convert_to_nop("\\x00\\x00", 0)
'\\x90\\x90'
>>>
"""
data = str(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
if not core.BNArchitectureConvertToNop(self.handle, buf, addr, len(data)):
return None
result = ctypes.create_string_buffer(len(data))
ctypes.memmove(result, buf, len(data))
return result.raw
def always_branch(self, data, addr):
"""
``always_branch`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of bytes
of the same length which always branches.
:param str data: bytes for the instruction to be converted
:param int addr: the virtual address of the instruction to be patched
:return: string containing len(data) which always branches to the same location as the provided instruction
:rtype: str
:Example:
>>> bytes = arch.always_branch(arch.assemble("je 10")[0], 0)
>>> arch.get_instruction_text(bytes, 0)
(['nop '], 1L)
>>> arch.get_instruction_text(bytes[1:], 0)
(['jmp ', '0x9'], 5L)
>>>
"""
data = str(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
if not core.BNArchitectureAlwaysBranch(self.handle, buf, addr, len(data)):
return None
result = ctypes.create_string_buffer(len(data))
ctypes.memmove(result, buf, len(data))
return result.raw
def invert_branch(self, data, addr):
"""
``invert_branch`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of bytes
of the same length which inverts the branch of provided instruction.
:param str data: bytes for the instruction to be converted
:param int addr: the virtual address of the instruction to be patched
:return: string containing len(data) which always branches to the same location as the provided instruction
:rtype: str
:Example:
>>> arch.get_instruction_text(arch.invert_branch(arch.assemble("je 10")[0], 0), 0)
(['jne ', '0xa'], 6L)
>>> arch.get_instruction_text(arch.invert_branch(arch.assemble("jo 10")[0], 0), 0)
(['jno ', '0xa'], 6L)
>>> arch.get_instruction_text(arch.invert_branch(arch.assemble("jge 10")[0], 0), 0)
(['jl ', '0xa'], 6L)
>>>
"""
data = str(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
if not core.BNArchitectureInvertBranch(self.handle, buf, addr, len(data)):
return None
result = ctypes.create_string_buffer(len(data))
ctypes.memmove(result, buf, len(data))
return result.raw
def skip_and_return_value(self, data, addr, value):
"""
``skip_and_return_value`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of
bytes of the same length which doesn't call and instead *return a value*.
:param str data: bytes for the instruction to be converted
:param int addr: the virtual address of the instruction to be patched
:return: string containing len(data) which always branches to the same location as the provided instruction
:rtype: str
:Example:
>>> arch.get_instruction_text(arch.skip_and_return_value(arch.assemble("call 10")[0], 0, 0), 0)
(['mov ', 'eax', ', ', '0x0'], 5L)
>>>
"""
data = str(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
if not core.BNArchitectureSkipAndReturnValue(self.handle, buf, addr, len(data), value):
return None
result = ctypes.create_string_buffer(len(data))
ctypes.memmove(result, buf, len(data))
return result.raw
def is_view_type_constant_defined(self, type_name, const_name):
"""
:param str type_name: the BinaryView type name of the constant to query
:param str const_name: the constant name to query
:rtype: None
:Example:
>>> arch.set_view_type_constant("ELF", "R_COPY", ELF_RELOC_COPY)
>>> arch.is_view_type_constant_defined("ELF", "R_COPY")
True
>>> arch.is_view_type_constant_defined("ELF", "NOT_THERE")
False
>>>
"""
return core.BNIsBinaryViewTypeArchitectureConstantDefined(self.handle, type_name, const_name)
def get_view_type_constant(self, type_name, const_name, default_value=0):
"""
``get_view_type_constant`` retrieves the view type constant for the given type_name and const_name.
:param str type_name: the BinaryView type name of the constant to be retrieved
:param str const_name: the constant name to retrieved
:param int value: optional default value if the type_name is not present. default value is zero.
:return: The BinaryView type constant or the default_value if not found
:rtype: int
:Example:
>>> ELF_RELOC_COPY = 5
>>> arch.set_view_type_constant("ELF", "R_COPY", ELF_RELOC_COPY)
>>> arch.get_view_type_constant("ELF", "R_COPY")
5L
>>> arch.get_view_type_constant("ELF", "NOT_HERE", 100)
100L
"""
return core.BNGetBinaryViewTypeArchitectureConstant(self.handle, type_name, const_name, default_value)
def set_view_type_constant(self, type_name, const_name, value):
"""
``set_view_type_constant`` creates a new binaryview type constant.
:param str type_name: the BinaryView type name of the constant to be registered
:param str const_name: the constant name to register
:param int value: the value of the constant
:rtype: None
:Example:
>>> ELF_RELOC_COPY = 5
>>> arch.set_view_type_constant("ELF", "R_COPY", ELF_RELOC_COPY)
>>>
"""
core.BNSetBinaryViewTypeArchitectureConstant(self.handle, type_name, const_name, value)
def parse_types_from_source(self, source, filename=None, include_dirs=[]):
"""
``parse_types_from_source`` parses the source string and any needed headers searching for them in
the optional list of directories provided in ``include_dirs``.
:param str source: source string to be parsed
:param str filename: optional source filename
:param list(str) include_dirs: optional list of string filename include directories
:return: a tuple of py:class:`TypeParserResult` and error string
:rtype: tuple(TypeParserResult,str)
:Example:
>>> arch.parse_types_from_source('int foo;\\nint bar(int x);\\nstruct bas{int x,y;};\\n')
({types: {'bas': <type: struct bas>}, variables: {'foo': <type: int32_t>}, functions:{'bar':
<type: int32_t(int32_t x)>}}, '')
>>>
"""
if filename is None:
filename = "input"
dir_buf = (ctypes.c_char_p * len(include_dirs))()
for i in xrange(0, len(include_dirs)):
dir_buf[i] = str(include_dirs[i])
parse = core.BNTypeParserResult()
errors = ctypes.c_char_p()
result = core.BNParseTypesFromSource(self.handle, source, filename, parse, errors, dir_buf, len(include_dirs))
error_str = errors.value
core.BNFreeString(ctypes.cast(errors, ctypes.POINTER(ctypes.c_byte)))
if not result:
return (None, error_str)
type_dict = {}
variables = {}
functions = {}
for i in xrange(0, parse.typeCount):
types[parse.types[i].name] = types.Type(core.BNNewTypeReference(parse.types[i].type))
for i in xrange(0, parse.variableCount):
variables[parse.variables[i].name] = types.Type(core.BNNewTypeReference(parse.variables[i].type))
for i in xrange(0, parse.functionCount):
functions[parse.functions[i].name] = types.Type(core.BNNewTypeReference(parse.functions[i].type))
core.BNFreeTypeParserResult(parse)
return (types.TypeParserResult(type_dict, variables, functions), error_str)
def parse_types_from_source_file(self, filename, include_dirs=[]):
"""
``parse_types_from_source_file`` parses the source file ``filename`` and any needed headers searching for them in
the optional list of directories provided in ``include_dirs``.
:param str filename: filename of file to be parsed
:param list(str) include_dirs: optional list of string filename include directories
:return: a tuple of py:class:`TypeParserResult` and error string
:rtype: tuple(TypeParserResult, str)
:Example:
>>> file = "/Users/binja/tmp.c"
>>> open(file).read()
'int foo;\\nint bar(int x);\\nstruct bas{int x,y;};\\n'
>>> arch.parse_types_from_source_file(file)
({types: {'bas': <type: struct bas>}, variables: {'foo': <type: int32_t>}, functions:
{'bar': <type: int32_t(int32_t x)>}}, '')
>>>
"""
dir_buf = (ctypes.c_char_p * len(include_dirs))()
for i in xrange(0, len(include_dirs)):
dir_buf[i] = str(include_dirs[i])
parse = core.BNTypeParserResult()
errors = ctypes.c_char_p()
result = core.BNParseTypesFromSourceFile(self.handle, filename, parse, errors, dir_buf, len(include_dirs))
error_str = errors.value
core.BNFreeString(ctypes.cast(errors, ctypes.POINTER(ctypes.c_byte)))
if not result:
return (None, error_str)
type_dict = {}
variables = {}
functions = {}
for i in xrange(0, parse.typeCount):
type_dict[parse.types[i].name] = types.Type(core.BNNewTypeReference(parse.types[i].type))
for i in xrange(0, parse.variableCount):
variables[parse.variables[i].name] = types.Type(core.BNNewTypeReference(parse.variables[i].type))
for i in xrange(0, parse.functionCount):
functions[parse.functions[i].name] = types.Type(core.BNNewTypeReference(parse.functions[i].type))
core.BNFreeTypeParserResult(parse)
return (types.TypeParserResult(type_dict, variables, functions), error_str)
def register_calling_convention(self, cc):
"""
``register_calling_convention`` registers a new calling convention for the Architecture.
:param CallingConvention cc: CallingConvention object to be registered
:rtype: None
"""
core.BNRegisterCallingConvention(self.handle, cc.handle)
class ReferenceSource(object):
def __init__(self, func, arch, addr):
self.function = func
self.arch = arch
self.address = addr
def __repr__(self):
if self.arch:
return "<ref: %s@%#x>" % (self.arch.name, self.address)
else:
return "<ref: %#x>" % self.address
|