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
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
|
# coding=utf-8
# Copyright (c) 2015-2021 Vector 35 Inc
#
# 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 ctypes
import inspect
from typing import Generator, Optional, List, Tuple, Union, Mapping, Any
# Binary Ninja components
from . import _binaryninjacore as core
from .enums import (AnalysisSkipReason, FunctionGraphType, SymbolType, InstructionTextTokenType,
HighlightStandardColor, HighlightColorStyle,
DisassemblyOption, IntegerDisplayType, InstructionTextTokenContext,
FunctionAnalysisSkipOverride)
from . import associateddatastore # Required in the main scope due to being an argument for _FunctionAssociatedDataStore
from . import types
from . import architecture
from . import lowlevelil
from . import mediumlevelil
from . import highlevelil
from . import binaryview
from . import basicblock
from . import variable
from . import flowgraph
from . import callingconvention
from . import workflow
# we define the following as such so the linter doesn't confuse 'highlight' the module with the
# property of the same name. There is probably some other work around but it eludes me.
from . import highlight as _highlight
from . import platform as _platform
ExpressionIndex = int
InstructionIndex = int
AnyFunctionType = Union['Function', 'lowlevelil.LowLevelILFunction', 'mediumlevelil.MediumLevelILFunction',
'highlevelil.HighLevelILFunction']
ILFunctionType = Union['lowlevelil.LowLevelILFunction', 'mediumlevelil.MediumLevelILFunction',
'highlevelil.HighLevelILFunction']
ILInstructionType = Union['lowlevelil.LowLevelILInstruction', 'mediumlevelil.MediumLevelILInstruction',
'highlevelil.HighLevelILInstruction']
def _function_name_():
return inspect.stack()[1][0].f_code.co_name
class ArchAndAddr:
def __init__(self, arch:Optional['architecture.Architecture']=None, addr:int=0):
self._arch = architecture.CoreArchitecture._from_cache(arch)
self._addr = addr
def __repr__(self):
return "archandaddr <%s @ %#x>" % (self._arch.name, self._addr)
@property
def arch(self) -> 'architecture.Architecture':
return self._arch
@property
def addr(self) -> int:
return self._addr
class _FunctionAssociatedDataStore(associateddatastore._AssociatedDataStore):
_defaults = {}
class DisassemblySettings:
def __init__(self, handle:core.BNDisassemblySettings=None):
if handle is None:
self.handle = core.BNCreateDisassemblySettings()
else:
self.handle = handle
def __del__(self):
core.BNFreeDisassemblySettings(self.handle)
@property
def width(self) -> int:
return core.BNGetDisassemblyWidth(self.handle)
@width.setter
def width(self, value:int) -> None:
core.BNSetDisassemblyWidth(self.handle, value)
@property
def max_symbol_width(self) -> int:
return core.BNGetDisassemblyMaximumSymbolWidth(self.handle)
@max_symbol_width.setter
def max_symbol_width(self, value:int) -> None:
core.BNSetDisassemblyMaximumSymbolWidth(self.handle, value)
def is_option_set(self, option:DisassemblyOption) -> bool:
if isinstance(option, str):
option = DisassemblyOption[option]
return core.BNIsDisassemblySettingsOptionSet(self.handle, option)
def set_option(self, option:DisassemblyOption, state:bool=True) -> None:
if isinstance(option, str):
option = DisassemblyOption[option]
core.BNSetDisassemblySettingsOption(self.handle, option, state)
class ILReferenceSource:
def __init__(self, func:Optional['Function'], arch:Optional['architecture.Architecture'], addr:int,
il_type:FunctionGraphType, expr_id:ExpressionIndex):
self._function = func
self._arch = arch
self._address = addr
self._il_type = il_type
self._expr_id = expr_id
@staticmethod
def get_il_name(il_type):
if il_type == FunctionGraphType.NormalFunctionGraph:
return 'disassembly'
if il_type == FunctionGraphType.LowLevelILFunctionGraph:
return 'llil'
if il_type == FunctionGraphType.LiftedILFunctionGraph:
return 'lifted_llil'
if il_type == FunctionGraphType.LowLevelILSSAFormFunctionGraph:
return 'llil_ssa'
if il_type == FunctionGraphType.MediumLevelILFunctionGraph:
return 'mlil'
if il_type == FunctionGraphType.MediumLevelILSSAFormFunctionGraph:
return 'mlil_ssa'
if il_type == FunctionGraphType.MappedMediumLevelILFunctionGraph:
return 'mapped_mlil'
if il_type == FunctionGraphType.MappedMediumLevelILSSAFormFunctionGraph:
return 'mapped_mlil_ssa'
if il_type == FunctionGraphType.HighLevelILFunctionGraph:
return 'hlil'
if il_type == FunctionGraphType.HighLevelILSSAFormFunctionGraph:
return 'hlil_ssa'
def __repr__(self):
if self._arch:
return "<ref: %s@%#x, %s@%d>" %\
(self._arch.name, self._address, self.get_il_name(self._il_type), self._expr_id)
else:
return "<ref: %#x, %s@%d>" %\
(self._address, self.get_il_name(self._il_type), self._expr_id)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return (self.function, self._arch, self._address, self._il_type, self._expr_id) ==\
(other._address, other._function, other._arch, other._il_type, other._expr_id)
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __hash__(self):
return hash((self._function, self._arch, self._address, self._il_type, self._expr_id))
@property
def function(self) -> Optional['Function']:
return self._function
@function.setter
def function(self, value:'Function') -> None:
self._function = value
@property
def arch(self) -> Optional['architecture.Architecture']:
return self._arch
@arch.setter
def arch(self, value) -> None:
self._arch = value
@property
def address(self) -> int:
return self._address
@address.setter
def address(self, value:int) -> None:
self._address = value
@property
def il_type(self) -> FunctionGraphType:
return self._il_type
@il_type.setter
def il_type(self, value:FunctionGraphType) -> None:
self._il_type = value
@property
def expr_id(self) -> ExpressionIndex:
return self._expr_id
@expr_id.setter
def expr_id(self, value:ExpressionIndex) -> None:
self._expr_id = value
class VariableReferenceSource:
def __init__(self, var:'variable.Variable', src:ILReferenceSource):
self._var = var
self._src = src
def __repr__(self):
return "<var: %s, src: %s>" % (repr(self._var), repr(self._src))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return (self.var == other.var) and (self.src == other.src)
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
@property
def var(self) -> 'variable.Variable':
return self._var
@var.setter
def var(self, value:'variable.Variable') -> None:
self._var = value
@property
def src(self) -> ILReferenceSource:
return self._src
@src.setter
def src(self, value:ILReferenceSource) -> None:
self._src = value
class Function:
_associated_data = {}
def __init__(self, view:Optional['binaryview.BinaryView']=None, handle:Optional[core.BNFunction]=None):
self._advanced_analysis_requests = 0
assert handle is not None, "creation of standalone 'Function' objects is not implemented"
self.handle = core.handle_of_type(handle, core.BNFunction)
if view is None:
self._view = binaryview.BinaryView(handle = core.BNGetFunctionData(self.handle))
else:
self._view = view
self._arch = None
self._platform = None
def __del__(self):
if self.handle is not None:
if self._advanced_analysis_requests > 0:
core.BNReleaseAdvancedFunctionAnalysisDataMultiple(self.handle, self._advanced_analysis_requests)
core.BNFreeFunction(self.handle)
def __repr__(self):
arch = self.arch
if arch:
return "<func: %s@%#x>" % (arch.name, self.start)
else:
return "<func: %#x>" % self.start
def __eq__(self, other:'Function') -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return ctypes.addressof(self.handle.contents) == ctypes.addressof(other.handle.contents)
def __ne__(self, other:'Function') -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __lt__(self, other:'Function') -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return self.start < other.start
def __gt__(self, other:'Function') -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return self.start > other.start
def __le__(self, other:'Function') -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return self.start <= other.start
def __ge__(self, other:'Function') -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return self.start >= other.start
def __hash__(self):
return hash((self.start, self.arch, self.platform))
def __getitem__(self, i) -> 'basicblock.BasicBlock':
count = ctypes.c_ulonglong()
blocks = core.BNGetFunctionBasicBlockList(self.handle, count)
assert blocks is not None, "core.BNGetFunctionBasicBlockList returned None"
try:
if i < 0:
i = count.value + i
if i < -count.value or i >= count.value:
raise IndexError("index out of range")
if i < 0:
i = count.value + i
core_block = core.BNNewBasicBlockReference(blocks[i])
assert core_block is not None
return basicblock.BasicBlock(core_block, self._view)
finally:
core.BNFreeBasicBlockList(blocks, count.value)
def __iter__(self) -> Generator['basicblock.BasicBlock', None, None]:
count = ctypes.c_ulonglong()
blocks = core.BNGetFunctionBasicBlockList(self.handle, count)
assert blocks is not None, "core.BNGetFunctionBasicBlockList returned None"
try:
for i in range(0, count.value):
block = core.BNNewBasicBlockReference(blocks[i])
assert block is not None
yield basicblock.BasicBlock(block, self._view)
finally:
core.BNFreeBasicBlockList(blocks, count.value)
def __str__(self):
result = ""
for token in self.type_tokens:
result += token.text
return result
@classmethod
def _unregister(cls, func:'core.BNFunction') -> None:
handle = ctypes.cast(func, ctypes.c_void_p)
if handle.value in cls._associated_data:
del cls._associated_data[handle.value]
@staticmethod
def set_default_session_data(name:str, value) -> None:
_FunctionAssociatedDataStore.set_default(name, value)
@property
def name(self) -> str:
"""Symbol name for the function"""
return self.symbol.name
@name.setter
def name(self, value:Union[str, 'types.Symbol']) -> None: # type: ignore
if value is None:
if self.symbol is not None:
self.view.undefine_user_symbol(self.symbol)
elif isinstance(value, str):
symbol = types.Symbol(SymbolType.FunctionSymbol, self.start, value)
self.view.define_user_symbol(symbol)
elif isinstance(value, types.Symbol):
self.view.define_user_symbol(value)
@property
def view(self) -> 'binaryview.BinaryView':
"""Function view (read-only)"""
return self._view
@property
def arch(self) -> Optional['architecture.Architecture']:
"""Function architecture (read-only)"""
if self._arch:
return self._arch
else:
arch = core.BNGetFunctionArchitecture(self.handle)
assert arch is not None
self._arch = architecture.CoreArchitecture._from_cache(arch)
return self._arch
@property
def platform(self) -> Optional['_platform.Platform']:
"""Function platform (read-only)"""
if self._platform:
return self._platform
else:
plat = core.BNGetFunctionPlatform(self.handle)
if plat is None:
return None
self._platform = _platform.Platform(handle = plat)
return self._platform
@property
def start(self) -> int:
"""Function start address (read-only)"""
return core.BNGetFunctionStart(self.handle)
@property
def total_bytes(self) -> int:
"""
Total bytes of a function calculated by summing each basic_block. Because basic blocks can overlap and
have gaps between them this may or may not be equivalent to a .size property.
"""
return sum(map(len, self))
@property
def highest_address(self) -> int:
"""The highest (largest) virtual address contained in a function."""
return core.BNGetFunctionHighestAddress(self.handle)
@property
def lowest_address(self) -> int:
"""The lowest (smallest) virtual address contained in a function."""
return core.BNGetFunctionLowestAddress(self.handle)
@property
def address_ranges(self) -> List['variable.AddressRange']:
"""All of the address ranges covered by a function"""
count = ctypes.c_ulonglong(0)
range_list = core.BNGetFunctionAddressRanges(self.handle, count)
assert range_list is not None, "core.BNGetFunctionAddressRanges returned None"
result = []
for i in range(0, count.value):
result.append(variable.AddressRange(range_list[i].start, range_list[i].end))
core.BNFreeAddressRanges(range_list)
return result
@property
def symbol(self) -> 'types.Symbol':
"""Function symbol(read-only)"""
sym = core.BNGetFunctionSymbol(self.handle)
assert sym is not None, "core.BNGetFunctionSymbol returned None"
return types.Symbol(None, None, None, handle = sym)
@property
def auto(self) -> bool:
"""
Whether function was automatically discovered (read-only) as a result of some creation of a 'user' function.
'user' functions may or may not have been created by a user through the or API. For instance the entry point
into a function is always created a 'user' function. 'user' functions should be considered the root of auto
analysis.
"""
return core.BNWasFunctionAutomaticallyDiscovered(self.handle)
@property
def can_return(self) -> 'types.BoolWithConfidence':
"""Whether function can return"""
result = core.BNCanFunctionReturn(self.handle)
return types.BoolWithConfidence(result.value, confidence = result.confidence)
@can_return.setter
def can_return(self, value:'types.BoolWithConfidence') -> None:
bc = core.BNBoolWithConfidence()
bc.value = bool(value)
if hasattr(value, 'confidence'):
bc.confidence = value.confidence
else:
bc.confidence = core.max_confidence
core.BNSetUserFunctionCanReturn(self.handle, bc)
@property
def explicitly_defined_type(self) -> bool:
"""Whether function has explicitly defined types (read-only)"""
return core.BNFunctionHasExplicitlyDefinedType(self.handle)
@property
def needs_update(self) -> bool:
"""Whether the function has analysis that needs to be updated (read-only)"""
return core.BNIsFunctionUpdateNeeded(self.handle)
@property
def basic_blocks(self) -> Generator['basicblock.BasicBlock', None, None]:
"""Generator of BasicBlock objects (read-only)"""
count = ctypes.c_ulonglong()
blocks = core.BNGetFunctionBasicBlockList(self.handle, count)
assert blocks is not None, "core.BNGetFunctionBasicBlockList returned None"
try:
for i in range(0, count.value):
block = core.BNNewBasicBlockReference(blocks[i])
assert block is not None
yield basicblock.BasicBlock(block, self._view)
finally:
core.BNFreeBasicBlockList(blocks, count.value)
@property
def comments(self) -> Mapping[int, str]:
"""Dict of comments (read-only)"""
count = ctypes.c_ulonglong()
addrs = core.BNGetCommentedAddresses(self.handle, count)
assert addrs is not None, "core.BNGetCommentedAddresses returned None"
result = {}
for i in range(0, count.value):
result[addrs[i]] = self.get_comment_at(addrs[i])
core.BNFreeAddressList(addrs)
return result
def create_user_tag(self, type:'binaryview.TagType', data:str="") -> 'binaryview.Tag':
"""Create a _user_ Tag object"""
return self.create_tag(type, data, True)
def create_auto_tag(self, type:'binaryview.TagType', data:str="") -> 'binaryview.Tag':
return self.create_tag(type, data, False)
# """Create an _auto_ Tag object"""
def create_tag(self, type:'binaryview.TagType', data:str="", user:bool=True) -> 'binaryview.Tag':
"""
``create_tag`` creates a new Tag object but does not add it anywhere.
Use :py:meth:`create_user_address_tag` or
:py:meth:`create_user_function_tag` to create and add in one step.
:param TagType type: The Tag Type for this Tag
:param str data: Additional data for the Tag
:return: The created Tag
:rtype: Tag
:Example:
>>> tt = bv.tag_types["Crashes"]
>>> tag = current_function.create_tag(tt, "Null pointer dereference", True)
>>> current_function.add_user_address_tag(here, tag)
>>>
"""
return self.view.create_tag(type, data, user)
@property
def address_tags(self) -> Generator[Tuple['architecture.Architecture', int, 'binaryview.Tag'], None, None]:
"""
``address_tags`` gets a list of all address Tags in the function.
Tags are returned as a list of (arch, address, Tag) tuples.
:rtype: Generator((Architecture, int, Tag))
"""
count = ctypes.c_ulonglong()
tags = core.BNGetAddressTagReferences(self.handle, count)
assert tags is not None, "core.BNGetAddressTagReferences returned None"
try:
for i in range(0, count.value):
arch = architecture.CoreArchitecture._from_cache(tags[i].arch)
core_tag = core.BNNewTagReference(tags[i].tag)
assert core_tag is not None, "core.BNNewTagReference returned None"
tag = binaryview.Tag(core_tag)
yield (arch, tags[i].addr, tag)
finally:
core.BNFreeTagReferences(tags, count.value)
def get_address_tags_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Generator['binaryview.Tag', None, None]:
"""
``get_address_tags_at`` gets a generator of all Tags in the function at a given address.
:param int addr: Address to get tags at
:param Architecture arch: Architecture for the block in which the Tag is added (optional)
:return: A Generator of Tags
"""
if arch is None:
if self.arch is None:
raise Exception("Can't get address tags for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
tags = core.BNGetAddressTags(self.handle, arch.handle, addr, count)
assert tags is not None, "core.BNGetAddressTags returned None"
try:
for i in range(0, count.value):
core_tag = core.BNNewTagReference(tags[i])
assert core_tag is not None
yield binaryview.Tag(core_tag)
finally:
core.BNFreeTagList(tags, count.value)
def add_user_address_tag(self, addr:int, tag:'binaryview.Tag', arch:Optional['architecture.Architecture']=None) -> None:
"""
``add_user_address_tag`` adds an already-created Tag object at a given address.
Since this adds a user tag, it will be added to the current undo buffer.
If you want want to create the tag as well, consider using
:meth:`create_user_address_tag <function.Function.create_user_address_tag>`
:param int addr: Address at which to add the tag
:param Tag tag: Tag object to be added
:param Architecture arch: Architecture for the block in which the Tag is added (optional)
:rtype: None
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call add_user_address_tag for function with no architecture specified")
arch = self.arch
core.BNAddUserAddressTag(self.handle, arch.handle, addr, tag.handle)
def create_user_address_tag(self, addr:int, type:'binaryview.TagType', data:str, unique:bool=False,
arch:Optional['architecture.Architecture']=None) -> 'binaryview.Tag':
"""
``create_user_address_tag`` creates and adds a Tag object at a given
address. Since this adds a user tag, it will be added to the current
undo buffer. To create tags associated with an address that is not
inside of a function, use :py:meth:`create_user_data_tag <binaryview.BinaryView.create_user_data_tag>`.
:param int addr: Address at which to add the tag
:param TagType type: Tag Type for the Tag that is created
:param str data: Additional data for the Tag
:param bool unique: If a tag already exists at this location with this data, don't add another
:param Architecture arch: Architecture for the block in which the Tag is added (optional)
:return: The created Tag
:rtype: Tag
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if unique:
tags = self.get_address_tags_at(addr, arch)
for tag in tags:
if tag.type == type and tag.data == data:
return tag
tag = self.create_tag(type, data, True)
core.BNAddUserAddressTag(self.handle, arch.handle, addr, tag.handle)
return tag
def remove_user_address_tag(self, addr:int, tag:'binaryview.TagType', arch:Optional['architecture.Architecture']=None) -> None:
"""
``remove_user_address_tag`` removes a Tag object at a given address.
Since this removes a user tag, it will be added to the current undo buffer.
:param int addr: Address at which to remove the tag
:param Tag tag: Tag object to be added
:param Architecture arch: Architecture for the block in which the Tag is added (optional)
:rtype: None
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
core.BNRemoveUserAddressTag(self.handle, arch.handle, addr, tag.handle)
def add_auto_address_tag(self, addr:int, tag:'binaryview.TagType', arch:Optional['architecture.Architecture']=None) -> None:
"""
``add_auto_address_tag`` adds an already-created Tag object at a given address.
If you want want to create the tag as well, consider using
:meth:`create_auto_address_tag <function.Function.create_auto_address_tag>`
:param int addr: Address at which to add the tag
:param Tag tag: Tag object to be added
:param Architecture arch: Architecture for the block in which the Tag is added (optional)
:rtype: None
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call add_auto_address_tag for function with no architecture specified")
arch = self.arch
core.BNAddAutoAddressTag(self.handle, arch.handle, addr, tag.handle)
def create_auto_address_tag(self, addr:int, type:'binaryview.TagType', data:str, unique:bool=False, arch:Optional['architecture.Architecture']=None) -> 'binaryview.Tag':
"""
``create_auto_address_tag`` creates and adds a Tag object at a given address.
:param int addr: Address at which to add the tag
:param TagType type: Tag Type for the Tag that is created
:param str data: Additional data for the Tag
:param bool unique: If a tag already exists at this location with this data, don't add another
:param Architecture arch: Architecture for the block in which the Tag is added (optional)
:return: The created Tag
:rtype: Tag
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if unique:
tags = self.get_address_tags_at(addr, arch)
for tag in tags:
if tag.type == type and tag.data == data:
return tag
tag = self.create_tag(type, data, False)
core.BNAddAutoAddressTag(self.handle, arch.handle, addr, tag.handle)
return tag
@property
def function_tags(self) -> Generator['binaryview.Tag', None, None]:
"""
``function_tags`` gets a list of all function Tags for the function.
:rtype: Generator(Tag)
"""
count = ctypes.c_ulonglong()
tags = core.BNGetFunctionTags(self.handle, count)
assert tags is not None, "core.BNGetFunctionTags returned None"
try:
for i in range(0, count.value):
core_tag = core.BNNewTagReference(tags[i])
assert core_tag is not None
yield binaryview.Tag(core_tag)
finally:
core.BNFreeTagList(tags, count.value)
def add_user_function_tag(self, tag:'binaryview.Tag') -> None:
"""
``add_user_function_tag`` adds an already-created Tag object as a function tag.
Since this adds a user tag, it will be added to the current undo buffer.
If you want want to create the tag as well, consider using
:meth:`create_user_function_tag <function.Function.create_user_function_tag>`
:param Tag tag: Tag object to be added
:rtype: None
"""
core.BNAddUserFunctionTag(self.handle, tag.handle)
def create_user_function_tag(self, type:'binaryview.TagType', data:str, unique:bool=False) -> 'binaryview.Tag':
"""
``add_user_function_tag`` creates and adds a Tag object as a function tag.
Since this adds a user tag, it will be added to the current undo buffer.
:param TagType type: Tag Type for the Tag that is created
:param str data: Additional data for the Tag
:param bool unique: If a tag already exists with this data, don't add another
:return: The created Tag
:rtype: Tag
"""
if unique:
for tag in self.function_tags:
if tag.type == type and tag.data == data:
return tag
tag = self.create_tag(type, data, True)
core.BNAddUserFunctionTag(self.handle, tag.handle)
return tag
def remove_user_function_tag(self, tag:'binaryview.Tag') -> None:
"""
``remove_user_function_tag`` removes a Tag object as a function tag.
Since this removes a user tag, it will be added to the current undo buffer.
:param Tag tag: Tag object to be added
:rtype: None
"""
core.BNRemoveUserFunctionTag(self.handle, tag.handle)
def add_auto_function_tag(self, tag:'binaryview.Tag') -> None:
"""
``add_auto_function_tag`` adds an already-created Tag object as a function tag.
If you want want to create the tag as well, consider using
:meth:`create_auto_function_tag <function.Function.create_auto_function_tag>`
:param Tag tag: Tag object to be added
:rtype: None
"""
core.BNAddAutoFunctionTag(self.handle, tag.handle)
def create_auto_function_tag(self, type:'binaryview.TagType', data:str, unique:bool=False) -> 'binaryview.Tag':
"""
``create_auto_function_tag`` creates and adds a Tag object as a function tag.
:param TagType type: Tag Type for the Tag that is created
:param str data: Additional data for the Tag
:param bool unique: If a tag already exists with this data, don't add another
:return: The created Tag
:rtype: Tag
"""
if unique:
for tag in self.function_tags:
if tag.type == type and tag.data == data:
return tag
tag = self.create_tag(type, data, False)
core.BNAddAutoFunctionTag(self.handle, tag.handle)
return tag
@property
def low_level_il(self) -> 'lowlevelil.LowLevelILFunction':
"""returns LowLevelILFunction used to represent Function low level IL (read-only)"""
return lowlevelil.LowLevelILFunction(self.arch, core.BNGetFunctionLowLevelIL(self.handle), self)
@property
def llil(self) -> 'lowlevelil.LowLevelILFunction':
"""returns LowLevelILFunction used to represent Function low level IL (read-only)"""
return lowlevelil.LowLevelILFunction(self.arch, core.BNGetFunctionLowLevelIL(self.handle), self)
@property
def llil_if_available(self) -> Optional['lowlevelil.LowLevelILFunction']:
"""returns LowLevelILFunction used to represent Function low level IL, or None if not loaded (read-only)"""
result = core.BNGetFunctionLowLevelILIfAvailable(self.handle)
if not result:
return None
return lowlevelil.LowLevelILFunction(self.arch, result, self)
@property
def lifted_il(self) -> 'lowlevelil.LowLevelILFunction':
"""returns LowLevelILFunction used to represent lifted IL (read-only)"""
return lowlevelil.LowLevelILFunction(self.arch, core.BNGetFunctionLiftedIL(self.handle), self)
@property
def lifted_il_if_available(self) -> Optional['lowlevelil.LowLevelILFunction']:
"""returns LowLevelILFunction used to represent lifted IL, or None if not loaded (read-only)"""
result = core.BNGetFunctionLiftedILIfAvailable(self.handle)
if not result:
return None
return lowlevelil.LowLevelILFunction(self.arch, result, self)
@property
def medium_level_il(self) -> 'mediumlevelil.MediumLevelILFunction':
"""Function medium level IL (read-only)"""
return mediumlevelil.MediumLevelILFunction(self.arch, core.BNGetFunctionMediumLevelIL(self.handle), self)
@property
def mlil(self) -> 'mediumlevelil.MediumLevelILFunction':
"""Function medium level IL (read-only)"""
return mediumlevelil.MediumLevelILFunction(self.arch, core.BNGetFunctionMediumLevelIL(self.handle), self)
@property
def mlil_if_available(self) -> Optional['mediumlevelil.MediumLevelILFunction']:
"""Function medium level IL, or None if not loaded (read-only)"""
result = core.BNGetFunctionMediumLevelILIfAvailable(self.handle)
if not result:
return None
return mediumlevelil.MediumLevelILFunction(self.arch, result, self)
@property
def high_level_il(self) -> 'highlevelil.HighLevelILFunction':
"""Function high level IL (read-only)"""
return highlevelil.HighLevelILFunction(self.arch, core.BNGetFunctionHighLevelIL(self.handle), self)
@property
def hlil(self) -> 'highlevelil.HighLevelILFunction':
"""Function high level IL (read-only)"""
return highlevelil.HighLevelILFunction(self.arch, core.BNGetFunctionHighLevelIL(self.handle), self)
@property
def hlil_if_available(self) -> Optional['highlevelil.HighLevelILFunction']:
"""Function high level IL, or None if not loaded (read-only)"""
result = core.BNGetFunctionHighLevelILIfAvailable(self.handle)
if not result:
return None
return highlevelil.HighLevelILFunction(self.arch, result, self)
@property
def function_type(self) -> 'types.Type':
"""
Function type object, can be set with either a string representing the function prototype
(`str(function)` shows examples) or a :py:class:`Type` object
"""
return types.Type(core.BNGetFunctionType(self.handle), platform = self.platform)
@function_type.setter
def function_type(self, value:'types.Type') -> None:
if isinstance(value, str):
(value, new_name) = self.view.parse_type_string(value)
self.name = str(new_name)
self.set_user_type(value)
@property
def stack_layout(self) -> Generator['variable.Variable', None, None]:
"""List of function stack variables (read-only)"""
count = ctypes.c_ulonglong()
v = core.BNGetStackLayout(self.handle, count)
assert v is not None, "core.BNGetStackLayout returned None"
try:
for i in range(0, count.value):
yield variable.Variable.from_BNVariable(self, v[i].var)
finally:
core.BNFreeVariableNameAndTypeList(v, count.value)
@property
def core_var_stack_layout(self) -> Generator['variable.CoreVariable', None, None]:
"""List of function stack variables (read-only)"""
count = ctypes.c_ulonglong()
v = core.BNGetStackLayout(self.handle, count)
assert v is not None, "core.BNGetStackLayout returned None"
try:
for i in range(0, count.value):
yield variable.CoreVariable.from_BNVariable(v[i].var)
finally:
core.BNFreeVariableNameAndTypeList(v, count.value)
@property
def vars(self) -> Generator['variable.Variable', None, None]:
"""Generator of function variables (read-only)"""
count = ctypes.c_ulonglong()
v = core.BNGetFunctionVariables(self.handle, count)
assert v is not None, "core.BNGetFunctionVariables returned None"
try:
for i in range(0, count.value):
yield variable.Variable.from_BNVariable(self, v[i].var)
finally:
core.BNFreeVariableNameAndTypeList(v, count.value)
@property
def core_vars(self) -> Generator['variable.CoreVariable', None, None]:
"""Generator of CoreVariable objects"""
count = ctypes.c_ulonglong()
v = core.BNGetFunctionVariables(self.handle, count)
assert v is not None, "core.BNGetFunctionVariables returned None"
try:
for i in range(0, count.value):
yield variable.CoreVariable.from_BNVariable(v[i].var)
finally:
core.BNFreeVariableNameAndTypeList(v, count.value)
@property
def indirect_branches(self) -> List['variable.IndirectBranchInfo']:
"""List of indirect branches (read-only)"""
count = ctypes.c_ulonglong()
branches = core.BNGetIndirectBranches(self.handle, count)
assert branches is not None, "core.BNGetIndirectBranches returned None"
result = []
for i in range(0, count.value):
result.append(variable.IndirectBranchInfo(architecture.CoreArchitecture._from_cache(branches[i].sourceArch), branches[i].sourceAddr, architecture.CoreArchitecture._from_cache(branches[i].destArch), branches[i].destAddr, branches[i].autoDefined))
core.BNFreeIndirectBranchList(branches)
return result
@property
def unresolved_indirect_branches(self) -> List[int]:
"""List of unresolved indirect branches (read-only)"""
count = ctypes.c_ulonglong()
addrs = core.BNGetUnresolvedIndirectBranches(self.handle, count)
assert addrs is not None, "core.BNGetUnresolvedIndirectBranches returned None"
result = []
for i in range(0, count.value):
result.append(addrs[i])
core.BNFreeAddressList(addrs)
return result
@property
def has_unresolved_indirect_branches(self) -> bool:
"""Has unresolved indirect branches (read-only)"""
return core.BNHasUnresolvedIndirectBranches(self.handle)
@property
def session_data(self) -> Any:
"""Dictionary object where plugins can store arbitrary data associated with the function"""
handle = ctypes.cast(self.handle, ctypes.c_void_p)
if handle.value not in Function._associated_data:
obj = _FunctionAssociatedDataStore()
Function._associated_data[handle.value] = obj
return obj
else:
return Function._associated_data[handle.value]
@property
def analysis_performance_info(self) -> Mapping[str, int]:
count = ctypes.c_ulonglong()
info = core.BNGetFunctionAnalysisPerformanceInfo(self.handle, count)
assert info is not None, "core.BNGetFunctionAnalysisPerformanceInfo returned None"
result = {}
for i in range(0, count.value):
result[info[i].name] = info[i].seconds
core.BNFreeAnalysisPerformanceInfo(info, count.value)
return result
@property
def type_tokens(self) -> List['InstructionTextToken']:
"""Text tokens for this function's prototype"""
return self.get_type_tokens()[0].tokens
@property
def return_type(self) -> Optional['types.Type']:
"""Return type of the function"""
result = core.BNGetFunctionReturnType(self.handle)
if not result.type:
return None
return types.Type(result.type, platform = self.platform, confidence = result.confidence)
@return_type.setter
def return_type(self, value:'types.Type') -> None:
type_conf = core.BNTypeWithConfidence()
if value is None:
type_conf.type = None
type_conf.confidence = 0
else:
type_conf.type = value.handle
type_conf.confidence = value.confidence
core.BNSetUserFunctionReturnType(self.handle, type_conf)
@property
def return_regs(self) -> 'types.RegisterSet':
"""Registers that are used for the return value"""
result = core.BNGetFunctionReturnRegisters(self.handle)
assert result is not None, "core.BNGetFunctionReturnRegisters returned None"
if self.arch is None:
raise Exception("Can not get property return_regs with unspecified Architecture")
reg_set = []
for i in range(0, result.count):
reg_set.append(self.arch.get_reg_name(result.regs[i]))
regs = types.RegisterSet(reg_set, confidence = result.confidence)
core.BNFreeRegisterSet(result)
return regs
@return_regs.setter
def return_regs(self, value:Union['types.RegisterSet', List['architecture.RegisterType']]) -> None: # type: ignore
regs = core.BNRegisterSetWithConfidence()
regs.regs = (ctypes.c_uint * len(value))()
regs.count = len(value)
if self.arch is None:
raise Exception("Can not get property return_regs with unspecified Architecture")
for i in range(0, len(value)):
regs.regs[i] = self.arch.get_reg_index(value[i])
if isinstance(value, types.RegisterSet):
regs.confidence = value.confidence
else:
regs.confidence = core.max_confidence
core.BNSetUserFunctionReturnRegisters(self.handle, regs)
@property
def calling_convention(self) -> Optional['callingconvention.CallingConvention']:
"""Calling convention used by the function"""
result = core.BNGetFunctionCallingConvention(self.handle)
if not result.convention:
return None
return callingconvention.CallingConvention(None, handle = result.convention, confidence = result.confidence)
@calling_convention.setter
def calling_convention(self, value:'callingconvention.CallingConvention') -> None:
conv_conf = core.BNCallingConventionWithConfidence()
if value is None:
conv_conf.convention = None
conv_conf.confidence = 0
else:
conv_conf.convention = value.handle
conv_conf.confidence = value.confidence
core.BNSetUserFunctionCallingConvention(self.handle, conv_conf)
@property
def parameter_vars(self) -> 'variable.ParameterVariables':
"""List of variables for the incoming function parameters"""
result = core.BNGetFunctionParameterVariables(self.handle)
var_list = []
for i in range(0, result.count):
var_list.append(variable.Variable.from_BNVariable(self, result.vars[i]))
confidence = result.confidence
core.BNFreeParameterVariables(result)
return variable.ParameterVariables(var_list, confidence, self)
@parameter_vars.setter
def parameter_vars(self, value:Optional[Union['variable.ParameterVariables', List['variable.Variable']]]) -> None: # type: ignore
if value is None:
var_list = []
else:
var_list = list(value)
var_conf = core.BNParameterVariablesWithConfidence()
var_conf.vars = (core.BNVariable * len(var_list))()
var_conf.count = len(var_list)
for i in range(0, len(var_list)):
var_conf.vars[i].type = var_list[i].source_type
var_conf.vars[i].index = var_list[i].index
var_conf.vars[i].storage = var_list[i].storage
if value is None:
var_conf.confidence = 0
elif isinstance(value, types.RegisterSet):
var_conf.confidence = value.confidence
else:
var_conf.confidence = core.max_confidence
core.BNSetUserFunctionParameterVariables(self.handle, var_conf)
@property
def has_variable_arguments(self) -> 'types.BoolWithConfidence':
"""Whether the function takes a variable number of arguments"""
result = core.BNFunctionHasVariableArguments(self.handle)
return types.BoolWithConfidence(result.value, confidence = result.confidence)
@has_variable_arguments.setter
def has_variable_arguments(self, value:Union[bool, 'types.BoolWithConfidence']) -> None: # type: ignore
bc = core.BNBoolWithConfidence()
bc.value = bool(value)
if isinstance(value, types.BoolWithConfidence):
bc.confidence = value.confidence
else:
bc.confidence = core.max_confidence
core.BNSetUserFunctionHasVariableArguments(self.handle, bc)
@property
def stack_adjustment(self) -> 'types.SizeWithConfidence':
"""Number of bytes removed from the stack after return"""
result = core.BNGetFunctionStackAdjustment(self.handle)
return types.SizeWithConfidence(result.value, confidence = result.confidence)
@stack_adjustment.setter
def stack_adjustment(self, value:'types.SizeWithConfidence') -> None:
oc = core.BNOffsetWithConfidence()
oc.value = int(value)
if hasattr(value, 'confidence'):
oc.confidence = value.confidence
else:
oc.confidence = core.max_confidence
core.BNSetUserFunctionStackAdjustment(self.handle, oc)
@property
def reg_stack_adjustments(self) -> Mapping['architecture.RegisterStackName', 'types.RegisterStackAdjustmentWithConfidence']:
"""Number of entries removed from each register stack after return"""
count = ctypes.c_ulonglong()
adjust = core.BNGetFunctionRegisterStackAdjustments(self.handle, count)
assert adjust is not None, "core.BNGetFunctionRegisterStackAdjustments returned None"
if self.arch is None:
raise Exception("Can not get property return_regs with unspecified Architecture")
result = {}
for i in range(0, count.value):
name = self.arch.get_reg_stack_name(adjust[i].regStack)
value = types.RegisterStackAdjustmentWithConfidence(adjust[i].adjustment,
confidence = adjust[i].confidence)
result[name] = value
core.BNFreeRegisterStackAdjustments(adjust)
return result
@reg_stack_adjustments.setter
def reg_stack_adjustments(self,
value:Mapping['architecture.RegisterStackName', Union[int, 'types.RegisterStackAdjustmentWithConfidence']]) -> None: # type: ignore
adjust = (core.BNRegisterStackAdjustment * len(value))()
if self.arch is None:
raise Exception("Can not get property return_regs with unspecified Architecture")
i = 0
for reg_stack in value.keys():
adjust[i].regStack = self.arch.get_reg_stack_index(reg_stack)
entry = value[reg_stack]
if isinstance(entry, types.RegisterStackAdjustmentWithConfidence):
adjust[i].adjustment = entry.value
adjust[i].confidence = entry.confidence
else:
adjust[i].adjustment = int(entry)
adjust[i].confidence = core.max_confidence
i += 1
core.BNSetUserFunctionRegisterStackAdjustments(self.handle, adjust, len(value))
@property
def clobbered_regs(self) -> 'types.RegisterSet':
"""Registers that are modified by this function"""
result = core.BNGetFunctionClobberedRegisters(self.handle)
if self.arch is None:
raise Exception("Can not get property return_regs with unspecified Architecture")
reg_set = []
for i in range(0, result.count):
reg_set.append(self.arch.get_reg_name(result.regs[i]))
regs = types.RegisterSet(reg_set, confidence = result.confidence)
core.BNFreeRegisterSet(result)
return regs
@clobbered_regs.setter
def clobbered_regs(self, value:Union['types.RegisterSet', List['architecture.RegisterType']]) -> None: # type: ignore
regs = core.BNRegisterSetWithConfidence()
if self.arch is None:
raise Exception("Can not get property return_regs with unspecified Architecture")
regs.regs = (ctypes.c_uint * len(value))()
regs.count = len(value)
for i in range(0, len(value)):
regs.regs[i] = self.arch.get_reg_index(value[i])
if isinstance(value, types.RegisterSet):
regs.confidence = value.confidence
else:
regs.confidence = core.max_confidence
core.BNSetUserFunctionClobberedRegisters(self.handle, regs)
@property
def global_pointer_value(self) -> variable.RegisterValue:
"""Discovered value of the global pointer register, if the function uses one (read-only)"""
result = core.BNGetFunctionGlobalPointerValue(self.handle)
return variable.RegisterValue.from_BNRegisterValue(result, self.arch)
@property
def comment(self) -> str:
"""Gets the comment for the current function"""
return core.BNGetFunctionComment(self.handle)
@comment.setter
def comment(self, comment:str) -> None:
"""Sets a comment for the current function"""
return core.BNSetFunctionComment(self.handle, comment)
@property
def llil_basic_blocks(self) -> Generator['lowlevelil.LowLevelILBasicBlock', None, None]:
"""A generator of all LowLevelILBasicBlock objects in the current function"""
for block in self.llil:
yield block
@property
def mlil_basic_blocks(self) -> Generator['mediumlevelil.MediumLevelILBasicBlock', None, None]:
"""A generator of all MediumLevelILBasicBlock objects in the current function"""
for block in self.mlil:
yield block
@property
def instructions(self) -> Generator[Tuple[List['InstructionTextToken'], int], None, None]:
"""A generator of instruction tokens and their start addresses for the current function"""
for block in self.basic_blocks:
start = block.start
for i in block:
yield (i[0], start)
start += i[1]
@property
def llil_instructions(self) -> Generator['lowlevelil.LowLevelILInstruction', None, None]:
"""Deprecated method provided for compatibility. Use llil.instructions instead. Was: A generator of llil instructions of the current function"""
return self.llil.instructions
@property
def mlil_instructions(self) -> Generator['mediumlevelil.MediumLevelILInstruction', None, None]:
"""Deprecated method provided for compatibility. Use mlil.instructions instead. Was: A generator of mlil instructions of the current function"""
return self.mlil.instructions
@property
def too_large(self) -> bool:
"""Whether the function is too large to automatically perform analysis (read-only)"""
return core.BNIsFunctionTooLarge(self.handle)
@property
def analysis_skipped(self) -> bool:
"""Whether automatic analysis was skipped for this function, set to true to disable analysis."""
return core.BNIsFunctionAnalysisSkipped(self.handle)
@analysis_skipped.setter
def analysis_skipped(self, skip:bool) -> None:
if skip:
core.BNSetFunctionAnalysisSkipOverride(self.handle, FunctionAnalysisSkipOverride.AlwaysSkipFunctionAnalysis)
else:
core.BNSetFunctionAnalysisSkipOverride(self.handle, FunctionAnalysisSkipOverride.NeverSkipFunctionAnalysis)
@property
def analysis_skip_reason(self) -> AnalysisSkipReason:
"""Function analysis skip reason"""
return AnalysisSkipReason(core.BNGetAnalysisSkipReason(self.handle))
@property
def analysis_skip_override(self) -> FunctionAnalysisSkipOverride:
"""Override for skipping of automatic analysis"""
return FunctionAnalysisSkipOverride(core.BNGetFunctionAnalysisSkipOverride(self.handle))
@analysis_skip_override.setter
def analysis_skip_override(self, override:FunctionAnalysisSkipOverride) -> None:
core.BNSetFunctionAnalysisSkipOverride(self.handle, override)
@property
def unresolved_stack_adjustment_graph(self) -> Optional['flowgraph.CoreFlowGraph']:
"""Flow graph of unresolved stack adjustments (read-only)"""
graph = core.BNGetUnresolvedStackAdjustmentGraph(self.handle)
if not graph:
return None
return flowgraph.CoreFlowGraph(graph)
def mark_recent_use(self) -> None:
core.BNMarkFunctionAsRecentlyUsed(self.handle)
def get_comment_at(self, addr:int) -> str:
return core.BNGetCommentForAddress(self.handle, addr)
def set_comment(self, addr:int, comment:str) -> None:
"""Deprecated method provided for compatibility. Use set_comment_at instead."""
core.BNSetCommentForAddress(self.handle, addr, comment)
def set_comment_at(self, addr:int, comment:str) -> None:
"""
``set_comment_at`` sets a comment for the current function at the address specified
:param int addr: virtual address within the current function to apply the comment to
:param str comment: string comment to apply
:rtype: None
:Example:
>>> current_function.set_comment_at(here, "hi")
"""
core.BNSetCommentForAddress(self.handle, addr, comment)
def add_user_code_ref(self, from_addr:int, to_addr:int, arch:Optional['architecture.Architecture']=None) -> None:
"""
``add_user_code_ref`` places a user-defined cross-reference from the instruction at
the given address and architecture to the specified target address. If the specified
source instruction is not contained within this function, no action is performed.
To remove the reference, use :func:`remove_user_code_ref`.
:param int from_addr: virtual address of the source instruction
:param int to_addr: virtual address of the xref's destination.
:param Architecture arch: (optional) architecture of the source instruction
:rtype: None
:Example:
>>> current_function.add_user_code_ref(here, 0x400000)
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
core.BNAddUserCodeReference(self.handle, arch.handle, from_addr, to_addr)
def remove_user_code_ref(self, from_addr:int, to_addr:int, from_arch:Optional['architecture.Architecture']=None) -> None:
"""
``remove_user_code_ref`` removes a user-defined cross-reference.
If the given address is not contained within this function, or if there is no
such user-defined cross-reference, no action is performed.
:param int from_addr: virtual address of the source instruction
:param int to_addr: virtual address of the xref's destination.
:param Architecture from_arch: (optional) architecture of the source instruction
:rtype: None
:Example:
>>> current_function.remove_user_code_ref(here, 0x400000)
"""
if from_arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
from_arch = self.arch
core.BNRemoveUserCodeReference(self.handle, from_arch.handle, from_addr, to_addr)
def add_user_type_ref(self, from_addr:int, name:'types.QualifiedNameType',
from_arch:Optional['architecture.Architecture']=None) -> None:
"""
``add_user_type_ref`` places a user-defined type cross-reference from the instruction at
the given address and architecture to the specified type. If the specified
source instruction is not contained within this function, no action is performed.
To remove the reference, use :func:`remove_user_type_ref`.
:param int from_addr: virtual address of the source instruction
:param QualifiedName name: name of the referenced type
:param Architecture from_arch: (optional) architecture of the source instruction
:rtype: None
:Example:
>>> current_function.add_user_code_ref(here, 'A')
"""
if from_arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
from_arch = self.arch
_name = types.QualifiedName(name)._get_core_struct()
core.BNAddUserTypeReference(self.handle, from_arch.handle, from_addr, _name)
def remove_user_type_ref(self, from_addr:int, name:'types.QualifiedNameType', from_arch:Optional['architecture.Architecture']=None) -> None:
"""
``remove_user_type_ref`` removes a user-defined type cross-reference.
If the given address is not contained within this function, or if there is no
such user-defined cross-reference, no action is performed.
:param int from_addr: virtual address of the source instruction
:param QualifiedName name: name of the referenced type
:param Architecture from_arch: (optional) architecture of the source instruction
:rtype: None
:Example:
>>> current_function.remove_user_type_ref(here, 'A')
"""
if from_arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
from_arch = self.arch
_name = types.QualifiedName(name)._get_core_struct()
core.BNRemoveUserTypeReference(self.handle, from_arch.handle, from_addr, _name)
def add_user_type_field_ref(self, from_addr:int, name:'types.QualifiedNameType', offset:int,
from_arch:Optional['architecture.Architecture']=None, size:int=0) -> None:
"""
``add_user_type_field_ref`` places a user-defined type field cross-reference from the
instruction at the given address and architecture to the specified type. If the specified
source instruction is not contained within this function, no action is performed.
To remove the reference, use :func:`remove_user_type_field_ref`.
:param int from_addr: virtual address of the source instruction
:param QualifiedName name: name of the referenced type
:param int offset: offset of the field, relative to the type
:param Architecture from_arch: (optional) architecture of the source instruction
:param int size: (optional) the size of the access
:rtype: None
:Example:
>>> current_function.add_user_type_field_ref(here, 'A', 0x8)
"""
if from_arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
from_arch = self.arch
_name = types.QualifiedName(name)._get_core_struct()
core.BNAddUserTypeFieldReference(self.handle, from_arch.handle, from_addr, _name,\
offset, size)
def remove_user_type_field_ref(self, from_addr:int, name:'types.QualifiedNameType', offset:int,
from_arch:Optional['architecture.Architecture']=None, size:int=0) -> None:
"""
``remove_user_type_field_ref`` removes a user-defined type field cross-reference.
If the given address is not contained within this function, or if there is no
such user-defined cross-reference, no action is performed.
:param int from_addr: virtual address of the source instruction
:param QualifiedName name: name of the referenced type
:param int offset: offset of the field, relative to the type
:param Architecture from_arch: (optional) architecture of the source instruction
:param int size: (optional) the size of the access
:rtype: None
:Example:
>>> current_function.remove_user_type_field_ref(here, 'A', 0x8)
"""
if from_arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
from_arch = self.arch
_name = types.QualifiedName(name)._get_core_struct()
core.BNRemoveUserTypeFieldReference(self.handle, from_arch.handle, from_addr, _name,\
offset, size)
def get_low_level_il_at(self, addr:int, arch:Optional['architecture.Architecture']=None):
"""
``get_low_level_il_at`` gets the LowLevelILInstruction corresponding to the given virtual address
:param int addr: virtual address of the function to be queried
:param Architecture arch: (optional) Architecture for the given function
:rtype: LowLevelILInstruction
:Example:
>>> func = next(bv.functions)
>>> func.get_low_level_il_at(func.start)
<il: push(rbp)>
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
idx = core.BNGetLowLevelILForInstruction(self.handle, arch.handle, addr)
if idx == len(self.llil):
return None
return self.llil[idx]
def get_llil_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Optional['lowlevelil.LowLevelILInstruction']:
"""
``get_llil_at`` gets the LowLevelILInstruction corresponding to the given virtual address
:param int addr: virtual address of the function to be queried
:param Architecture arch: (optional) Architecture for the given function
:rtype: LowLevelILInstruction
:Example:
>>> func = next(bv.functions)
>>> func.get_llil_at(func.start)
<il: push(rbp)>
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
idx = core.BNGetLowLevelILForInstruction(self.handle, arch.handle, addr)
if idx == len(self.llil):
return None
return self.llil[idx]
def get_llils_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> List['lowlevelil.LowLevelILInstruction']:
"""
``get_llils_at`` gets the LowLevelILInstruction(s) corresponding to the given virtual address
:param int addr: virtual address of the function to be queried
:param Architecture arch: (optional) Architecture for the given function
:rtype: list(LowLevelILInstruction)
:Example:
>>> func = next(bv.functions)
>>> func.get_llils_at(func.start)
[<il: push(rbp)>]
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call get_llils_at for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
instrs = core.BNGetLowLevelILInstructionsForAddress(self.handle, arch.handle, addr, count)
assert instrs is not None, "core.BNGetLowLevelILInstructionsForAddress returned None"
result = []
for i in range(0, count.value):
result.append(self.llil[instrs[i]])
core.BNFreeILInstructionList(instrs)
return result
def get_low_level_il_exits_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> List[int]:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
exits = core.BNGetLowLevelILExitsForInstruction(self.handle, arch.handle, addr, count)
assert exits is not None, "core.BNGetLowLevelILExitsForInstruction returned None"
result = []
for i in range(0, count.value):
result.append(exits[i])
core.BNFreeILInstructionList(exits)
return result
def get_reg_value_at(self, addr:int, reg:'architecture.RegisterType',
arch:Optional['architecture.Architecture']=None) -> 'variable.RegisterValue':
"""
``get_reg_value_at`` gets the value the provided string register address corresponding to the given virtual address
:param int addr: virtual address of the instruction to query
:param str reg: string value of native register to query
:param Architecture arch: (optional) Architecture for the given function
:rtype: variable.RegisterValue
:Example:
>>> func.get_reg_value_at(0x400dbe, 'rdi')
<const 0x2>
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
reg = arch.get_reg_index(reg)
value = core.BNGetRegisterValueAtInstruction(self.handle, arch.handle, addr, reg)
result = variable.RegisterValue.from_BNRegisterValue(value, arch)
return result
@property
def auto_address_tags(self):
"""
``auto_address_tags`` gets a list of all auto-defined address Tags in the function.
Tags are returned as a list of (arch, address, Tag) tuples.
:rtype: list((Architecture, int, Tag))
"""
count = ctypes.c_ulonglong()
tags = core.BNGetAutoAddressTagReferences(self.handle, count)
assert tags is not None, "core.BNGetAutoAddressTagReferences returned None"
result = []
for i in range(0, count.value):
arch = architecture.CoreArchitecture._from_cache(tags[i].arch)
tag_ref = core.BNNewTagReference(tags[i].tag)
assert tag_ref is not None, "core.BNNewTagReference returned None"
tag = binaryview.Tag(tag_ref)
result.append((arch, tags[i].addr, tag))
core.BNFreeTagReferences(tags, count.value)
return result
@property
def user_address_tags(self):
"""
``user_address_tags`` gets a list of all user address Tags in the function.
Tags are returned as a list of (arch, address, Tag) tuples.
:rtype: list((Architecture, int, Tag))
"""
count = ctypes.c_ulonglong()
tags = core.BNGetUserAddressTagReferences(self.handle, count)
assert tags is not None, "core.BNGetUserAddressTagReferences returned"
result = []
for i in range(0, count.value):
arch = architecture.CoreArchitecture._from_cache(tags[i].arch)
tag_ref = core.BNNewTagReference(tags[i].tag)
assert tag_ref is not None, "core.BNNewTagReference returned None"
tag = binaryview.Tag(tag_ref)
result.append((arch, tags[i].addr, tag))
core.BNFreeTagReferences(tags, count.value)
return result
def get_reg_value_after(self, addr:int, reg:'architecture.RegisterType',
arch:Optional['architecture.Architecture']=None) -> 'variable.RegisterValue':
"""
``get_reg_value_after`` gets the value instruction address corresponding to the given virtual address
:param int addr: virtual address of the instruction to query
:param str reg: string value of native register to query
:param Architecture arch: (optional) Architecture for the given function
:rtype: variable.RegisterValue
:Example:
>>> func.get_reg_value_after(0x400dbe, 'rdi')
<undetermined>
"""
if arch is None:
if self.arch is None:
raise Exception("Can't call get_reg_value_after for function with no architecture specified")
arch = self.arch
reg = arch.get_reg_index(reg)
value = core.BNGetRegisterValueAfterInstruction(self.handle, arch.handle, addr, reg)
result = variable.RegisterValue.from_BNRegisterValue(value, arch)
return result
def get_auto_address_tags_at(self, addr, arch=None):
"""
``get_auto_address_tags_at`` gets a list of all auto-defined Tags in the function at a given address.
:param int addr: Address to get tags at
:param Architecture arch: Architecture for the block in which the Tag is located (optional)
:return: A list of Tags
:rtype: list(Tag)
"""
if arch is None:
if self.arch is None:
raise Exception("Can't call get_auto_address_tags_at for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
tags = core.BNGetAutoAddressTags(self.handle, arch.handle, addr, count)
assert tags is not None, "core.BNGetAutoAddressTags returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(tags[i])
assert tag_ref is not None, "core.BNNewTagReference returned None"
result.append(binaryview.Tag(tag_ref))
core.BNFreeTagList(tags, count.value)
return result
def get_user_address_tags_at(self, addr, arch=None):
"""
``get_user_address_tags_at`` gets a list of all user Tags in the function at a given address.
:param int addr: Address to get tags at
:param Architecture arch: Architecture for the block in which the Tag is located (optional)
:return: A list of Tags
:rtype: list(Tag)
"""
if arch is None:
if self.arch is None:
raise Exception("Can't call get_user_address_tags_at for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
tags = core.BNGetUserAddressTags(self.handle, arch.handle, addr, count)
assert tags is not None, "core.BNGetUserAddressTags returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(tags[i])
assert tag_ref is not None, "core.BNNewTagReference returned None"
result.append(binaryview.Tag(tag_ref))
core.BNFreeTagList(tags, count.value)
return result
def get_address_tags_of_type(self, addr, tag_type, arch=None):
"""
``get_address_tags_of_type`` gets a list of all Tags in the function at a given address with a given type.
:param int addr: Address to get tags at
:param TagType tag_type: TagType object to match in searching
:param Architecture arch: Architecture for the block in which the Tags are located (optional)
:return: A list of data Tags
:rtype: list(Tag)
"""
if arch is None:
if self.arch is None:
raise Exception("Can't call get_address_tags_of_type for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
tags = core.BNGetAddressTagsOfType(self.handle, arch.handle, addr, tag_type.handle, count)
assert tags is not None, "core.BNGetAddressTagsOfType returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(tags[i])
assert tag_ref is not None, "core.BNNewTagReference returned None"
result.append(binaryview.Tag(tag_ref))
core.BNFreeTagList(tags, count.value)
return result
def get_auto_address_tags_of_type(self, addr, tag_type, arch=None):
"""
``get_auto_address_tags_of_type`` gets a list of all auto-defined Tags in the function at a given address with a given type.
:param int addr: Address to get tags at
:param TagType tag_type: TagType object to match in searching
:param Architecture arch: Architecture for the block in which the Tags are located (optional)
:return: A list of data Tags
:rtype: list(Tag)
"""
if arch is None:
if self.arch is None:
raise Exception("Can't call get_auto_address_tags_of_type for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
tags = core.BNGetAutoAddressTagsOfType(self.handle, arch.handle, addr, tag_type.handle, count)
assert tags is not None, "core.BNGetAutoAddressTagsOfType returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(tags[i])
assert tag_ref is not None, "core.BNNewTagReference returned None"
result.append(binaryview.Tag(tag_ref))
core.BNFreeTagList(tags, count.value)
return result
def get_user_address_tags_of_type(self, addr, tag_type, arch=None):
"""
``get_user_address_tags_of_type`` gets a list of all user Tags in the function at a given address with a given type.
:param int addr: Address to get tags at
:param TagType tag_type: TagType object to match in searching
:param Architecture arch: Architecture for the block in which the Tags are located (optional)
:return: A list of data Tags
:rtype: list(Tag)
"""
if arch is None:
if self.arch is None:
raise Exception("Can't call get_user_address_tags_of_type for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
tags = core.BNGetUserAddressTagsOfType(self.handle, arch.handle, addr, tag_type.handle, count)
assert tags is not None, "core.BNGetUserAddressTagsOfType returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(tags[i])
assert tag_ref is not None, "core.BNNewTagReference returned None"
result.append(binaryview.Tag(tag_ref))
core.BNFreeTagList(tags, count.value)
return result
def get_address_tags_in_range(self, address_range, arch=None):
"""
``get_address_tags_in_range`` gets a list of all Tags in the function at a given address.
Range is inclusive at the start, exclusive at the end.
:param AddressRange address_range: Address range from which to get tags
:param Architecture arch: Architecture for the block in which the Tag is located (optional)
:return: A list of (arch, address, Tag) tuples
:rtype: list((Architecture, int, Tag))
"""
if arch is None:
if self.arch is None:
raise Exception("Can't call get_address_tags_in_range for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
refs = core.BNGetAddressTagsInRange(self.handle, arch.handle, address_range.start, address_range.end, count)
assert refs is not None, "core.BNGetAddressTagsInRange returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(refs[i].tag)
assert tag_ref is not None, "core.BNNewTagReference returned None"
tag = binaryview.Tag(tag_ref)
result.append((arch, refs[i].addr, tag))
core.BNFreeTagReferences(refs, count.value)
return result
def get_auto_address_tags_in_range(self, address_range, arch=None):
"""
``get_auto_address_tags_in_range`` gets a list of all auto-defined Tags in the function at a given address.
Range is inclusive at the start, exclusive at the end.
:param AddressRange address_range: Address range from which to get tags
:param Architecture arch: Architecture for the block in which the Tag is located (optional)
:return: A list of (arch, address, Tag) tuples
:rtype: list((Architecture, int, Tag))
"""
if arch is None:
if self.arch is None:
raise Exception("Can't call get_auto_address_tags_in_range for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
refs = core.BNGetAutoAddressTagsInRange(self.handle, arch.handle, address_range.start, address_range.end, count)
assert refs is not None, "core.BNGetAutoAddressTagsInRange returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(refs[i].tag)
assert tag_ref is not None, "core.BNNewTagReference returned None"
tag = binaryview.Tag(tag_ref)
result.append((arch, refs[i].addr, tag))
core.BNFreeTagReferences(refs, count.value)
return result
def get_user_address_tags_in_range(self, address_range, arch=None):
"""
``get_user_address_tags_in_range`` gets a list of all user Tags in the function at a given address.
Range is inclusive at the start, exclusive at the end.
:param AddressRange address_range: Address range from which to get tags
:param Architecture arch: Architecture for the block in which the Tag is located (optional)
:return: A list of (arch, address, Tag) tuples
:rtype: list((Architecture, int, Tag))
"""
if arch is None:
if self.arch is None:
raise Exception("Can't call get_user_address_tags_in_range for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
refs = core.BNGetUserAddressTagsInRange(self.handle, arch.handle, address_range.start, address_range.end, count)
assert refs is not None, "core.BNGetUserAddressTagsInRange returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(refs[i].tag)
assert tag_ref is not None, "core.BNNewTagReference returned None"
tag = binaryview.Tag(tag_ref)
result.append((arch, refs[i].addr, tag))
core.BNFreeTagReferences(refs, count.value)
return result
def get_stack_contents_at(self, addr:int, offset:int, size:int,
arch:Optional['architecture.Architecture']=None) -> 'variable.RegisterValue':
"""
``get_stack_contents_at`` returns the RegisterValue for the item on the stack in the current function at the
given virtual address ``addr``, stack offset ``offset`` and size of ``size``. Optionally specifying the architecture.
:param int addr: virtual address of the instruction to query
:param int offset: stack offset base of stack
:param int size: size of memory to query
:param Architecture arch: (optional) Architecture for the given function
:rtype: variable.RegisterValue
.. note:: Stack base is zero on entry into the function unless the architecture places the return address on the \
stack as in (x86/x86_64) where the stack base will start at address_size
:Example:
>>> func.get_stack_contents_at(0x400fad, -16, 4)
<range: 0x8 to 0xffffffff>
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
value = core.BNGetStackContentsAtInstruction(self.handle, arch.handle, addr, offset, size)
result = variable.RegisterValue.from_BNRegisterValue(value, arch)
return result
def get_stack_contents_after(self, addr:int, offset:int, size:int,
arch:Optional['architecture.Architecture']=None) -> 'variable.RegisterValue':
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
value = core.BNGetStackContentsAfterInstruction(self.handle, arch.handle, addr, offset, size)
result = variable.RegisterValue.from_BNRegisterValue(value, arch)
return result
def get_parameter_at(self, addr:int, func_type:Optional['types.Type'], i:int,
arch:Optional['architecture.Architecture']=None) -> 'variable.RegisterValue':
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
_func_type = None
if func_type is not None:
_func_type = func_type.handle
value = core.BNGetParameterValueAtInstruction(self.handle, arch.handle, addr, _func_type, i)
result = variable.RegisterValue.from_BNRegisterValue(value, arch)
return result
def remove_user_address_tags_of_type(self, addr, tag_type, arch=None):
"""
``remove_user_address_tags_of_type`` removes all tags at the given address of the given type.
Since this removes user tags, it will be added to the current undo buffer.
:param int addr: Address at which to remove the tag
:param Tag tag_type: TagType object to match for removing
:param Architecture arch: Architecture for the block in which the Tags is located (optional)
:rtype: None
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
core.BNRemoveUserAddressTagsOfType(self.handle, arch.handle, addr, tag_type.handle)
def get_parameter_at_low_level_il_instruction(self, instr:'lowlevelil.InstructionIndex',
func_type:'types.Type', i:int) -> 'variable.RegisterValue':
_func_type = None
if func_type is not None:
_func_type = func_type.handle
value = core.BNGetParameterValueAtLowLevelILInstruction(self.handle, instr, _func_type, i)
result = variable.RegisterValue.from_BNRegisterValue(value, self.arch)
return result
def get_regs_read_by(self, addr:int, arch:Optional['architecture.Architecture']=None) -> List['architecture.RegisterName']:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
regs = core.BNGetRegistersReadByInstruction(self.handle, arch.handle, addr, count)
assert regs is not None, "core.BNGetRegistersReadByInstruction returned None"
result = []
for i in range(0, count.value):
result.append(arch.get_reg_name(regs[i]))
core.BNFreeRegisterList(regs)
return result
def get_regs_written_by(self, addr:int, arch:Optional['architecture.Architecture']=None) -> List['architecture.RegisterName']:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
regs = core.BNGetRegistersWrittenByInstruction(self.handle, arch.handle, addr, count)
assert regs is not None, "core.BNGetRegistersWrittenByInstruction returned None"
result = []
for i in range(0, count.value):
result.append(arch.get_reg_name(regs[i]))
core.BNFreeRegisterList(regs)
return result
def remove_auto_address_tag(self, addr:int, tag:'binaryview.TagType', arch:Optional['architecture.Architecture']=None) -> None:
"""
``remove_auto_address_tag`` removes a Tag object at a given address.
:param int addr: Address at which to add the tag
:param Tag tag: Tag object to be added
:param Architecture arch: Architecture for the block in which the Tag is added (optional)
:rtype: None
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call remove_auto_address_tag with no architecture specified")
arch = self.arch
core.BNRemoveAutoAddressTag(self.handle, arch.handle, addr, tag.handle)
def remove_auto_address_tags_of_type(self, addr, tag_type, arch=None):
"""
``remove_auto_address_tags_of_type`` removes all tags at the given address of the given type.
:param int addr: Address at which to remove the tags
:param Tag tag_type: TagType object to match for removing
:param Architecture arch: Architecture for the block in which the Tags is located (optional)
:rtype: None
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
core.BNRemoveAutoAddressTagsOfType(self.handle, arch.handle, addr, tag_type.handle)
def get_stack_vars_referenced_by(self, addr:int,
arch:Optional['architecture.Architecture']=None) -> List['variable.StackVariableReference']:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
refs = core.BNGetStackVariablesReferencedByInstruction(self.handle, arch.handle, addr, count)
assert refs is not None, "core.BNGetStackVariablesReferencedByInstruction returned None"
result = []
for i in range(0, count.value):
var_type = types.Type(core.BNNewTypeReference(refs[i].type), platform = self.platform, confidence = refs[i].typeConfidence)
var = variable.Variable.from_identifier(self, refs[i].varIdentifier)
result.append(variable.StackVariableReference(refs[i].sourceOperand, var_type, refs[i].name, var,
refs[i].referencedOffset, refs[i].size))
core.BNFreeStackVariableReferenceList(refs, count.value)
return result
@property
def auto_function_tags(self):
"""
``auto_function_tags`` gets a list of all auto-defined function Tags for the function.
:rtype: list(Tag)
"""
count = ctypes.c_ulonglong()
tags = core.BNGetAutoFunctionTags(self.handle, count)
assert tags is not None, "core.BNGetAutoFunctionTags returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(tags[i])
assert tag_ref is not None, "core.BNNewTagReference returned None"
result.append(binaryview.Tag(tag_ref))
core.BNFreeTagList(tags, count.value)
return result
@property
def user_function_tags(self):
"""
``user_function_tags`` gets a list of all user function Tags for the function.
:rtype: list(Tag)
"""
count = ctypes.c_ulonglong()
tags = core.BNGetUserFunctionTags(self.handle, count)
assert tags is not None, "core.BNGetUserFunctionTags returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(tags[i])
assert tag_ref is not None, "core.BNNewTagReference returned None"
result.append(binaryview.Tag(tag_ref))
core.BNFreeTagList(tags, count.value)
return result
def get_lifted_il_at(self, addr:int,
arch:Optional['architecture.Architecture']=None) -> Optional['lowlevelil.LowLevelILInstruction']:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
idx = core.BNGetLiftedILForInstruction(self.handle, arch.handle, addr)
if idx == len(self.lifted_il):
return None
return self.lifted_il[idx]
def get_lifted_ils_at(self, addr:int,
arch:Optional['architecture.Architecture']=None) -> List['lowlevelil.LowLevelILInstruction']:
"""
``get_lifted_ils_at`` gets the Lifted IL Instruction(s) corresponding to the given virtual address
:param int addr: virtual address of the function to be queried
:param Architecture arch: (optional) Architecture for the given function
:rtype: list(LowLevelILInstruction)
:Example:
>>> func = next(bv.functions)
>>> func.get_lifted_ils_at(func.start)
[<il: push(rbp)>]
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
instrs = core.BNGetLiftedILInstructionsForAddress(self.handle, arch.handle, addr, count)
assert instrs is not None, "core.BNGetLiftedILInstructionsForAddress returned None"
result = []
for i in range(0, count.value):
result.append(self.lifted_il[instrs[i]])
core.BNFreeILInstructionList(instrs)
return result
def get_function_tags_of_type(self, tag_type):
"""
``get_function_tags_of_type`` gets a list of all function Tags with a given type.
:param TagType tag_type: TagType object to match in searching
:return: A list of data Tags
:rtype: list(Tag)
"""
count = ctypes.c_ulonglong()
tags = core.BNGetFunctionTagsOfType(self.handle, tag_type.handle, count)
assert tags is not None, "core.BNGetFunctionTagsOfType returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(tags[i])
assert tag_ref is not None, "core.BNNewTagReference returned None"
result.append(binaryview.Tag(tag_ref))
core.BNFreeTagList(tags, count.value)
return result
def get_auto_function_tags_of_type(self, tag_type):
"""
``get_auto_function_tags_of_type`` gets a list of all auto-defined function Tags with a given type.
:param TagType tag_type: TagType object to match in searching
:return: A list of data Tags
:rtype: list(Tag)
"""
count = ctypes.c_ulonglong()
tags = core.BNGetAutoFunctionTagsOfType(self.handle, tag_type.handle, count)
assert tags is not None, "core.BNGetAutoFunctionTagsOfType returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(tags[i])
assert tag_ref is not None, "core.BNNewTagReference returned None"
result.append(binaryview.Tag(tag_ref))
core.BNFreeTagList(tags, count.value)
return result
def get_user_function_tags_of_type(self, tag_type):
"""
``get_user_function_tags_of_type`` gets a list of all user function Tags with a given type.
:param TagType tag_type: TagType object to match in searching
:return: A list of data Tags
:rtype: list(Tag)
"""
count = ctypes.c_ulonglong()
tags = core.BNGetUserFunctionTagsOfType(self.handle, tag_type.handle, count)
assert tags is not None, "core.BNGetUserFunctionTagsOfType returned None"
result = []
for i in range(0, count.value):
tag_ref = core.BNNewTagReference(tags[i])
assert tag_ref is not None, "core.BNNewTagReference returned None"
result.append(binaryview.Tag(tag_ref))
core.BNFreeTagList(tags, count.value)
return result
def remove_user_function_tags_of_type(self, tag_type):
"""
``remove_user_function_tags_of_type`` removes all function Tag objects on a function of a given type
Since this removes user tags, it will be added to the current undo buffer.
:param TagType tag_type: TagType object to match for removing
:rtype: None
"""
core.BNRemoveUserFunctionTagsOfType(self.handle, tag_type.handle)
def get_constants_referenced_by(self, addr:int,
arch:'architecture.Architecture'=None) -> List[variable.ConstantReference]:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call get_constants_referenced_by with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
refs = core.BNGetConstantsReferencedByInstruction(self.handle, arch.handle, addr, count)
assert refs is not None, "core.BNGetConstantsReferencedByInstruction returned None"
result = []
for i in range(0, count.value):
result.append(variable.ConstantReference(refs[i].value, refs[i].size, refs[i].pointer, refs[i].intermediate))
core.BNFreeConstantReferenceList(refs)
return result
def remove_auto_function_tag(self, tag:'binaryview.Tag') -> None:
"""
``remove_user_function_tag`` removes a Tag object as a function tag.
:param Tag tag: Tag object to be added
:rtype: None
"""
core.BNRemoveAutoFunctionTag(self.handle, tag.handle)
def remove_auto_function_tags_of_type(self, tag_type):
"""
``remove_user_function_tags_of_type`` removes all function Tag objects on a function of a given type
:param TagType tag_type: TagType object to match for removing
:rtype: None
"""
core.BNRemoveAutoFunctionTagsOfType(self.handle, tag_type.handle)
def get_lifted_il_flag_uses_for_definition(self, i:'lowlevelil.InstructionIndex',
flag:'architecture.FlagType') -> List['lowlevelil.LowLevelILInstruction']:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
flag = self.arch.get_flag_index(flag)
count = ctypes.c_ulonglong()
instrs = core.BNGetLiftedILFlagUsesForDefinition(self.handle, i, flag, count)
assert instrs is not None, "core.BNGetLiftedILFlagUsesForDefinition returned None"
result = []
for j in range(0, count.value):
result.append(instrs[lowlevelil.InstructionIndex(j)])
core.BNFreeILInstructionList(instrs)
return result
def get_lifted_il_flag_definitions_for_use(self, i:'lowlevelil.InstructionIndex',
flag:'architecture.FlagType') -> List['lowlevelil.InstructionIndex']:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
flag = self.arch.get_flag_index(flag)
count = ctypes.c_ulonglong()
instrs = core.BNGetLiftedILFlagDefinitionsForUse(self.handle, i, flag, count)
assert instrs is not None, "core.BNGetLiftedILFlagDefinitionsForUse returned None"
result = []
for j in range(0, count.value):
result.append(instrs[lowlevelil.InstructionIndex(j)])
core.BNFreeILInstructionList(instrs)
return result
def get_flags_read_by_lifted_il_instruction(self, i:'lowlevelil.InstructionIndex') -> \
List['architecture.RegisterName']:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
count = ctypes.c_ulonglong()
flags = core.BNGetFlagsReadByLiftedILInstruction(self.handle, i, count)
assert flags is not None, "core.BNGetFlagsReadByLiftedILInstruction returned None"
result = []
for j in range(0, count.value):
result.append(self.arch._flags_by_index[flags[j]])
core.BNFreeRegisterList(flags)
return result
def get_flags_written_by_lifted_il_instruction(self, i:'lowlevelil.InstructionIndex') -> \
List['architecture.FlagName']:
count = ctypes.c_ulonglong()
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
flags = core.BNGetFlagsWrittenByLiftedILInstruction(self.handle, i, count)
assert flags is not None, "core.BNGetFlagsWrittenByLiftedILInstruction returned None"
result = []
for j in range(0, count.value):
result.append(self.arch._flags_by_index[flags[j]])
core.BNFreeRegisterList(flags)
return result
def create_graph(self, graph_type:FunctionGraphType=FunctionGraphType.NormalFunctionGraph,
settings:'DisassemblySettings'=None) -> flowgraph.CoreFlowGraph:
if settings is not None:
settings_obj = settings.handle
else:
settings_obj = None
return flowgraph.CoreFlowGraph(core.BNCreateFunctionGraph(self.handle, graph_type, settings_obj))
def apply_imported_types(self, sym:'types.Symbol', type:'types.Type'=None) -> None:
core.BNApplyImportedTypes(self.handle, sym.handle, None if type is None else type.handle)
def apply_auto_discovered_type(self, func_type:'types.Type') -> None:
core.BNApplyAutoDiscoveredFunctionType(self.handle, func_type.handle)
def set_auto_indirect_branches(self, source:int, branches:List[Tuple['architecture.Architecture', int]],
source_arch:Optional['architecture.Architecture']=None) -> None:
if source_arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
source_arch = self.arch
branch_list = (core.BNArchitectureAndAddress * len(branches))()
for i in range(len(branches)):
branch_list[i].arch = branches[i][0].handle
branch_list[i].address = branches[i][1]
core.BNSetAutoIndirectBranches(self.handle, source_arch.handle, source, branch_list, len(branches))
def set_user_indirect_branches(self, source:int, branches:List[Tuple['architecture.Architecture', int]],
source_arch:Optional['architecture.Architecture']=None) -> None:
if source_arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
source_arch = self.arch
branch_list = (core.BNArchitectureAndAddress * len(branches))()
for i in range(len(branches)):
branch_list[i].arch = branches[i][0].handle
branch_list[i].address = branches[i][1]
core.BNSetUserIndirectBranches(self.handle, source_arch.handle, source, branch_list, len(branches))
def get_indirect_branches_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> List['variable.IndirectBranchInfo']:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
branches = core.BNGetIndirectBranchesAt(self.handle, arch.handle, addr, count)
try:
assert branches is not None, "core.BNGetIndirectBranchesAt returned None"
result = []
for i in range(count.value):
result.append(variable.IndirectBranchInfo(architecture.CoreArchitecture._from_cache(branches[i].sourceArch), branches[i].sourceAddr, architecture.CoreArchitecture._from_cache(branches[i].destArch), branches[i].destAddr, branches[i].autoDefined))
return result
finally:
core.BNFreeIndirectBranchList(branches)
def get_block_annotations(self, addr:int, arch:Optional['architecture.Architecture']=None) -> \
List[List['InstructionTextToken']]:
if arch is None:
if self.arch is None:
raise Exception("can not get_block_annotations if Function.arch is None")
arch = self.arch
count = ctypes.c_ulonglong(0)
lines = core.BNGetFunctionBlockAnnotations(self.handle, arch.handle, addr, count)
try:
assert lines is not None, "core.BNGetFunctionBlockAnnotations returned None"
result = []
for i in range(count.value):
result.append(InstructionTextToken._from_core_struct(lines[i].tokens, lines[i].count))
return result
finally:
core.BNFreeInstructionTextLines(lines, count.value)
def set_auto_type(self, value:'types.Type') -> None:
core.BNSetFunctionAutoType(self.handle, value.handle)
def set_user_type(self, value:'types.Type') -> None:
core.BNSetFunctionUserType(self.handle, value.handle)
def set_auto_return_type(self, value:'types.Type') -> None:
type_conf = core.BNTypeWithConfidence()
if value is None:
type_conf.type = None
type_conf.confidence = 0
else:
type_conf.type = value.handle
type_conf.confidence = value.confidence
core.BNSetAutoFunctionReturnType(self.handle, type_conf)
def set_auto_return_regs(self, value:Union['types.RegisterSet', List['architecture.RegisterType']]) -> None:
regs = core.BNRegisterSetWithConfidence()
regs.regs = (ctypes.c_uint * len(value))()
regs.count = len(value)
if self.arch is None:
raise Exception("can not set_auto_return_regs if Function.arch is None")
for i in range(0, len(value)):
regs.regs[i] = self.arch.get_reg_index(value[i])
if isinstance(value, types.RegisterSet):
regs.confidence = value.confidence
else:
regs.confidence = core.max_confidence
core.BNSetAutoFunctionReturnRegisters(self.handle, regs)
def set_auto_calling_convention(self, value:'callingconvention.CallingConvention') -> None:
conv_conf = core.BNCallingConventionWithConfidence()
if value is None:
conv_conf.convention = None
conv_conf.confidence = 0
else:
conv_conf.convention = value.handle
conv_conf.confidence = value.confidence
core.BNSetAutoFunctionCallingConvention(self.handle, conv_conf)
def set_auto_parameter_vars(self, value:Optional[Union[List['variable.Variable'], 'variable.Variable', \
'variable.ParameterVariables']]) -> None:
if value is None:
var_list = []
elif isinstance(value, variable.Variable):
var_list = [value]
elif isinstance(value, variable.ParameterVariables):
var_list = value.vars
else:
var_list = list(value)
var_conf = core.BNParameterVariablesWithConfidence()
var_conf.vars = (core.BNVariable * len(var_list))()
var_conf.count = len(var_list)
for i in range(0, len(var_list)):
var_conf.vars[i].type = var_list[i].source_type
var_conf.vars[i].index = var_list[i].index
var_conf.vars[i].storage = var_list[i].storage
if value is None:
var_conf.confidence = 0
elif isinstance(value, variable.ParameterVariables):
var_conf.confidence = value.confidence
else:
var_conf.confidence = core.max_confidence
core.BNSetAutoFunctionParameterVariables(self.handle, var_conf)
def set_auto_has_variable_arguments(self, value:Union[bool, 'types.BoolWithConfidence']) -> None:
bc = core.BNBoolWithConfidence()
bc.value = bool(value)
if isinstance(value, types.BoolWithConfidence):
bc.confidence = value.confidence
else:
bc.confidence = core.max_confidence
core.BNSetAutoFunctionHasVariableArguments(self.handle, bc)
def set_auto_can_return(self, value:Union[bool, 'types.BoolWithConfidence']) -> None:
bc = core.BNBoolWithConfidence()
bc.value = bool(value)
if isinstance(value, types.BoolWithConfidence):
bc.confidence = value.confidence
else:
bc.confidence = core.max_confidence
core.BNSetAutoFunctionCanReturn(self.handle, bc)
def set_auto_stack_adjustment(self, value:Union[int, 'types.SizeWithConfidence']) -> None:
oc = core.BNOffsetWithConfidence()
oc.value = int(value)
if isinstance(value, types.SizeWithConfidence):
oc.confidence = value.confidence
else:
oc.confidence = core.max_confidence
core.BNSetAutoFunctionStackAdjustment(self.handle, oc)
def set_auto_reg_stack_adjustments(self, value:Mapping['architecture.RegisterStackName', 'types.RegisterStackAdjustmentWithConfidence']):
adjust = (core.BNRegisterStackAdjustment * len(value))()
i = 0
if self.arch is None:
raise Exception("can not set_auto_reg_stack_adjustments if Function.arch is None")
for reg_stack in value.keys():
adjust[i].regStack = self.arch.get_reg_stack_index(reg_stack)
if isinstance(value[reg_stack], types.RegisterStackAdjustmentWithConfidence):
adjust[i].adjustment = value[reg_stack].value
adjust[i].confidence = value[reg_stack].confidence
else:
adjust[i].adjustment = value[reg_stack]
adjust[i].confidence = core.max_confidence
i += 1
core.BNSetAutoFunctionRegisterStackAdjustments(self.handle, adjust, len(value))
def set_auto_clobbered_regs(self, value:List['architecture.RegisterType']) -> None:
regs = core.BNRegisterSetWithConfidence()
regs.regs = (ctypes.c_uint * len(value))()
regs.count = len(value)
if self.arch is None:
raise Exception("can not set_auto_clobbered_regs if Function.arch")
for i in range(0, len(value)):
regs.regs[i] = self.arch.get_reg_index(value[i])
if isinstance(value, types.RegisterSet):
regs.confidence = value.confidence
else:
regs.confidence = core.max_confidence
core.BNSetAutoFunctionClobberedRegisters(self.handle, regs)
def get_int_display_type(self, instr_addr:int, value:int, operand:int, arch:Optional['architecture.Architecture']=None) -> IntegerDisplayType:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
return IntegerDisplayType(core.BNGetIntegerConstantDisplayType(self.handle, arch.handle, instr_addr, value, operand))
def set_int_display_type(self, instr_addr:int, value:int, operand:int, display_type:IntegerDisplayType, arch:Optional['architecture.Architecture']=None) -> None:
"""
:param int instr_addr:
:param int value:
:param int operand:
:param enums.IntegerDisplayType display_type:
:param Architecture arch: (optional)
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if isinstance(display_type, str):
display_type = IntegerDisplayType[display_type]
core.BNSetIntegerConstantDisplayType(self.handle, arch.handle, instr_addr, value, operand, display_type)
def reanalyze(self) -> None:
"""
``reanalyze`` causes this functions to be reanalyzed. This function does not wait for the analysis to finish.
:rtype: None
"""
core.BNReanalyzeFunction(self.handle)
def request_advanced_analysis_data(self) -> None:
core.BNRequestAdvancedFunctionAnalysisData(self.handle)
self._advanced_analysis_requests += 1
def release_advanced_analysis_data(self) -> None:
core.BNReleaseAdvancedFunctionAnalysisData(self.handle)
self._advanced_analysis_requests -= 1
def get_basic_block_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Optional['basicblock.BasicBlock']:
"""
``get_basic_block_at`` returns the BasicBlock of the optionally specified Architecture ``arch`` at the given
address ``addr``.
:param int addr: Address of the BasicBlock to retrieve.
:param Architecture arch: (optional) Architecture of the basic block if different from the Function's self.arch
:Example:
>>> current_function.get_basic_block_at(current_function.start)
<block: x86_64@0x100000f30-0x100000f50>
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
block = core.BNGetFunctionBasicBlockAtAddress(self.handle, arch.handle, addr)
if not block:
return None
return basicblock.BasicBlock(block, self._view)
def get_instr_highlight(self, addr:int, arch:Optional['architecture.Architecture']=None) -> '_highlight.HighlightColor':
"""
:Example:
>>> current_function.set_user_instr_highlight(here, highlight.HighlightColor(red=0xff, blue=0xff, green=0))
>>> current_function.get_instr_highlight(here)
<color: #ff00ff>
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
color = core.BNGetInstructionHighlight(self.handle, arch.handle, addr)
if color.style == HighlightColorStyle.StandardHighlightColor:
return _highlight.HighlightColor(color = color.color, alpha = color.alpha)
elif color.style == HighlightColorStyle.MixedHighlightColor:
return _highlight.HighlightColor(color = color.color, mix_color = color.mixColor, mix = color.mix, alpha = color.alpha)
elif color.style == HighlightColorStyle.CustomHighlightColor:
return _highlight.HighlightColor(red = color.r, green = color.g, blue = color.b, alpha = color.alpha)
return _highlight.HighlightColor(color = HighlightStandardColor.NoHighlightColor)
def set_auto_instr_highlight(self, addr:int, color:Union['_highlight.HighlightColor', HighlightStandardColor],
arch:Optional['architecture.Architecture']=None):
"""
``set_auto_instr_highlight`` highlights the instruction at the specified address with the supplied color
.. warning:: Use only in analysis plugins. Do not use in regular plugins, as colors won't be saved to the database.
:param int addr: virtual address of the instruction to be highlighted
:param HighlightStandardColor|highlight.HighlightColor color: Color value to use for highlighting
:param Architecture arch: (optional) Architecture of the instruction if different from self.arch
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if not isinstance(color, HighlightStandardColor) and not isinstance(color, _highlight.HighlightColor):
raise ValueError("Specified color is not one of HighlightStandardColor, _highlight.HighlightColor")
if isinstance(color, HighlightStandardColor):
color = _highlight.HighlightColor(color = color)
core.BNSetAutoInstructionHighlight(self.handle, arch.handle, addr, color._get_core_struct())
def set_user_instr_highlight(self, addr:int, color:Union['_highlight.HighlightColor', HighlightStandardColor],
arch:Optional['architecture.Architecture']=None):
"""
``set_user_instr_highlight`` highlights the instruction at the specified address with the supplied color
:param int addr: virtual address of the instruction to be highlighted
:param HighlightStandardColor|highlight.HighlightColor color: Color value to use for highlighting
:param Architecture arch: (optional) Architecture of the instruction if different from self.arch
:Example:
>>> current_function.set_user_instr_highlight(here, HighlightStandardColor.BlueHighlightColor)
>>> current_function.set_user_instr_highlight(here, highlight.HighlightColor(red=0xff, blue=0xff, green=0))
"""
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if not isinstance(color, HighlightStandardColor) and not isinstance(color, _highlight.HighlightColor):
raise ValueError("Specified color is not one of HighlightStandardColor, highlight.HighlightColor")
if isinstance(color, HighlightStandardColor):
color = _highlight.HighlightColor(color)
core.BNSetUserInstructionHighlight(self.handle, arch.handle, addr, color._get_core_struct())
def create_auto_stack_var(self, offset:int, var_type:'types.Type', name:str) -> None:
tc = core.BNTypeWithConfidence()
tc.type = var_type.handle
tc.confidence = var_type.confidence
core.BNCreateAutoStackVariable(self.handle, offset, tc, name)
def create_user_stack_var(self, offset:int, var_type:'types.Type', name:str) -> None:
tc = core.BNTypeWithConfidence()
tc.type = var_type.handle
tc.confidence = var_type.confidence
core.BNCreateUserStackVariable(self.handle, offset, tc, name)
def delete_auto_stack_var(self, offset:int) -> None:
core.BNDeleteAutoStackVariable(self.handle, offset)
def delete_user_stack_var(self, offset:int) -> None:
core.BNDeleteUserStackVariable(self.handle, offset)
def create_auto_var(self, var:'variable.Variable', var_type:'types.Type', name:str,
ignore_disjoint_uses:bool=False) -> None:
tc = core.BNTypeWithConfidence()
tc.type = var_type.handle
tc.confidence = var_type.confidence
core.BNCreateAutoVariable(self.handle, var.to_BNVariable(), tc, name, ignore_disjoint_uses)
def create_user_var(self, var:'variable.Variable', var_type:'types.Type', name:str,
ignore_disjoint_uses:bool=False) -> None:
tc = core.BNTypeWithConfidence()
tc.type = var_type.handle
tc.confidence = var_type.confidence
core.BNCreateUserVariable(self.handle, var.to_BNVariable(), tc, name, ignore_disjoint_uses)
def delete_auto_var(self, var:'variable.Variable') -> None:
core.BNDeleteAutoVariable(self.handle, var.to_BNVariable())
def delete_user_var(self, var:'variable.Variable') -> None:
core.BNDeleteUserVariable(self.handle, var.to_BNVariable())
def is_var_user_defined(self, var:'variable.Variable') -> bool:
return core.BNIsVariableUserDefined(self.handle, var.to_BNVariable())
def get_stack_var_at_frame_offset(self, offset:int, addr:int, arch:Optional['architecture.Architecture']=None) -> \
Optional['variable.Variable']:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
found_var = core.BNVariableNameAndType()
if not core.BNGetStackVariableAtFrameOffset(self.handle, arch.handle, addr, offset, found_var):
return None
result = variable.Variable.from_BNVariable(self, found_var.var)
core.BNFreeVariableNameAndType(found_var)
return result
def get_type_tokens(self, settings:'DisassemblySettings'=None) -> List['DisassemblyTextLine']:
_settings = None
if settings is not None:
_settings = settings.handle
count = ctypes.c_ulonglong()
lines = core.BNGetFunctionTypeTokens(self.handle, settings, count)
assert lines is not None, "core.BNGetFunctionTypeTokens returned None"
result = []
for i in range(0, count.value):
addr = lines[i].addr
color = _highlight.HighlightColor._from_core_struct(lines[i].highlight)
tokens = InstructionTextToken._from_core_struct(lines[i].tokens, lines[i].count)
result.append(DisassemblyTextLine(tokens, addr, color = color))
core.BNFreeDisassemblyTextLines(lines, count.value)
return result
def get_reg_value_at_exit(self, reg:'architecture.RegisterType') -> 'variable.RegisterValue':
if self.arch is None:
raise Exception("can not get_reg_value_at_exit if Function.arch is")
result = core.BNGetFunctionRegisterValueAtExit(self.handle, self.arch.get_reg_index(reg))
return variable.RegisterValue.from_BNRegisterValue(result, self.arch)
def set_auto_call_stack_adjustment(self, addr:int, adjust:Union[int, 'types.SizeWithConfidence'],\
arch:Optional['architecture.Architecture']=None) -> None:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if not isinstance(adjust, types.SizeWithConfidence):
adjust = types.SizeWithConfidence(adjust)
core.BNSetAutoCallStackAdjustment(self.handle, arch.handle, addr, adjust.value, adjust.confidence)
def set_auto_call_reg_stack_adjustment(self, addr:int, adjust:Mapping['architecture.RegisterStackName', int],\
arch:Optional['architecture.Architecture']=None) -> None:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
adjust_buf = (core.BNRegisterStackAdjustment * len(adjust))()
i = 0
for reg_stack in adjust.keys():
adjust_buf[i].regStack = arch.get_reg_stack_index(reg_stack)
value = adjust[reg_stack]
if not isinstance(value, types.RegisterStackAdjustmentWithConfidence):
value = types.RegisterStackAdjustmentWithConfidence(value)
adjust_buf[i].adjustment = value.value
adjust_buf[i].confidence = value.confidence
i += 1
core.BNSetAutoCallRegisterStackAdjustment(self.handle, arch.handle, addr, adjust_buf, len(adjust))
def set_auto_call_reg_stack_adjustment_for_reg_stack(self, addr:int, reg_stack:'architecture.RegisterStackType',
adjust, arch:Optional['architecture.Architecture']=None) -> None:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
reg_stack = arch.get_reg_stack_index(reg_stack)
if not isinstance(adjust, types.RegisterStackAdjustmentWithConfidence):
adjust = types.RegisterStackAdjustmentWithConfidence(adjust)
core.BNSetAutoCallRegisterStackAdjustmentForRegisterStack(self.handle, arch.handle, addr, reg_stack,
adjust.value, adjust.confidence)
def set_call_type_adjustment(self, addr:int, adjust_type:'types.Type', arch:Optional['architecture.Architecture']=None) -> \
None:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if adjust_type is None:
tc = None
else:
tc = core.BNTypeWithConfidence()
tc.type = adjust_type.handle
tc.confidence = adjust_type.confidence
core.BNSetUserCallTypeAdjustment(self.handle, arch.handle, addr, tc)
def set_call_stack_adjustment(self, addr:int, adjust:Union[int, 'types.SizeWithConfidence'],
arch:Optional['architecture.Architecture']=None):
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if not isinstance(adjust, types.SizeWithConfidence):
adjust = types.SizeWithConfidence(adjust)
core.BNSetUserCallStackAdjustment(self.handle, arch.handle, addr, adjust.value, adjust.confidence)
def set_call_reg_stack_adjustment(self, addr:int,
adjust:Mapping['architecture.RegisterStackName', 'types.RegisterStackAdjustmentWithConfidence'],
arch:Optional['architecture.Architecture']=None) -> None:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
adjust_buf = (core.BNRegisterStackAdjustment * len(adjust))()
i = 0
for reg_stack in adjust.keys():
adjust_buf[i].regStack = arch.get_reg_stack_index(reg_stack)
value = adjust[reg_stack]
if not isinstance(value, types.RegisterStackAdjustmentWithConfidence):
value = types.RegisterStackAdjustmentWithConfidence(value)
adjust_buf[i].adjustment = value.value
adjust_buf[i].confidence = value.confidence
i += 1
core.BNSetUserCallRegisterStackAdjustment(self.handle, arch.handle, addr, adjust_buf, len(adjust))
def set_call_reg_stack_adjustment_for_reg_stack(self, addr:int, reg_stack:'architecture.RegisterStackType',
adjust:Union[int, 'types.RegisterStackAdjustmentWithConfidence'], arch:Optional['architecture.Architecture']=None) -> None:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
reg_stack = arch.get_reg_stack_index(reg_stack)
if not isinstance(adjust, types.RegisterStackAdjustmentWithConfidence):
adjust = types.RegisterStackAdjustmentWithConfidence(adjust)
core.BNSetUserCallRegisterStackAdjustmentForRegisterStack(self.handle, arch.handle, addr, reg_stack,
adjust.value, adjust.confidence)
def get_call_type_adjustment(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Optional['types.Type']:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
result = core.BNGetCallTypeAdjustment(self.handle, arch.handle, addr)
if not result.type:
return None
platform = self.platform
return types.Type(result.type, platform = platform, confidence = result.confidence)
def get_call_stack_adjustment(self, addr:int, arch:Optional['architecture.Architecture']=None) -> 'types.SizeWithConfidence':
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
result = core.BNGetCallStackAdjustment(self.handle, arch.handle, addr)
return types.SizeWithConfidence(result.value, confidence = result.confidence)
def get_call_reg_stack_adjustment(self, addr:int, arch:Optional['architecture.Architecture']=None) -> \
Mapping['architecture.RegisterName', 'types.RegisterStackAdjustmentWithConfidence']:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
adjust = core.BNGetCallRegisterStackAdjustment(self.handle, arch.handle, addr, count)
assert adjust is not None, "core.BNGetCallRegisterStackAdjustment returned None"
result = {}
for i in range(0, count.value):
result[arch.get_reg_stack_name(adjust[i].regStack)] = types.RegisterStackAdjustmentWithConfidence(
adjust[i].adjustment, confidence = adjust[i].confidence)
core.BNFreeRegisterStackAdjustments(adjust)
return result
def get_call_reg_stack_adjustment_for_reg_stack(self, addr:int, reg_stack:'architecture.RegisterStackType',\
arch:Optional['architecture.Architecture']=None) -> 'types.RegisterStackAdjustmentWithConfidence':
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
reg_stack = arch.get_reg_stack_index(reg_stack)
adjust = core.BNGetCallRegisterStackAdjustmentForRegisterStack(self.handle, arch.handle, addr, reg_stack)
result = types.RegisterStackAdjustmentWithConfidence(adjust.adjustment, confidence = adjust.confidence)
return result
def is_call_instruction(self, addr:int, arch:Optional['architecture.Architecture']=None) -> bool:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
return core.BNIsCallInstruction(self.handle, arch.handle, addr)
def set_user_var_value(self, var:'variable.Variable', def_addr:int, value:'variable.PossibleValueSet') -> None:
"""
`set_user_var_value` allows the user to specify a PossibleValueSet value for an MLIL variable at its \
definition site.
.. warning:: Setting the variable value, triggers a reanalysis of the function and allows the dataflow \
to compute and propagate values which depend on the current variable. This implies that branch conditions \
whose values can be determined statically will be computed, leading to potential branch elimination at \
the HLIL layer.
:param Variable var: Variable for which the value is to be set
:param int def_addr: Address of the definition site of the variable
:param PossibleValueSet value: Informed value of the variable
:rtype: None
:Example:
>>> var = current_mlil[0].operands[0]
>>> def_site = 0x40108d
>>> value = PossibleValueSet.constant(5)
>>> current_function.set_user_var_value(var, def_site, value)
"""
if self.arch is None:
raise Exception("can not set_user_var_value if Function.arch is None")
var_defs = self.mlil.get_var_definitions(var)
if var_defs is None:
raise ValueError("Could not get definition for Variable")
found = False
for site in var_defs:
if site.address == def_addr:
found = True
break
if not found:
raise ValueError("No definition for Variable found at given address")
def_site = core.BNArchitectureAndAddress()
def_site.arch = self.arch.handle
def_site.address = def_addr
core.BNSetUserVariableValue(self.handle, var.to_BNVariable(), def_site, value._to_api_object())
def clear_user_var_value(self, var:'variable.Variable', def_addr:int) -> None:
"""
Clears a previously defined user variable value.
:param Variable var: Variable for which the value was informed
:param int def_addr: Address of the definition site of the variable
:rtype: None
"""
var_defs = self.mlil.get_var_definitions(var)
if var_defs is None:
raise ValueError("Could not get definition for Variable")
if self.arch is None:
raise Exception("can not clear_user_var_value if Function.arch is None")
found = False
for site in var_defs:
if site.address == def_addr:
found = True
break
if not found:
raise ValueError("No definition for Variable found at given address")
def_site = core.BNArchitectureAndAddress()
def_site.arch = self.arch.handle
def_site.address = def_addr
core.BNClearUserVariableValue(self.handle, var.to_BNVariable(), def_site)
def get_all_user_var_values(self) -> \
Mapping['variable.Variable', Mapping['ArchAndAddr', 'variable.PossibleValueSet']]:
"""
Returns a map of current defined user variable values.
:returns: Map of user current defined user variable values and their definition sites.
:type: dict of (Variable, dict of (ArchAndAddr, PossibleValueSet))
"""
count = ctypes.c_ulonglong(0)
var_values = core.BNGetAllUserVariableValues(self.handle, count)
assert var_values is not None, "core.BNGetAllUserVariableValues returned None"
result = {}
i = 0
for i in range(count.value):
var_val = var_values[i]
var = variable.Variable.from_BNVariable(self, var_val.var)
if var not in result:
result[var] = {}
def_site = ArchAndAddr(var_val.defSite.arch, var_val.defSite.address)
result[var][def_site] = variable.PossibleValueSet(def_site.arch, var_val.value)
core.BNFreeUserVariableValues(var_values)
return result
def clear_all_user_var_values(self) -> None:
"""
Clear all user defined variable values.
:rtype: None
"""
all_values = self.get_all_user_var_values()
for var in all_values:
for def_site in all_values[var]:
self.clear_user_var_value(var, def_site.addr)
def request_debug_report(self, name:str) -> None:
"""
``request_debug_report`` can generate internal debug reports for a variety of analysis.
Current list of possible values include:
- mlil_translator
- stack_adjust_graph
- high_level_il
:param str name: Name of the debug report
:rtype: None
"""
core.BNRequestFunctionDebugReport(self.handle, name)
self.view.update_analysis()
@property
def call_sites(self) -> List['binaryview.ReferenceSource']:
"""
``call_sites`` returns a list of possible call sites contained in this function.
This includes ordinary calls, tail calls, and indirect jumps. Not all of the returned call sites
are necessarily true call sites; some may simply be unresolved indirect jumps, for example.
:return: List of References that represent the sources of possible calls in this function
:rtype: list(ReferenceSource)
"""
count = ctypes.c_ulonglong(0)
refs = core.BNGetFunctionCallSites(self.handle, count)
assert refs is not None, "core.BNGetFunctionCallSites returned None"
result = []
for i in range(0, count.value):
if refs[i].func:
func = Function(self.view, core.BNNewFunctionReference(refs[i].func))
else:
func = None
if refs[i].arch:
arch = architecture.CoreArchitecture._from_cache(refs[i].arch)
else:
arch = None
addr = refs[i].addr
result.append(binaryview.ReferenceSource(func, arch, addr))
core.BNFreeCodeReferences(refs, count.value)
return result
@property
def callees(self) -> List['Function']:
"""
``callees`` returns a list of functions that this function calls
This does not include the address of those calls, rather just the function objects themselves. Use :py:meth:`call_sites` to identify the location of these calls.
:return: List of Functions that this function calls
:rtype: list(Function)
"""
called = []
for callee_addr in self.callee_addresses:
func = self.view.get_function_at(callee_addr, self.platform)
if func is not None:
called.append(func)
return called
@property
def callee_addresses(self) -> List[int]:
"""
``callee_addressses`` returns a list of start addresses for functions that call this function.
Does not point to the actual address where the call occurs, just the start of the function that contains the reference.
:return: List of start addresess for Functions that call this function
:rtype: list(int)
"""
result = []
for ref in self.call_sites:
result.extend(self.view.get_callees(ref.address, ref.function, ref.arch))
return result
@property
def callers(self) -> List[int]:
"""
``callers`` returns a list of functions that call this function
Does not point to the actual address where the call occurs, just the start of the function that contains the call.
:return: List of start addresess for Functions that call this function
:rtype: list(int)
"""
functions = []
for ref in self.view.get_code_refs(self.start):
if ref.function is not None:
functions.append(ref.function)
return functions
@property
def workflow(self):
handle = core.BNGetWorkflowForFunction(self.handle)
if handle is None:
return None
return workflow.Workflow(handle = handle)
def get_mlil_var_refs(self, var:'variable.Variable') -> List[ILReferenceSource]:
"""
``get_mlil_var_refs`` returns a list of ILReferenceSource objects (IL xrefs or cross-references)
that reference the given variable. The variable is a local variable that can be either on the stack,
in a register, or in a flag.
This function is related to get_hlil_var_refs(), which returns variable references collected
from HLIL. The two can be different in several cases, e.g., multiple variables in MLIL can be merged
into a single variable in HLIL.
:param Variable var: Variable for which to query the xref
:return: List of IL References for the given variable
:rtype: list(ILReferenceSource)
:Example:
>>> var = current_mlil[0].operands[0]
>>> current_function.get_mlil_var_refs(var)
"""
count = ctypes.c_ulonglong(0)
refs = core.BNGetMediumLevelILVariableReferences(self.handle, var.to_BNVariable(), count)
assert refs is not None, "core.BNGetMediumLevelILVariableReferences returned None"
result = []
for i in range(0, count.value):
if refs[i].func:
func = Function(self.view, core.BNNewFunctionReference(refs[i].func))
else:
func = None
if refs[i].arch:
arch = architecture.CoreArchitecture._from_cache(refs[i].arch)
else:
arch = None
result.append(ILReferenceSource(
func, arch, refs[i].addr, refs[i].type, refs[i].exprId))
core.BNFreeILReferences(refs, count.value)
return result
def get_mlil_var_refs_from(self, addr:int, length:int=None, arch:Optional['architecture.Architecture']=None) -> \
List[VariableReferenceSource]:
"""
``get_mlil_var_refs_from`` returns a list of variables referenced by code in the function ``func``,
of the architecture ``arch``, and at the address ``addr``. If no function is specified, references from
all functions and containing the address will be returned. If no architecture is specified, the
architecture of the function will be used.
This function is related to get_hlil_var_refs_from(), which returns variable references collected
from HLIL. The two can be different in several cases, e.g., multiple variables in MLIL can be merged
into a single variable in HLIL.
:param int addr: virtual address to query for variable references
:param int length: optional length of query
:param Architecture arch: optional architecture of query
:return: list of variable reference sources
:rtype: list(VariableReferenceSource)
"""
result = []
count = ctypes.c_ulonglong(0)
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if length is None:
refs = core.BNGetMediumLevelILVariableReferencesFrom(self.handle, arch.handle, addr, count)
assert refs is not None, "core.BNGetMediumLevelILVariableReferencesFrom returned None"
else:
refs = core.BNGetMediumLevelILVariableReferencesInRange(self.handle, arch.handle, addr, length, count)
assert refs is not None, "core.BNGetMediumLevelILVariableReferencesInRange returned None"
for i in range(0, count.value):
var = variable.Variable.from_BNVariable(self, refs[i].var)
if refs[i].source.func:
func = Function(self.view, core.BNNewFunctionReference(refs[i].source.func))
else:
func = None
if refs[i].source.arch:
_arch = architecture.CoreArchitecture._from_cache(refs[i].source.arch)
else:
_arch = arch
src = ILReferenceSource(func, _arch, refs[i].source.addr, refs[i].source.type, refs[i].source.exprId)
result.append(VariableReferenceSource(var, src))
core.BNFreeVariableReferenceSourceList(refs, count.value)
return result
def get_hlil_var_refs(self, var:'variable.Variable') -> List[ILReferenceSource]:
"""
``get_hlil_var_refs`` returns a list of ILReferenceSource objects (IL xrefs or cross-references)
that reference the given variable. The variable is a local variable that can be either on the stack,
in a register, or in a flag.
:param Variable var: Variable for which to query the xref
:return: List of IL References for the given variable
:rtype: list(ILReferenceSource)
:Example:
>>> var = current_hlil[0].operands[0]
>>> current_function.get_hlil_var_refs(var)
"""
count = ctypes.c_ulonglong(0)
refs = core.BNGetHighLevelILVariableReferences(self.handle, var.to_BNVariable(), count)
assert refs is not None, "core.BNGetHighLevelILVariableReferences returned None"
result = []
for i in range(0, count.value):
if refs[i].func:
func = Function(self.view, core.BNNewFunctionReference(refs[i].func))
else:
func = None
if refs[i].arch:
arch = architecture.CoreArchitecture._from_cache(refs[i].arch)
else:
arch = None
result.append(ILReferenceSource(
func, arch, refs[i].addr, refs[i].type, refs[i].exprId))
core.BNFreeILReferences(refs, count.value)
return result
def get_hlil_var_refs_from(self, addr:int, length:int=None, arch:Optional['architecture.Architecture']=None) -> \
List[VariableReferenceSource]:
"""
``get_hlil_var_refs_from`` returns a list of variables referenced by code in the function ``func``,
of the architecture ``arch``, and at the address ``addr``. If no function is specified, references from
all functions and containing the address will be returned. If no architecture is specified, the
architecture of the function will be used.
:param int addr: virtual address to query for variable references
:param int length: optional length of query
:param Architecture arch: optional architecture of query
:return: list of variables reference sources
:rtype: list(VariableReferenceSource)
"""
result = []
count = ctypes.c_ulonglong(0)
if arch is None:
if self.arch is None:
raise Exception("can not get_block_annotations if Function.arch is None")
arch = self.arch
if length is None:
refs = core.BNGetHighLevelILVariableReferencesFrom(self.handle, arch.handle, addr, count)
assert refs is not None, "core.BNGetHighLevelILVariableReferencesFrom returned None"
else:
refs = core.BNGetHighLevelILVariableReferencesInRange(self.handle, arch.handle, addr, length, count)
assert refs is not None, "core.BNGetHighLevelILVariableReferencesInRange returned None"
for i in range(0, count.value):
var = variable.Variable.from_BNVariable(self, refs[i].var)
if refs[i].source.func:
func = Function(self.view, core.BNNewFunctionReference(refs[i].source.func))
else:
func = None
if refs[i].source.arch:
_arch = architecture.CoreArchitecture._from_cache(refs[i].source.arch)
else:
_arch = arch
src = ILReferenceSource(func, _arch, refs[i].source.addr, refs[i].source.type, refs[i].source.exprId)
result.append(VariableReferenceSource(var, src))
core.BNFreeVariableReferenceSourceList(refs, count.value)
return result
def get_instruction_containing_address(self, addr:int, arch:Optional['architecture.Architecture']=None) -> \
Optional[int]:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
start = ctypes.c_ulonglong()
if core.BNGetInstructionContainingAddress(self.handle, arch.handle, addr, start):
return start.value
return None
class AdvancedFunctionAnalysisDataRequestor:
def __init__(self, func:'Function'=None):
self._function = func
if self._function is not None:
self._function.request_advanced_analysis_data()
def __del__(self):
if self._function is not None:
self._function.release_advanced_analysis_data()
@property
def function(self) -> Optional['Function']:
return self._function
@function.setter
def function(self, func:'Function') -> None:
if self._function is not None:
self._function.release_advanced_analysis_data()
self._function = func
if self._function is not None:
self._function.request_advanced_analysis_data()
def close(self) -> None:
if self._function is not None:
self._function.release_advanced_analysis_data()
self._function = None
class DisassemblyTextLine:
def __init__(self, tokens:List['InstructionTextToken'], address:int=None, il_instr:ILInstructionType=None,
color:Union['_highlight.HighlightColor', HighlightStandardColor]=None):
self._address = address
self._tokens = tokens
self._il_instruction = il_instr
if color is None:
self._highlight = _highlight.HighlightColor()
else:
if not isinstance(color, HighlightStandardColor) and not isinstance(color, _highlight.HighlightColor):
raise ValueError("Specified color is not one of HighlightStandardColor, _highlight.HighlightColor")
if isinstance(color, HighlightStandardColor):
color = _highlight.HighlightColor(color)
self._highlight = color
def __str__(self):
return "".join(map(str, self.tokens))
def __repr__(self):
if self.address is None:
return str(self)
return "<%#x: %s>" % (self.address, str(self))
@property
def address(self) -> Optional[int]:
return self._address
@address.setter
def address(self, value:int) -> None:
self._address = value
@property
def tokens(self) -> List['InstructionTextToken']:
return self._tokens
@tokens.setter
def tokens(self, value:List['InstructionTextToken']) -> None:
self._tokens = value
@property
def il_instruction(self) -> Optional[ILInstructionType]:
return self._il_instruction
@il_instruction.setter
def il_instruction(self, value:ILInstructionType) -> None:
self._il_instruction = value
@property
def highlight(self) -> '_highlight.HighlightColor':
return self._highlight
@highlight.setter
def highlight(self, value:'_highlight.HighlightColor') -> None:
self._highlight = value
class DisassemblyTextRenderer:
def __init__(self, func:AnyFunctionType=None, settings:'DisassemblySettings'=None,
handle:core.BNDisassemblySettings=None):
if handle is None:
if func is None:
raise ValueError("function required for disassembly")
settings_obj = None
if settings is not None:
settings_obj = settings.handle
if isinstance(func, Function):
self.handle = core.BNCreateDisassemblyTextRenderer(func.handle, settings_obj)
elif isinstance(func, lowlevelil.LowLevelILFunction):
self.handle = core.BNCreateLowLevelILDisassemblyTextRenderer(func.handle, settings_obj)
elif isinstance(func, mediumlevelil.MediumLevelILFunction):
self.handle = core.BNCreateMediumLevelILDisassemblyTextRenderer(func.handle, settings_obj)
elif isinstance(func, highlevelil.HighLevelILFunction):
self.handle = core.BNCreateHighLevelILDisassemblyTextRenderer(func.handle, settings_obj)
else:
raise TypeError("invalid function object")
else:
self.handle = handle
def __del__(self):
core.BNFreeDisassemblyTextRenderer(self.handle)
@property
def function(self) -> 'Function':
return Function(handle = core.BNGetDisassemblyTextRendererFunction(self.handle))
@property
def il_function(self) -> Optional[ILFunctionType]:
llil = core.BNGetDisassemblyTextRendererLowLevelILFunction(self.handle)
if llil:
return lowlevelil.LowLevelILFunction(handle = llil)
mlil = core.BNGetDisassemblyTextRendererMediumLevelILFunction(self.handle)
if mlil:
return mediumlevelil.MediumLevelILFunction(handle = mlil)
hlil = core.BNGetDisassemblyTextRendererHighLevelILFunction(self.handle)
if hlil:
return highlevelil.HighLevelILFunction(handle = hlil)
return None
@property
def basic_block(self) -> Optional['basicblock.BasicBlock']:
result = core.BNGetDisassemblyTextRendererBasicBlock(self.handle)
if result:
return basicblock.BasicBlock(handle = result)
return None
@basic_block.setter
def basic_block(self, block:'basicblock.BasicBlock') -> None:
if block is not None:
core.BNSetDisassemblyTextRendererBasicBlock(self.handle, block.handle)
else:
core.BNSetDisassemblyTextRendererBasicBlock(self.handle, None)
@property
def arch(self) -> 'architecture.Architecture':
return architecture.CoreArchitecture._from_cache(handle = core.BNGetDisassemblyTextRendererArchitecture(self.handle))
@arch.setter
def arch(self, arch='architecture.Architecture') -> None:
core.BNSetDisassemblyTextRendererArchitecture(self.handle, arch.handle)
@property
def settings(self) -> 'DisassemblySettings':
return DisassemblySettings(handle = core.BNGetDisassemblyTextRendererSettings(self.handle))
@settings.setter
def settings(self, settings:'DisassemblySettings') -> None:
if settings is not None:
core.BNSetDisassemblyTextRendererSettings(self.handle, settings.handle)
core.BNSetDisassemblyTextRendererSettings(self.handle, None)
@property
def il(self) -> bool:
return core.BNIsILDisassemblyTextRenderer(self.handle)
@property
def has_data_flow(self) -> bool:
return core.BNDisassemblyTextRendererHasDataFlow(self.handle)
def get_instruction_annotations(self, addr:int) -> List['InstructionTextToken']:
count = ctypes.c_ulonglong()
tokens = core.BNGetDisassemblyTextRendererInstructionAnnotations(self.handle, addr, count)
assert tokens is not None
result = InstructionTextToken._from_core_struct(tokens, count.value)
core.BNFreeInstructionText(tokens, count.value)
return result
def get_instruction_text(self, addr:int) -> Generator[Tuple[Optional['DisassemblyTextLine'], int], None, None]:
count = ctypes.c_ulonglong()
length = ctypes.c_ulonglong()
lines = ctypes.POINTER(core.BNDisassemblyTextLine)()
if not core.BNGetDisassemblyTextRendererInstructionText(self.handle, addr, length, lines, count):
yield None, 0
return
il_function = self.il_function
try:
for i in range(0, count.value):
addr = lines[i].addr
if (lines[i].instrIndex != 0xffffffffffffffff) and (il_function is not None):
il_instr = il_function[lines[i].instrIndex]
else:
il_instr = None
color = _highlight.HighlightColor._from_core_struct(lines[i].highlight)
tokens = InstructionTextToken._from_core_struct(lines[i].tokens, lines[i].count)
yield DisassemblyTextLine(tokens, addr, il_instr, color), length.value
finally:
core.BNFreeDisassemblyTextLines(lines, count.value)
def get_disassembly_text(self, addr:int) -> Generator[Tuple[Optional['DisassemblyTextLine'], int], None, None]:
count = ctypes.c_ulonglong()
length = ctypes.c_ulonglong()
length.value = 0
lines = ctypes.POINTER(core.BNDisassemblyTextLine)()
ok = core.BNGetDisassemblyTextRendererLines(self.handle, addr, length, lines, count)
if not ok:
yield None, 0
return
il_function = self.il_function
try:
for i in range(0, count.value):
addr = lines[i].addr
if (lines[i].instrIndex != 0xffffffffffffffff) and (il_function is not None):
il_instr = il_function[lines[i].instrIndex]
else:
il_instr = None
color = _highlight.HighlightColor._from_core_struct(lines[i].highlight)
tokens = InstructionTextToken._from_core_struct(lines[i].tokens, lines[i].count)
yield DisassemblyTextLine(tokens, addr, il_instr, color), length.value
finally:
core.BNFreeDisassemblyTextLines(lines, count.value)
def post_process_lines(self, addr:int, length:int, in_lines:Union[str, List[str], List['DisassemblyTextLine']],
indent_spaces:str=''):
if isinstance(in_lines, str):
in_lines = in_lines.split('\n')
line_buf = (core.BNDisassemblyTextLine * len(in_lines))()
for i, line in enumerate(in_lines):
if isinstance(line, str):
line = DisassemblyTextLine([InstructionTextToken(InstructionTextTokenType.TextToken, line)])
if not isinstance(line, DisassemblyTextLine):
line = DisassemblyTextLine(line)
if line.address is None:
if len(line.tokens) > 0:
line_buf[i].addr = line.tokens[0].address
else:
line_buf[i].addr = 0
else:
line_buf[i].addr = line.address
if line.il_instruction is not None:
line_buf[i].instrIndex = line.il_instruction.instr_index
else:
line_buf[i].instrIndex = 0xffffffffffffffff
color = line.highlight
if not isinstance(color, HighlightStandardColor) and not isinstance(color, _highlight.HighlightColor):
raise ValueError("Specified color is not one of HighlightStandardColor, _highlight.HighlightColor")
if isinstance(color, HighlightStandardColor):
color = _highlight.HighlightColor(color)
line_buf[i].highlight = color._get_core_struct()
line_buf[i].count = len(line.tokens)
line_buf[i].tokens = InstructionTextToken._get_core_struct(line.tokens)
count = ctypes.c_ulonglong()
lines = ctypes.POINTER(core.BNDisassemblyTextLine)()
lines = core.BNPostProcessDisassemblyTextRendererLines(self.handle, addr, length, line_buf, len(in_lines), count, indent_spaces)
assert lines is not None, "core.BNPostProcessDisassemblyTextRendererLines returned None"
il_function = self.il_function
try:
for i in range(count.value):
addr = lines[i].addr
if (lines[i].instrIndex != 0xffffffffffffffff) and (il_function is not None):
il_instr = il_function[lines[i].instrIndex]
else:
il_instr = None
color = _highlight.HighlightColor._from_core_struct(lines[i].highlight)
tokens = InstructionTextToken._from_core_struct(lines[i].tokens, lines[i].count)
yield DisassemblyTextLine(tokens, addr, il_instr, color)
finally:
core.BNFreeDisassemblyTextLines(lines, count.value)
def reset_deduplicated_comments(self) -> None:
core.BNResetDisassemblyTextRendererDeduplicatedComments(self.handle)
def add_symbol_token(self, tokens:List['InstructionTextToken'], addr:int, size:int, operand:int=None) -> bool:
if operand is None:
operand = 0xffffffff
count = ctypes.c_ulonglong()
new_tokens = ctypes.POINTER(core.BNInstructionTextToken)()
if not core.BNGetDisassemblyTextRendererSymbolTokens(self.handle, addr, size, operand, new_tokens, count):
return False
assert new_tokens is not None
result = InstructionTextToken._from_core_struct(new_tokens, count.value)
tokens += result
core.BNFreeInstructionText(new_tokens, count.value)
return True
def add_stack_var_reference_tokens(self, tokens:List['InstructionTextToken'],
ref:'variable.StackVariableReference') -> None:
stack_ref = core.BNStackVariableReference()
if ref.source_operand is None:
stack_ref.sourceOperand = 0xffffffff
else:
stack_ref.sourceOperand = ref.source_operand
if ref.type is None:
stack_ref.type = None
stack_ref.typeConfidence = 0
else:
stack_ref.type = ref.type.handle
stack_ref.typeConfidence = ref.type.confidence
stack_ref.name = ref.name
stack_ref.varIdentifier = ref.var.identifier
stack_ref.referencedOffset = ref.referenced_offset
stack_ref.size = ref.size
count = ctypes.c_ulonglong()
new_tokens = core.BNGetDisassemblyTextRendererStackVariableReferenceTokens(self.handle, stack_ref, count)
assert new_tokens is not None
result = InstructionTextToken._from_core_struct(new_tokens, count.value)
tokens += result
core.BNFreeInstructionText(new_tokens, count.value)
@staticmethod
def is_integer_token(token:'InstructionTextToken') -> bool:
return core.BNIsIntegerToken(token)
def add_integer_token(self, tokens:List['InstructionTextToken'], int_token:'InstructionTextToken', addr:int,
arch:Optional['architecture.Architecture']=None) -> None:
if arch is not None:
arch = arch.handle
in_token_obj = InstructionTextToken._get_core_struct([int_token])
count = ctypes.c_ulonglong()
new_tokens = core.BNGetDisassemblyTextRendererIntegerTokens(self.handle, in_token_obj, arch, addr, count)
assert new_tokens is not None
result = InstructionTextToken._from_core_struct(new_tokens, count.value)
tokens += result
core.BNFreeInstructionText(new_tokens, count.value)
def wrap_comment(self, lines:List['DisassemblyTextLine'], cur_line:'DisassemblyTextLine', comment:str,
has_auto_annotations:bool, leading_spaces:str=" ", indent_spaces:str= "") -> None:
cur_line_obj = core.BNDisassemblyTextLine()
cur_line_obj.addr = cur_line.address
if cur_line.il_instruction is None:
cur_line_obj.instrIndex = 0xffffffffffffffff
else:
cur_line_obj.instrIndex = cur_line.il_instruction.instr_index
cur_line_obj.highlight = cur_line.highlight._get_core_struct()
cur_line_obj.tokens = InstructionTextToken._get_core_struct(cur_line.tokens)
cur_line_obj.count = len(cur_line.tokens)
count = ctypes.c_ulonglong()
new_lines = core.BNDisassemblyTextRendererWrapComment(self.handle, cur_line_obj, count, comment,
has_auto_annotations, leading_spaces, indent_spaces)
assert new_lines is not None, "core.BNDisassemblyTextRendererWrapComment returned None"
il_function = self.il_function
for i in range(0, count.value):
addr = new_lines[i].addr
if (new_lines[i].instrIndex != 0xffffffffffffffff) and (il_function is not None):
il_instr = il_function[new_lines[i].instrIndex]
else:
il_instr = None
color = _highlight.HighlightColor._from_core_struct(new_lines[i].highlight)
tokens = InstructionTextToken._from_core_struct(new_lines[i].tokens, new_lines[i].count)
lines.append(DisassemblyTextLine(tokens, addr, il_instr, color))
core.BNFreeDisassemblyTextLines(new_lines, count.value)
class InstructionTextToken:
"""
``class InstructionTextToken`` is used to tell the core about the various components in the disassembly views.
The below table is provided for documentation purposes but the complete list of TokenTypes is available at: :class:`!enums.InstructionTextTokenType`. Note that types marked as `Not emitted by architectures` are not intended to be used by Architectures during lifting. Rather, they are added by the core during analysis or display. UI plugins, however, may make use of them as appropriate.
Uses of tokens include plugins that parse the output of an architecture (though parsing IL is recommended), or additionally, applying color schemes appropriately.
========================== ============================================
InstructionTextTokenType Description
========================== ============================================
AddressDisplayToken **Not emitted by architectures**
AnnotationToken **Not emitted by architectures**
ArgumentNameToken **Not emitted by architectures**
BeginMemoryOperandToken The start of memory operand
CharacterConstantToken A printable character
CodeRelativeAddressToken **Not emitted by architectures**
CodeSymbolToken **Not emitted by architectures**
DataSymbolToken **Not emitted by architectures**
EndMemoryOperandToken The end of a memory operand
ExternalSymbolToken **Not emitted by architectures**
FieldNameToken **Not emitted by architectures**
FloatingPointToken Floating point number
HexDumpByteValueToken **Not emitted by architectures**
HexDumpInvalidByteToken **Not emitted by architectures**
HexDumpSkippedByteToken **Not emitted by architectures**
HexDumpTextToken **Not emitted by architectures**
ImportToken **Not emitted by architectures**
IndirectImportToken **Not emitted by architectures**
InstructionToken The instruction mnemonic
IntegerToken Integers
KeywordToken **Not emitted by architectures**
LocalVariableToken **Not emitted by architectures**
NameSpaceSeparatorToken **Not emitted by architectures**
NameSpaceToken **Not emitted by architectures**
OpcodeToken **Not emitted by architectures**
OperandSeparatorToken The comma or delimiter that separates tokens
PossibleAddressToken Integers that are likely addresses
RegisterToken Registers
StringToken **Not emitted by architectures**
StructOffsetToken **Not emitted by architectures**
TagToken **Not emitted by architectures**
TextToken Used for anything not of another type.
CommentToken Comments
TypeNameToken **Not emitted by architectures**
========================== ============================================
"""
def __init__(self, token_type:Union[InstructionTextTokenType, int], text:str, value:int=0, size:int=0,
operand:int=0xffffffff, context:InstructionTextTokenContext=InstructionTextTokenContext.NoTokenContext,
address:int=0, confidence:int=core.max_confidence, typeNames:List[str]=[], width:int=0):
self._type = InstructionTextTokenType(token_type)
self._text = text
self._value = value
self._size = size
self._operand = operand
self._context = InstructionTextTokenContext(context)
self._confidence = confidence
self._address = address
self._typeNames = typeNames
self._width = width
if width == 0:
self._width = len(self._text)
@staticmethod
def _from_core_struct(tokens:'ctypes.pointer[core.BNInstructionTextToken]', count:int) -> List['InstructionTextToken']:
result:List['InstructionTextToken'] = []
for j in range(count):
token_type = InstructionTextTokenType(tokens[j].type)
text = tokens[j].text
if not isinstance(text, str):
text = text.decode("utf-8")
width = tokens[j].width
value = tokens[j].value
size = tokens[j].size
operand = tokens[j].operand
context = tokens[j].context
confidence = tokens[j].confidence
address = tokens[j].address
typeNames = []
for i in range(tokens[j].namesCount):
if not isinstance(tokens[j].typeNames[i], str):
typeNames.append(tokens[j].typeNames[i].decode("utf-8"))
else:
typeNames.append(tokens[j].typeNames[i])
result.append(InstructionTextToken(token_type, text, value, size, operand, context, address, confidence, typeNames, width))
return result
@staticmethod
def _get_core_struct(tokens:List['InstructionTextToken']) -> 'ctypes.Array[core.BNInstructionTextToken]':
""" Helper method for converting between core.BNInstructionTextToken and InstructionTextToken lists """
result = (core.BNInstructionTextToken * len(tokens))()
for j in range(len(tokens)):
result[j].type = tokens[j].type
result[j].text = tokens[j].text
result[j].width = tokens[j].width
result[j].value = tokens[j].value
result[j].size = tokens[j].size
result[j].operand = tokens[j].operand
result[j].context = tokens[j].context
result[j].confidence = tokens[j].confidence
result[j].address = tokens[j].address
result[j].namesCount = len(tokens[j].typeNames)
result[j].typeNames = (ctypes.c_char_p * len(tokens[j].typeNames))()
for i in range(len(tokens[j].typeNames)):
result[j].typeNames[i] = tokens[j].typeNames[i].encode("utf-8")
return result
def __str__(self):
return self._text
def __repr__(self):
return repr(self._text)
@property
def type(self) -> InstructionTextTokenType:
return self._type
@type.setter
def type(self, value:InstructionTextTokenType) -> None:
self._type = value
@property
def text(self) -> str:
return self._text
@text.setter
def text(self, value:str) -> None:
self._text = value
@property
def value(self) -> int:
return self._value
@value.setter
def value(self, value:int) -> None:
self._value = value
@property
def size(self) -> int:
return self._size
@size.setter
def size(self, value:int) -> None:
self._size = value
@property
def operand(self) -> int:
return self._operand
@operand.setter
def operand(self, value:int) -> None:
self._operand = value
@property
def context(self) -> InstructionTextTokenContext:
return self._context
@context.setter
def context(self, value:InstructionTextTokenContext) -> None:
self._context = value
@property
def confidence(self) -> int:
return self._confidence
@confidence.setter
def confidence(self, value:int) -> None:
self._confidence = value
@property
def address(self) -> int:
return self._address
@address.setter
def address(self, value:int) -> None:
self._address = value
@property
def typeNames(self) -> List[str]:
return self._typeNames
@typeNames.setter
def typeNames(self, value:List[str]) -> None:
self._typeNames = value
@property
def width(self) -> int:
return self._width
|