summaryrefslogtreecommitdiff
path: root/python/architecture.py
blob: c11007df599f4a7e111094aad43a52975e48b550 (plain)
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
# Copyright (c) 2015-2026 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 traceback
import ctypes
from typing import Generator, Union, List, Optional, Mapping, Tuple, NewType, Dict, Set, Any
from dataclasses import dataclass, field

# Binary Ninja components
import binaryninja
from . import _binaryninjacore as core
from .enums import (
    Endianness, ImplicitRegisterExtend, BranchType, LowLevelILFlagCondition, FlagRole, LowLevelILOperation,
    InstructionTextTokenType, InstructionTextTokenContext, IntrinsicClass
)
from .log import log_error_for_exception, log_debug_for_exception
from . import lowlevelil
from . import types
from . import databuffer
from . import platform
from . import callingconvention
from . import typelibrary
from . import function
from . import binaryview
from . import variable
from . import basicblock
from . import log

RegisterIndex = NewType('RegisterIndex', int)
RegisterStackIndex = NewType('RegisterStackIndex', int)
FlagIndex = NewType('FlagIndex', int)
SemanticClassIndex = NewType('SemanticClassIndex', int)
SemanticGroupIndex = NewType('SemanticGroupIndex', int)
IntrinsicIndex = NewType('IntrinsicIndex', int)
FlagWriteTypeIndex = NewType('FlagWriteTypeIndex', int)

RegisterName = NewType('RegisterName', str)
RegisterStackName = NewType('RegisterStackName', str)
FlagName = NewType('FlagName', str)
SemanticClassName = NewType('SemanticClassName', str)
SemanticGroupName = NewType('SemanticGroupName', str)
IntrinsicName = NewType('IntrinsicName', str)
FlagWriteTypeName = NewType('FlagWriteTypeName', str)

RegisterType = Union[RegisterName, 'lowlevelil.ILRegister', RegisterIndex]
FlagType = Union[FlagName, 'lowlevelil.ILFlag', FlagIndex]
FlagWriteType = Union[FlagWriteTypeName, FlagWriteTypeIndex]
RegisterStackType = Union[RegisterStackName, 'lowlevelil.ILRegisterStack', RegisterStackIndex]
SemanticClassType = Union[SemanticClassName, 'lowlevelil.ILSemanticFlagClass', SemanticClassIndex]
SemanticGroupType = Union[SemanticGroupName, 'lowlevelil.ILSemanticFlagGroup', SemanticGroupIndex]
IntrinsicType = Union[IntrinsicName, 'lowlevelil.ILIntrinsic', IntrinsicIndex]


@dataclass
class BasicBlockAnalysisContext:
	"""Used by ``analyze_basic_blocks`` and contains analysis settings and other contextual information.

    .. note:: This class is meant to be used by Architecture plugins only
    """

	_handle: core.BNBasicBlockAnalysisContext
	_function: "function.Function"
	_contextual_returns_dirty: bool

	# In
	_indirect_branches: List["variable.IndirectBranchInfo"]
	_indirect_no_return_calls: Set["function.ArchAndAddr"]
	_analysis_skip_override: core.FunctionAnalysisSkipOverride
	_guided_analysis_mode: bool
	_trigger_guided_on_invalid_instruction: bool
	_translate_tail_calls: bool
	_disallow_branch_to_string: bool
	_max_function_size: int

	# In/Out
	_max_size_reached: bool
	_contextual_returns: Dict["function.ArchAndAddr", bool]

	# Out
	_direct_code_references: Dict[int, "function.ArchAndAddr"]
	_direct_no_return_calls: Set["function.ArchAndAddr"]
	_halted_disassembly_addresses: Set["function.ArchAndAddr"]

	@staticmethod
	def from_core_struct(bn_bb_context: core.BNBasicBlockAnalysisContext) -> "BasicBlockAnalysisContext":
		"""Create a BasicBlockAnalysisContext from a core.BNBasicBlockAnalysisContext structure."""

		indirect_branches = []
		for i in range(0, bn_bb_context.indirectBranchesCount):
			ibi = variable.IndirectBranchInfo(
			    source_arch=CoreArchitecture._from_cache(bn_bb_context.indirectBranches[i].sourceArch),
			    source_addr=bn_bb_context.indirectBranches[i].sourceAddr,
			    dest_arch=CoreArchitecture._from_cache(bn_bb_context.indirectBranches[i].destArch),
			    dest_addr=bn_bb_context.indirectBranches[i].destAddr,
			    auto_defined=bn_bb_context.indirectBranches[i].autoDefined,
			)
			indirect_branches.append(ibi)

		indirect_no_return_calls = set()
		for i in range(0, bn_bb_context.indirectNoReturnCallsCount):
			loc = function.ArchAndAddr(
			    CoreArchitecture._from_cache(bn_bb_context.indirectNoReturnCalls[i].arch),
			    bn_bb_context.indirectNoReturnCalls[i].address,
			)
			indirect_no_return_calls.add(loc)

		contextual_returns = {}
		for i in range(0, bn_bb_context.contextualFunctionReturnCount):
			loc = function.ArchAndAddr(
			    CoreArchitecture._from_cache(bn_bb_context.contextualFunctionReturnLocations[i].arch),
			    bn_bb_context.contextualFunctionReturnLocations[i].address,
			)
			contextual_returns[loc] = bn_bb_context._contextualFunctionReturnValues[i]

		direct_code_references = {}
		for i in range(0, bn_bb_context.directRefCount):
			src = function.ArchAndAddr(
			    CoreArchitecture._from_cache(bn_bb_context.directRefSources[i].arch),
			    bn_bb_context.directRefSources[i].address,
			)
			direct_code_references[bn_bb_context.directRefTargets[i]] = src

		direct_no_return_calls = set()
		for i in range(0, bn_bb_context.directNoReturnCallsCount):
			loc = function.ArchAndAddr(
			    CoreArchitecture._from_cache(bn_bb_context.directNoReturnCallLocations[i].arch),
			    bn_bb_context.directNoReturnCallLocations[i].address,
			)
			direct_no_return_calls.add(loc)

		halted_disassembly_addresses = set()
		for i in range(0, bn_bb_context.haltedDisassemblyAddressesCount):
			addr = function.ArchAndAddr(
			    CoreArchitecture._from_cache(bn_bb_context.haltedDisassemblyAddresses[i].arch),
			    bn_bb_context.haltedDisassemblyAddresses[i].address,
			)
			halted_disassembly_addresses.add(addr)

		view = binaryview.BinaryView(handle=core.BNGetFunctionData(bn_bb_context.function))
		return BasicBlockAnalysisContext(
		    _handle=bn_bb_context,
		    _function=function.Function(view, core.BNNewFunctionReference(bn_bb_context.function)),
		    _indirect_branches=indirect_branches, _indirect_no_return_calls=indirect_no_return_calls,
		    _analysis_skip_override=bn_bb_context.analysisSkipOverride,
		    _guided_analysis_mode=bn_bb_context.guidedAnalysisMode,
		    _trigger_guided_on_invalid_instruction=bn_bb_context.triggerGuidedOnInvalidInstruction,
		    _translate_tail_calls=bn_bb_context.translateTailCalls,
		    _disallow_branch_to_string=bn_bb_context.disallowBranchToString,
		    _max_function_size=bn_bb_context.maxFunctionSize, _max_size_reached=bn_bb_context.maxSizeReached,
		    _contextual_returns=contextual_returns, _contextual_returns_dirty=False,
		    _direct_code_references=direct_code_references, _direct_no_return_calls=direct_no_return_calls,
		    _halted_disassembly_addresses=halted_disassembly_addresses,
		)

	@property
	def indirect_branches(self) -> List["variable.IndirectBranchInfo"]:
		"""Get the list of indirect branches in this context."""

		return self._indirect_branches

	@property
	def indirect_no_return_calls(self) -> Set["function.ArchAndAddr"]:
		"""Get the set of indirect no-return calls in this context."""

		return self._indirect_no_return_calls

	@property
	def analysis_skip_override(self) -> core.FunctionAnalysisSkipOverride:
		"""Get the analysis skip override setting for this context."""

		return self._analysis_skip_override

	@property
	def guided_analysis_mode(self) -> bool:
		"""Get the setting that determines if functions start in guided analysis mode."""

		return self._guided_analysis_mode

	@property
	def trigger_guided_on_invalid_instruction(self) -> bool:
		"""Get the setting that determines if guided mode should be triggered on invalid instructions."""

		return self._trigger_guided_on_invalid_instruction

	@property
	def translate_tail_calls(self) -> bool:
		"""Get setting from context that determines if tail calls should be translated."""

		return self._translate_tail_calls

	@property
	def disallow_branch_to_string(self) -> bool:
		"""Get setting from context that determines if branches to string addresses should be disallowed."""

		return self._disallow_branch_to_string

	@property
	def max_function_size(self) -> int:
		"""Get the maximum function size setting for this context."""

		return self._max_function_size

	@property
	def halt_on_invalid_instruction(self) -> bool:
		"""Get the setting from context that determines if analysis should halt on invalid instructions."""

		return self._halt_on_invalid_instruction

	@property
	def max_size_reached(self) -> bool:
		"""Get boolean that indicates if the maximum function size has been reached."""

		return self._max_size_reached

	@max_size_reached.setter
	def max_size_reached(self, value: bool) -> None:
		"""Set boolean that indicates if the maximum function size has been reached.

        :param bool value: The new value for max_size_reached
        """
		if not isinstance(value, bool):
			raise TypeError("value must be a boolean")

		self._max_size_reached = value

	@property
	def contextual_returns(self) -> Dict["function.ArchAndAddr", bool]:
		"""Get the mapping of contextual function return locations to their values."""

		return self._contextual_returns

	def add_contextual_return(self, loc: "function.ArchAndAddr", value: bool) -> None:
		"""
        ``add_contextual_return`` adds a contextual function return location and its value to the current function.

        :param function.ArchAndAddr loc: The location of the contextual function return
        :param bool value: The value of the contextual function return
        """
		if not isinstance(value, bool):
			raise TypeError("value must be a boolean")

		if not isinstance(loc, function.ArchAndAddr):
			raise TypeError("loc must be an instance of function.ArchAndAddr")

		# Update existing value if it exists
		if loc in self._contextual_returns:
			if self._contextual_returns[loc] == value:
				return

		self._contextual_returns[loc] = value
		self._contextual_returns_dirty = True

	@property
	def direct_code_references(self) -> Dict[int, "function.ArchAndAddr"]:
		"""Get the mapping of direct code reference targets to their source locations."""

		return self._direct_code_references

	def add_direct_code_reference(self, target: int, source: "function.ArchAndAddr") -> None:
		"""
        ``add_direct_code_reference`` adds a direct code reference to the current function.

        :param int target: The target address of the direct code reference
        :param function.ArchAndAddr source: The source location of the direct code reference
        """

		if not isinstance(target, int):
			raise TypeError("target must be an integer")

		if not isinstance(source, function.ArchAndAddr):
			raise TypeError("source must be an instance of function.ArchAndAddr")

		self._direct_code_references[target] = source

	@property
	def direct_no_return_calls(self) -> Set["function.ArchAndAddr"]:
		"""Get the set of direct no-return call locations in this context."""

		return self._direct_no_return_calls

	def add_direct_no_return_call(self, loc: "function.ArchAndAddr") -> None:
		"""
        ``add_direct_no_return_call`` adds a direct no-return call location to the current function.

        :param function.ArchAndAddr loc: The location of the direct no-return call
        """
		if not isinstance(loc, function.ArchAndAddr):
			raise TypeError("loc must be an instance of function.ArchAndAddr")

		self._direct_no_return_calls.add(loc)

	@property
	def halted_disassembly_addresses(self) -> Set["function.ArchAndAddr"]:
		"""Get the set of addresses where disassembly has been halted."""

		return self._halted_disassembly_addresses

	def add_halted_disassembly_address(self, loc: "function.ArchAndAddr") -> None:
		"""
        ``add_halted_disassembly_address`` adds an address to the set of halted disassembly addresses.

        :param function.ArchAndAddr loc: The location of the halted disassembly address
        """
		if not isinstance(loc, function.ArchAndAddr):
			raise TypeError("loc must be an instance of function.ArchAndAddr")

		self._halted_disassembly_addresses.add(loc)

	@property
	def function_arch_context(self) -> Any:
		"""Get the function architecture context"""

		tok = int(self._handle.functionArchContext or 0)
		if tok == 0:
			return None
		return self._function.arch.function_arch_contexts.get(tok, None)

	@function_arch_context.setter
	def function_arch_context(self, value: Any) -> None:
		"""Set the function architecture context"""

		if self._handle.functionArchContext:
			raise ValueError("Function architecture context has already been set")
		token = self._function.start
		self._function.arch.function_arch_contexts[token] = value
		self._handle.functionArchContext = ctypes.c_void_p(token)

	def create_basic_block(self, arch: "Architecture", start: int) -> Optional["basicblock.BasicBlock"]:
		"""
        ``create_basic_block`` creates a new BasicBlock at the specified address for the given Architecture.

        :param Architecture arch: Architecture of the BasicBlock to create
        :param int start: Address of the BasicBlock to create
        """

		if not isinstance(arch, Architecture):
			raise TypeError("arch must be an instance of architecture.Architecture")

		bnblock = core.BNAnalyzeBasicBlocksContextCreateBasicBlock(self._handle, arch.handle, start)
		if not bnblock:
			return None

		view = binaryview.BinaryView(handle=core.BNGetFunctionData(self._function.handle))
		return basicblock.BasicBlock(bnblock, view)

	def add_basic_block(self, block: "basicblock.BasicBlock") -> None:
		"""
        ``add_basic_block`` adds a BasicBlock to the current function.

        :param basicblock.BasicBlock block: The BasicBlock to add
        """
		if not isinstance(block, basicblock.BasicBlock):
			raise TypeError("block must be an instance of basicblock.BasicBlock")

		core.BNAnalyzeBasicBlocksContextAddBasicBlockToFunction(self._handle, block.handle)

	def add_temp_outgoing_reference(self, target: "function.Function") -> None:
		"""
        ``add_temp_outgoing_reference`` adds a temporary outgoing reference to the specified function.

        :param function.Function target: The target function to add a temporary outgoing reference to
        """
		if not isinstance(target, function.Function):
			raise TypeError("target must be an instance of function.Function")

		core.BNAnalyzeBasicBlocksContextAddTempReference(self._handle, target.handle)

	def finalize(self) -> None:
		"""
        ``finalize`` finalizes the function's basic block analysis
        """

		if self._direct_code_references:
			total = len(self._direct_code_references)
			sources = (core.BNArchitectureAndAddress * total)()
			targets = (ctypes.c_ulonglong * total)()
			for i, (target, src) in enumerate(self._direct_code_references.items()):
				sources[i].arch = src.arch.handle
				sources[i].address = src.addr
				targets[i] = target

			core.BNAnalyzeBasicBlocksContextSetDirectCodeReferences(self._handle, sources, targets, total)

		if self._direct_no_return_calls:
			total = len(self._direct_no_return_calls)
			direct_no_return_calls = (core.BNArchitectureAndAddress * total)()
			for i, loc in enumerate(self._direct_no_return_calls):
				direct_no_return_calls[i].arch = loc.arch.handle
				direct_no_return_calls[i].address = loc.addr
			core.BNAnalyzeBasicBlocksContextSetDirectNoReturnCalls(self._handle, direct_no_return_calls, total)

		if self._halted_disassembly_addresses:
			total = len(self._halted_disassembly_addresses)
			halted_addresses = (core.BNArchitectureAndAddress * total)()
			for i, loc in enumerate(self._halted_disassembly_addresses):
				halted_addresses[i].arch = loc.arch.handle
				halted_addresses[i].address = loc.addr
			core.BNAnalyzeBasicBlocksContextSetHaltedDisassemblyAddresses(self._handle, halted_addresses, total)

		self._handle.maxSizeReached = ctypes.c_bool(self._max_size_reached)
		if self._contextual_returns_dirty:
			total = len(self._contextual_returns)
			values = (ctypes.c_bool * total)()
			returns = (core.BNArchitectureAndAddress * total)()
			for i, (loc, value) in enumerate(self._contextual_returns.items()):
				returns[i].arch = loc.arch.handle
				returns[i].address = loc.addr
				values[i] = value
			core.BNAnalyzeBasicBlocksContextSetContextualFunctionReturns(self._handle, returns, values, total)


@dataclass
class FunctionLifterContext:
	"""Used by ``lift_function`` and contains contextual information for function-level lifting

	.. note:: This class is meant to be used by Architecture plugins only
	"""

	_handle: core.BNFunctionLifterContext
	_function: "function.Function"
	_platform: "platform.Platform"
	_logger: "log.Logger"
	_blocks: List["basicblock.BasicBlock"]
	_contextual_returns: Dict["function.ArchAndAddr", bool]
	_inline_remapping: Dict["function.ArchAndAddr", "function.ArchAndAddr"]
	_user_indirect_branches: Dict["function.ArchAndAddr", Set["function.ArchAndAddr"]]
	_auto_indirect_branches: Dict["function.ArchAndAddr", Set["function.ArchAndAddr"]]
	_inlined_calls: Set[int]
	_function_arch_context_token: int

	@staticmethod
	def from_core_struct(
	    func: core.BNLowLevelILFunction, bn_fl_context: core.BNFunctionLifterContext
	) -> "FunctionLifterContext":
		"""Create a FunctionLifterContext from a core.BNFunctionLifterContext structure."""

		session_id = core.BNLoggerGetSessionId(bn_fl_context.logger)
		name = core.BNLoggerGetName(bn_fl_context.logger)
		logger = log.Logger(session_id, name, handle=core.BNNewLoggerReference(bn_fl_context.logger))

		plat = platform.CorePlatform._from_cache(core.BNNewPlatformReference(bn_fl_context.platform))
		blocks = []
		for i in range(0, bn_fl_context.basicBlockCount):
			blocks.append(basicblock.BasicBlock(core.BNNewBasicBlockReference(bn_fl_context.basicBlocks[i])))

		contextual_returns = {}
		for i in range(0, bn_fl_context.contextualFunctionReturnCount):
			loc = function.ArchAndAddr(
			    CoreArchitecture._from_cache(bn_fl_context.contextualFunctionReturnLocations[i].arch),
			    bn_fl_context.contextualFunctionReturnLocations[i].address,
			)

			contextual_returns[loc] = bn_fl_context._contextualFunctionReturnValues[i]

		inline_remapping = {}
		for i in range(0, bn_fl_context.inlinedRemappingEntryCount):
			key = function.ArchAndAddr(
			    CoreArchitecture._from_cache(bn_fl_context.inlinedRemappingKeys[i].arch),
			    bn_fl_context.inlinedRemappingKeys[i].address,
			)
			dest = function.ArchAndAddr(
			    CoreArchitecture._from_cache(bn_fl_context.inlinedRemappingEntries[i].destination.arch),
			    bn_fl_context.inlinedRemappingEntries[i].destination.address,
			)
			inline_remapping[src] = dest

		user_indirect_branches = {}
		auto_indirect_branches = {}
		for i in range(0, bn_fl_context.indirectBranchesCount):
			src = function.ArchAndAddr(
			    CoreArchitecture._from_cache(bn_fl_context.indirectBranches[i].sourceArch),
			    bn_fl_context.indirectBranches[i].sourceAddr,
			)

			dest = function.ArchAndAddr(
				CoreArchitecture._from_cache(bn_fl_context.indirectBranches[i].destArch),
				bn_fl_context.indirectBranches[i].destAddr,
			)

			if bn_fl_context.indirectBranches[i].autoDefined:
				if src not in auto_indirect_branches:
					auto_indirect_branches[src] = set()
				auto_indirect_branches[src].add(dest)
			else:
				if src not in user_indirect_branches:
					user_indirect_branches[src] = set()
				user_indirect_branches[src].add(dest)

		inlined_calls = set()
		for i in range(0, bn_fl_context.inlinedCallsCount):
			inlined_calls.add(bn_fl_context.inlinedCalls[i])

		return FunctionLifterContext(
		    _handle=bn_fl_context,
		    _function=lowlevelil.LowLevelILFunction(plat.arch,
		                                            core.BNNewLowLevelILFunctionReference(func)), _platform=plat,
		    _logger=logger, _blocks=blocks, _contextual_returns=contextual_returns, _inline_remapping=inline_remapping,
		    _user_indirect_branches=user_indirect_branches, _auto_indirect_branches=auto_indirect_branches,
		    _inlined_calls=inlined_calls, _function_arch_context_token=bn_fl_context.functionArchContext,
		)

	def prepare_block_translation(self, function, arch, address):
		"""Prepare the basic block for translation"""

		core.BNPrepareBlockTranslation(function.handle, arch.handle, address)

	@property
	def blocks(self) -> List["basicblock.BasicBlock"]:
		"""Get the list of basic blocks in this context"""

		return self._blocks

	@property
	def function_arch_context(self) -> Any:
		"""Get the function architecture context"""

		return self._function.arch.function_arch_contexts.get(self._function_arch_context_token, None)

@dataclass(frozen=True)
class RegisterInfo:
	full_width_reg: RegisterName
	size: int
	offset: int = 0
	extend: ImplicitRegisterExtend = ImplicitRegisterExtend.NoExtend
	index: Optional[RegisterIndex] = None

	def __repr__(self):
		if self.extend == ImplicitRegisterExtend.ZeroExtendToFullWidth:
			extend = ", zero extend"
		elif self.extend == ImplicitRegisterExtend.SignExtendToFullWidth:
			extend = ", sign extend"
		else:
			extend = ""
		return f"<reg: size {self.size}, offset {self.offset} in {self.full_width_reg}{extend}>"


@dataclass(frozen=True)
class RegisterStackInfo:
	storage_regs: List[RegisterName]
	top_relative_regs: List[RegisterName]
	stack_top_reg: RegisterName
	index: Optional[RegisterStackIndex] = None

	def __repr__(self):
		return f"<reg stack: {len(self.storage_regs)} regs, stack top in {self.stack_top_reg}>"


@dataclass(frozen=True)
class IntrinsicInput:
	type: 'types.Type'
	name: str = ""

	def __repr__(self):
		if len(self.name) == 0:
			return f"<input: {self.type}>"
		return f"<input: {self.type} {self.name}>"


@dataclass(frozen=True)
class IntrinsicInfo:
	inputs: List[IntrinsicInput]
	outputs: List['types.Type']
	index: Optional[int] = None

	def __repr__(self):
		return f"<intrinsic: {repr(self.inputs)} -> {repr(self.outputs)}>"


@dataclass(frozen=True)
class InstructionBranch:
	type: BranchType
	target: int
	arch: Optional['Architecture']

	def __repr__(self):
		if self.arch is not None:
			return f"<{self.type.name}: {self.arch.name}@{self.target:#x}>"
		return f"<{self.type}: {self.target:#x}>"


@dataclass(frozen=False)
class InstructionInfo:
	length: int = 0
	arch_transition_by_target_addr: bool = False
	branch_delay: int = 0
	branches: List[InstructionBranch] = field(default_factory=list)

	def add_branch(self, branch_type: BranchType, target: int = 0, arch: Optional['Architecture'] = None) -> None:
		self.branches.append(InstructionBranch(branch_type, target, arch))

	def __len__(self):
		return self.length

	def __repr__(self):
		branch_delay = ""
		if self.branch_delay:
			branch_delay = ", delay slot"
		return f"<instr: {self.length} bytes{branch_delay}, {repr(self.branches)}>"


class _ArchitectureMetaClass(type):
	def __iter__(self) -> Generator['Architecture', None, None]:
		binaryninja._init_plugins()
		count = ctypes.c_ulonglong()
		archs = core.BNGetArchitectureList(count)
		if archs is None:
			return
		try:
			for i in range(0, count.value):
				yield CoreArchitecture._from_cache(archs[i])
		finally:
			core.BNFreeArchitectureList(archs)

	def __getitem__(cls: '_ArchitectureMetaClass', name: str) -> 'Architecture':
		binaryninja._init_plugins()
		arch = core.BNGetArchitectureByName(name)
		if arch is None:
			raise KeyError(f"'{name}' is not a valid architecture")
		return CoreArchitecture._from_cache(arch)

	def __contains__(cls: '_ArchitectureMetaClass', name: object) -> bool:
		if not isinstance(name, str):
			return False
		try:
			cls[name]
			return True
		except KeyError:
			return False

	def get(cls: '_ArchitectureMetaClass', name: str, default: Any = None) -> Optional['Architecture']:
		try:
			return cls[name]
		except KeyError:
			if default is not None:
				return default
			return None


class Architecture(metaclass=_ArchitectureMetaClass):
	"""
	``class Architecture`` is the parent class for all CPU architectures. Subclasses of Architecture implement assembly,
	disassembly, IL lifting, and patching.

	``class Architecture`` has a metaclass with the additional methods ``register``, and supports
	iteration::

		>>> #List the architectures
		>>> list(Architecture)
		[<arch: aarch64>, <arch: armv7>, <arch: thumb2>, <arch: armv7eb>, <arch: thumb2eb>, <arch: mipsel32>, <arch: mips32>, <arch: ppc>, <arch: ppc64>, <arch: ppc_le>, <arch: ppc64_le>, <arch: x86_16>, <arch: x86>, <arch: x86_64>]
		>>> #Register a new Architecture
		>>> class MyArch(Architecture):
		...  name = "MyArch"
		...
		>>> MyArch.register()
		>>> list(Architecture)
		[<arch: aarch64>, <arch: armv7>, <arch: thumb2>, <arch: armv7eb>, <arch: thumb2eb>, <arch: mipsel32>, <arch: mips32>, <arch: ppc>, <arch: ppc64>, <arch: ppc_le>, <arch: ppc64_le>, <arch: x86_16>, <arch: x86>, <arch: x86_64>, <arch: MyArch>]
		>>>

	For the purposes of this documentation the variable ``arch`` will be used in the following context ::

		>>> from binaryninja import *
		>>> arch = Architecture['x86']

	.. note:: The `max_instr_length` property of an architecture is not necessarily representative of the maximum instruction size of the associated CPU architecture. Rather, it represents the maximum size of a potential instruction that the architecture plugin can handle. So for example, the value for x86 is 16 despite the largest valid instruction being only 15 bytes long, and the value for mips32 is currently 8 because multiple instructions are decoded looking for delay slots so they can be reordered.

	"""
	name = None
	endianness = Endianness.LittleEndian
	address_size = 8
	default_int_size = 4
	instr_alignment = 1
	max_instr_length = 16
	opcode_display_length = 8
	regs: Dict[RegisterName, RegisterInfo] = {}
	stack_pointer = None
	link_reg = None
	global_regs = []
	system_regs = []
	flags: List[FlagName] = []
	flag_write_types: List[FlagWriteTypeName] = []
	semantic_flag_classes: List[SemanticClassName] = []
	semantic_flag_groups: List[SemanticGroupName] = []
	flag_roles: Dict[FlagName, FlagRole] = {}
	flags_required_for_flag_condition: Dict['lowlevelil.LowLevelILFlagCondition', List[FlagName]] = {}
	flags_required_for_semantic_flag_group: Dict[SemanticGroupName, List[FlagName]] = {}
	flag_conditions_for_semantic_flag_group: Dict[SemanticGroupName, Dict[Optional[SemanticClassName], 'lowlevelil.LowLevelILFlagCondition']] = {}
	flags_written_by_flag_write_type: Dict[FlagWriteTypeName, List[FlagName]] = {}
	semantic_class_for_flag_write_type: Dict[FlagWriteTypeName, SemanticClassName] = {}
	reg_stacks: Dict[RegisterStackName, RegisterStackInfo] = {}
	intrinsics = {}
	next_address = 0
	function_arch_contexts: Dict[int, Any] = {}

	def __init__(self):
		binaryninja._init_plugins()

		if self.__class__.opcode_display_length > self.__class__.max_instr_length:
			self.__class__.opcode_display_length = self.__class__.max_instr_length

		self._cb = core.BNCustomArchitecture()
		self._cb.context = 0
		self._cb.init = self._cb.init.__class__(self._init)
		self._cb.getEndianness = self._cb.getEndianness.__class__(self._get_endianness)
		self._cb.getAddressSize = self._cb.getAddressSize.__class__(self._get_address_size)
		self._cb.getDefaultIntegerSize = self._cb.getDefaultIntegerSize.__class__(self._get_default_integer_size)
		self._cb.getInstructionAlignment = self._cb.getInstructionAlignment.__class__(self._get_instruction_alignment)
		self._cb.getMaxInstructionLength = self._cb.getMaxInstructionLength.__class__(self._get_max_instruction_length)
		self._cb.getOpcodeDisplayLength = self._cb.getOpcodeDisplayLength.__class__(self._get_opcode_display_length)
		self._cb.getAssociatedArchitectureByAddress = self._cb.getAssociatedArchitectureByAddress.__class__(
		    self._get_associated_arch_by_address
		)
		self._cb.getInstructionInfo = self._cb.getInstructionInfo.__class__(self._get_instruction_info)
		self._cb.getInstructionText = self._cb.getInstructionText.__class__(self._get_instruction_text)
		self._cb.getInstructionTextWithContext = self._cb.getInstructionTextWithContext.__class__(
		    self._get_instruction_text_with_context
		)
		self._cb.freeInstructionText = self._cb.freeInstructionText.__class__(self._free_instruction_text)
		self._cb.getInstructionLowLevelIL = self._cb.getInstructionLowLevelIL.__class__(
		    self._get_instruction_low_level_il
		)
		self._cb.analyzeBasicBlocks = self._cb.analyzeBasicBlocks.__class__(self._analyze_basic_blocks)
		self._cb.liftFunction = self._cb.liftFunction.__class__(self._lift_function)
		self._cb.freeFunctionArchContext = self._cb.freeFunctionArchContext.__class__(self._free_function_arch_context)
		self._cb.getRegisterName = self._cb.getRegisterName.__class__(self._get_register_name)
		self._cb.getFlagName = self._cb.getFlagName.__class__(self._get_flag_name)
		self._cb.getFlagWriteTypeName = self._cb.getFlagWriteTypeName.__class__(self._get_flag_write_type_name)
		self._cb.getSemanticFlagClassName = self._cb.getSemanticFlagClassName.__class__(
		    self._get_semantic_flag_class_name
		)
		self._cb.getSemanticFlagGroupName = self._cb.getSemanticFlagGroupName.__class__(
		    self._get_semantic_flag_group_name
		)
		self._cb.getFullWidthRegisters = self._cb.getFullWidthRegisters.__class__(self._get_full_width_registers)
		self._cb.getAllRegisters = self._cb.getAllRegisters.__class__(self._get_all_registers)
		self._cb.getAllFlags = self._cb.getAllRegisters.__class__(self._get_all_flags)
		self._cb.getAllFlagWriteTypes = self._cb.getAllRegisters.__class__(self._get_all_flag_write_types)
		self._cb.getAllSemanticFlagClasses = self._cb.getAllSemanticFlagClasses.__class__(
		    self._get_all_semantic_flag_classes
		)
		self._cb.getAllSemanticFlagGroups = self._cb.getAllSemanticFlagGroups.__class__(
		    self._get_all_semantic_flag_groups
		)
		self._cb.getFlagRole = self._cb.getFlagRole.__class__(self._get_flag_role)
		self._cb.getFlagsRequiredForFlagCondition = self._cb.getFlagsRequiredForFlagCondition.__class__(
		    self._get_flags_required_for_flag_condition
		)
		self._cb.getFlagsRequiredForSemanticFlagGroup = self._cb.getFlagsRequiredForSemanticFlagGroup.__class__(
		    self._get_flags_required_for_semantic_flag_group
		)
		self._cb.getFlagConditionsForSemanticFlagGroup = self._cb.getFlagConditionsForSemanticFlagGroup.__class__(
		    self._get_flag_conditions_for_semantic_flag_group
		)
		self._cb.freeFlagConditionsForSemanticFlagGroup = self._cb.freeFlagConditionsForSemanticFlagGroup.__class__(
		    self._free_flag_conditions_for_semantic_flag_group
		)
		self._cb.getFlagsWrittenByFlagWriteType = self._cb.getFlagsWrittenByFlagWriteType.__class__(
		    self._get_flags_written_by_flag_write_type
		)
		self._cb.getSemanticClassForFlagWriteType = self._cb.getSemanticClassForFlagWriteType.__class__(
		    self._get_semantic_class_for_flag_write_type
		)
		self._cb.getFlagWriteLowLevelIL = self._cb.getFlagWriteLowLevelIL.__class__(self._get_flag_write_low_level_il)
		self._cb.getFlagConditionLowLevelIL = self._cb.getFlagConditionLowLevelIL.__class__(
		    self._get_flag_condition_low_level_il
		)
		self._cb.getSemanticFlagGroupLowLevelIL = self._cb.getSemanticFlagGroupLowLevelIL.__class__(
		    self._get_semantic_flag_group_low_level_il
		)
		self._cb.freeRegisterList = self._cb.freeRegisterList.__class__(self._free_register_list)
		self._cb.getRegisterInfo = self._cb.getRegisterInfo.__class__(self._get_register_info)
		self._cb.getStackPointerRegister = self._cb.getStackPointerRegister.__class__(self._get_stack_pointer_register)
		self._cb.getLinkRegister = self._cb.getLinkRegister.__class__(self._get_link_register)
		self._cb.getGlobalRegisters = self._cb.getGlobalRegisters.__class__(self._get_global_registers)
		self._cb.getSystemRegisters = self._cb.getSystemRegisters.__class__(self._get_system_registers)
		self._cb.getRegisterStackName = self._cb.getRegisterStackName.__class__(self._get_register_stack_name)
		self._cb.getAllRegisterStacks = self._cb.getAllRegisterStacks.__class__(self._get_all_register_stacks)
		self._cb.getRegisterStackInfo = self._cb.getRegisterStackInfo.__class__(self._get_register_stack_info)
		self._cb.getIntrinsicClass = self._cb.getIntrinsicClass.__class__(self._get_intrinsic_class)
		self._cb.getIntrinsicName = self._cb.getIntrinsicName.__class__(self._get_intrinsic_name)
		self._cb.getAllIntrinsics = self._cb.getAllIntrinsics.__class__(self._get_all_intrinsics)
		self._cb.getIntrinsicInputs = self._cb.getIntrinsicInputs.__class__(self._get_intrinsic_inputs)
		self._cb.freeNameAndTypeList = self._cb.freeNameAndTypeList.__class__(self._free_name_and_type_list)
		self._cb.getIntrinsicOutputs = self._cb.getIntrinsicOutputs.__class__(self._get_intrinsic_outputs)
		self._cb.freeTypeList = self._cb.freeTypeList.__class__(self._free_type_list)
		self._cb.canAssemble = self._cb.canAssemble.__class__(self._can_assemble)
		self._cb.assemble = self._cb.assemble.__class__(self._assemble)
		self._cb.isNeverBranchPatchAvailable = self._cb.isNeverBranchPatchAvailable.__class__(
		    self._is_never_branch_patch_available
		)
		self._cb.isAlwaysBranchPatchAvailable = self._cb.isAlwaysBranchPatchAvailable.__class__(
		    self._is_always_branch_patch_available
		)
		self._cb.isInvertBranchPatchAvailable = self._cb.isInvertBranchPatchAvailable.__class__(
		    self._is_invert_branch_patch_available
		)
		self._cb.isSkipAndReturnZeroPatchAvailable = self._cb.isSkipAndReturnZeroPatchAvailable.__class__(
		    self._is_skip_and_return_zero_patch_available
		)
		self._cb.isSkipAndReturnValuePatchAvailable = self._cb.isSkipAndReturnValuePatchAvailable.__class__(
		    self._is_skip_and_return_value_patch_available
		)
		self._cb.convertToNop = self._cb.convertToNop.__class__(self._convert_to_nop)
		self._cb.alwaysBranch = self._cb.alwaysBranch.__class__(self._always_branch)
		self._cb.invertBranch = self._cb.invertBranch.__class__(self._invert_branch)
		self._cb.skipAndReturnValue = self._cb.skipAndReturnValue.__class__(self._skip_and_return_value)

		self.__dict__['endianness'] = self.__class__.endianness
		self.__dict__['address_size'] = self.__class__.address_size
		self.__dict__['default_int_size'] = self.__class__.default_int_size
		self.__dict__['instr_alignment'] = self.__class__.instr_alignment
		self.__dict__['max_instr_length'] = self.__class__.max_instr_length
		self.__dict__['opcode_display_length'] = self.__class__.opcode_display_length
		self.__dict__['stack_pointer'] = self.__class__.stack_pointer
		self.__dict__['link_reg'] = self.__class__.link_reg

		self._all_regs: Dict[RegisterName, RegisterIndex] = {}
		self._full_width_regs: Dict[RegisterName, RegisterIndex] = {}
		self._regs_by_index: Dict[RegisterIndex, RegisterName] = {}
		self.regs = self.__class__.regs
		assert self.regs is not None, "Custom Architecture doesn't specify a register map"
		reg_index = RegisterIndex(0)

		# Registers used for storage in register stacks must be sequential, so allocate these in order first
		self._all_reg_stacks: Dict[RegisterStackName, RegisterStackIndex] = {}
		self._reg_stacks_by_index: Dict[RegisterStackIndex, RegisterStackName] = {}
		self.reg_stacks = self.__class__.reg_stacks
		assert self.regs is not None, "Custom Architecture doesn't specify a reg_stacks map"
		reg_stack_index = RegisterStackIndex(0)
		for reg_stack, info in self.reg_stacks.items():
			for reg in info.storage_regs:
				self._all_regs[reg] = reg_index
				self._regs_by_index[reg_index] = reg
				r = self.regs[reg]
				self.regs[reg] = RegisterInfo(r.full_width_reg, r.size, r.offset, r.extend, reg_index)
				reg_index = RegisterIndex(reg_index + 1)
			for reg in info.top_relative_regs:
				self._all_regs[reg] = reg_index
				self._regs_by_index[reg_index] = reg
				r = self.regs[reg]
				self.regs[reg] = RegisterInfo(r.full_width_reg, r.size, r.offset, r.extend, reg_index)
				reg_index = RegisterIndex(reg_index + 1)
			if reg_stack not in self._all_reg_stacks:
				self._all_reg_stacks[reg_stack] = reg_stack_index
				self._reg_stacks_by_index[reg_stack_index] = reg_stack
				rs = self.reg_stacks[reg_stack]
				self.reg_stacks[reg_stack] = RegisterStackInfo(
				    rs.storage_regs, rs.top_relative_regs, rs.stack_top_reg, reg_stack_index
				)
				reg_stack_index = RegisterStackIndex(reg_stack_index + 1)

		for reg, info in self.regs.items():
			if reg not in self._all_regs:
				self._all_regs[reg] = reg_index
				self._regs_by_index[reg_index] = reg
				r = self.regs[reg]
				self.regs[reg] = RegisterInfo(r.full_width_reg, r.size, r.offset, r.extend, reg_index)
				reg_index = RegisterIndex(reg_index + 1)
			if info.full_width_reg not in self._all_regs:
				self._all_regs[info.full_width_reg] = reg_index
				self._regs_by_index[reg_index] = info.full_width_reg
				r = self.regs[reg]
				self.regs[info.full_width_reg] = RegisterInfo(r.full_width_reg, r.size, r.offset, r.extend, reg_index)
				reg_index = RegisterIndex(reg_index + 1)
			if info.full_width_reg not in self._full_width_regs:
				self._full_width_regs[info.full_width_reg] = self._all_regs[info.full_width_reg]

		self._flags: Dict[FlagName, FlagIndex] = {}
		self._flags_by_index: Dict[FlagIndex, FlagName] = {}
		self.flags: List[FlagName] = self.__class__.flags
		flag_index = FlagIndex(0)
		for flag in self.__class__.flags:
			if flag not in self._flags:
				self._flags[flag] = flag_index
				self._flags_by_index[flag_index] = flag
				flag_index = FlagIndex(flag_index + 1)

		self._flag_write_types: Dict[FlagWriteTypeName, FlagWriteTypeIndex] = {}
		self._flag_write_types_by_index: Dict[FlagWriteTypeIndex, FlagWriteTypeName] = {}
		self.flag_write_types: List[FlagWriteTypeName] = self.__class__.flag_write_types
		write_type_index = FlagWriteTypeIndex(1)
		for write_type in self.__class__.flag_write_types:
			if write_type not in self._flag_write_types:
				self._flag_write_types[write_type] = write_type_index
				self._flag_write_types_by_index[write_type_index] = write_type
				write_type_index = FlagWriteTypeIndex(write_type_index + 1)

		self._semantic_flag_classes: Dict[SemanticClassName, SemanticClassIndex] = {}
		self._semantic_flag_classes_by_index: Dict[SemanticClassIndex, SemanticClassName] = {}
		self.semantic_flag_classes: List[SemanticClassName] = self.__class__.semantic_flag_classes
		semantic_class_index = SemanticClassIndex(1)
		for sem_class in self.__class__.semantic_flag_classes:
			if sem_class not in self._semantic_flag_classes:
				self._semantic_flag_classes[sem_class] = semantic_class_index
				self._semantic_flag_classes_by_index[semantic_class_index] = sem_class
				semantic_class_index = SemanticClassIndex(semantic_class_index + 1)

		self._semantic_flag_groups: Dict[SemanticGroupName, SemanticGroupIndex] = {}
		self._semantic_flag_groups_by_index: Dict[SemanticGroupIndex, SemanticGroupName] = {}
		self.semantic_flag_groups: List[SemanticGroupName] = self.__class__.semantic_flag_groups
		semantic_group_index = SemanticGroupIndex(0)
		for sem_group in self.__class__.semantic_flag_groups:
			if sem_group not in self._semantic_flag_groups:
				self._semantic_flag_groups[sem_group] = semantic_group_index
				self._semantic_flag_groups_by_index[semantic_group_index] = sem_group
				semantic_group_index = SemanticGroupIndex(semantic_group_index + 1)

		self._flag_roles: Dict[FlagIndex, FlagRole] = {}
		self.flag_roles: Dict[FlagName, FlagRole] = self.__class__.flag_roles
		for flag in self.__class__.flag_roles:
			role = self.__class__.flag_roles[flag]
			if isinstance(role, str):
				role = FlagRole[role]
			self._flag_roles[self._flags[flag]] = role

		self.flags_required_for_flag_condition: Dict['lowlevelil.LowLevelILFlagCondition',
		                                             List[FlagName]] = self.__class__.flags_required_for_flag_condition

		self._flags_required_by_semantic_flag_group: Dict[SemanticGroupIndex, List[FlagIndex]] = {}
		self.flags_required_for_semantic_flag_group: Dict[
		    SemanticGroupName, List[FlagName]] = self.__class__.flags_required_for_semantic_flag_group
		for group in self.__class__.flags_required_for_semantic_flag_group:
			flags: List[FlagIndex] = []
			for flag in self.__class__.flags_required_for_semantic_flag_group[group]:
				flags.append(self._flags[flag])
			self._flags_required_by_semantic_flag_group[self._semantic_flag_groups[group]] = flags

		self._flag_conditions_for_semantic_flag_group = {}
		self.flag_conditions_for_semantic_flag_group = self.__class__.flag_conditions_for_semantic_flag_group
		for group in self.__class__.flag_conditions_for_semantic_flag_group:
			class_cond = {}
			for sem_class in self.__class__.flag_conditions_for_semantic_flag_group[group]:
				if sem_class is None:
					class_cond[0] = self.__class__.flag_conditions_for_semantic_flag_group[group][sem_class]
				else:
					class_cond[self._semantic_flag_classes[sem_class]
					           ] = self.__class__.flag_conditions_for_semantic_flag_group[group][sem_class]
			self._flag_conditions_for_semantic_flag_group[self._semantic_flag_groups[group]] = class_cond

		self._flags_written_by_flag_write_type = {}
		self.flags_written_by_flag_write_type = self.__class__.flags_written_by_flag_write_type
		for write_type in self.__class__.flags_written_by_flag_write_type:
			flags = []
			for flag in self.__class__.flags_written_by_flag_write_type[write_type]:
				flags.append(self._flags[flag])
			self._flags_written_by_flag_write_type[self._flag_write_types[write_type]] = flags

		self._semantic_class_for_flag_write_type = {}
		self.semantic_class_for_flag_write_type = self.__class__.semantic_class_for_flag_write_type
		for write_type in self.__class__.semantic_class_for_flag_write_type:
			sem_class = self.__class__.semantic_class_for_flag_write_type[write_type]
			if sem_class in self._semantic_flag_classes:
				sem_class_index = self._semantic_flag_classes[sem_class]
			else:
				sem_class_index = 0
			self._semantic_class_for_flag_write_type[self._flag_write_types[write_type]] = sem_class_index

		self.global_regs = self.__class__.global_regs
		self.system_regs = self.__class__.system_regs

		self._intrinsics: Dict[IntrinsicName, IntrinsicIndex] = {}
		self._intrinsic_class_by_index: Dict[IntrinsicIndex, IntrinsicClass] = {}
		self._intrinsics_by_index: Dict[IntrinsicIndex, Tuple[IntrinsicName, IntrinsicInfo]] = {}
		intrinsic_index = IntrinsicIndex(0)
		for intrinsic in self.__class__.intrinsics.keys():
			if intrinsic not in self._intrinsics:
				info = self.__class__.intrinsics[intrinsic]
				for i in range(0, len(info.inputs)):
					if isinstance(info.inputs[i], types.Type):
						info.inputs[i] = IntrinsicInput(info.inputs[i])
					elif isinstance(info.inputs[i], tuple):
						info.inputs[i] = IntrinsicInput(info.inputs[i][0], info.inputs[i][1])

				info = IntrinsicInfo(info.inputs, info.outputs, intrinsic_index)
				self._intrinsics[intrinsic] = intrinsic_index
				self._intrinsics_by_index[intrinsic_index] = (intrinsic, info)
				intrinsic_index = IntrinsicIndex(intrinsic_index + 1)
				self.intrinsics[intrinsic] = info

		self._pending_reg_lists = {}
		self._pending_token_lists = {}
		self._pending_condition_lists = {}
		self._pending_name_and_type_lists = {}
		self._pending_type_lists = {}

	def __repr__(self):
		return f"<arch: {self.name}>"

	def __eq__(self, other):
		if not isinstance(other, self.__class__):
			return NotImplemented
		return ctypes.addressof(self.handle.contents) == ctypes.addressof(other.handle.contents)

	def __ne__(self, other):
		if not isinstance(other, self.__class__):
			return NotImplemented
		return not (self == other)

	def __hash__(self):
		return hash(ctypes.addressof(self.handle.contents))

	def __str__(self):
		return self.name

	@classmethod
	def register(cls) -> 'Architecture':
		binaryninja._init_plugins()
		if cls.name is None:
			raise ValueError("architecture 'name' is not defined")
		arch = cls()
		cls._registered_cb = arch._cb
		arch.handle = core.BNRegisterArchitecture(cls.name, arch._cb)
		return arch

	@property
	def full_width_regs(self) -> List[RegisterName]:
		"""List of full width register strings (read-only)"""
		count = ctypes.c_ulonglong()
		regs = core.BNGetFullWidthArchitectureRegisters(self.handle, count)
		assert regs is not None, "core.BNGetFullWidthArchitectureRegisters returned None"
		result: List[RegisterName] = []
		try:
			for i in range(0, count.value):
				result.append(RegisterName(core.BNGetArchitectureRegisterName(self.handle, regs[i])))
		finally:
			core.BNFreeRegisterList(regs)
		return result

	@property
	def calling_conventions(self) -> Mapping[str, 'callingconvention.CallingConvention']:
		"""Dict of CallingConvention objects (read-only)"""
		count = ctypes.c_ulonglong()
		cc = core.BNGetArchitectureCallingConventions(self.handle, count)
		assert cc is not None, "core.BNGetArchitectureCallingConventions returned None"
		result = {}
		try:
			for i in range(0, count.value):
				obj = callingconvention.CallingConvention(handle=core.BNNewCallingConventionReference(cc[i]))
				result[obj.name] = obj
		finally:
			core.BNFreeCallingConventionList(cc, count.value)
		return result

	@property
	def standalone_platform(self) -> 'platform.Platform':
		"""Architecture standalone platform (read-only)"""
		pl = core.BNGetArchitectureStandalonePlatform(self.handle)
		return platform.CorePlatform._from_cache(pl)

	@property
	def type_libraries(self) -> List['typelibrary.TypeLibrary']:
		"""Architecture type libraries"""
		count = ctypes.c_ulonglong(0)
		result = []
		handles = core.BNGetArchitectureTypeLibraries(self.handle, count)
		assert handles is not None, "core.BNGetArchitectureTypeLibraries returned None"
		for i in range(0, count.value):
			result.append(typelibrary.TypeLibrary(core.BNNewTypeLibraryReference(handles[i])))
		core.BNFreeTypeLibraryList(handles, count.value)
		return result

	@property
	def can_assemble(self) -> bool:
		"""returns if the architecture can assemble instructions (read-only)"""
		return core.BNCanArchitectureAssemble(self.handle)

	def _init(self, ctxt, handle):
		self.handle = handle

	def _get_endianness(self, ctxt):
		try:
			return self.endianness
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_endianness")
			return Endianness.LittleEndian

	def _get_address_size(self, ctxt):
		try:
			return self.address_size
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_address_size")
			return 8

	def _get_default_integer_size(self, ctxt):
		try:
			return self.default_int_size
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_default_integer_size")
			return 4

	def _get_instruction_alignment(self, ctxt):
		try:
			return self.instr_alignment
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_instruction_alignment")
			return 1

	def _get_max_instruction_length(self, ctxt):
		try:
			return self.max_instr_length
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_max_instruction_length")
			return 16

	def _get_opcode_display_length(self, ctxt):
		try:
			return self.opcode_display_length
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_opcode_display_length")
			return 8

	def _get_associated_arch_by_address(self, ctxt, addr):
		try:
			result, new_addr = self.get_associated_arch_by_address(addr[0])
			addr[0] = new_addr
			return ctypes.cast(result.handle, ctypes.c_void_p).value
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_associated_arch_by_address")
			return ctypes.cast(self.handle, ctypes.c_void_p).value

	def _get_instruction_info(self, ctxt, data, addr, max_len, result):
		try:
			buf = ctypes.create_string_buffer(max_len)
			ctypes.memmove(buf, data, max_len)
			info = self.get_instruction_info(buf.raw, addr)
			if info is None:
				return False
			result[0].length = info.length
			result[0].archTransitionByTargetAddr = info.arch_transition_by_target_addr
			result[0].delaySlots = info.branch_delay
			result[0].branchCount = len(info.branches)
			for i in range(0, len(info.branches)):
				if isinstance(info.branches[i].type, str):
					result[0].branchType[i] = BranchType[info.branches[i].type.name]
				else:
					result[0].branchType[i] = info.branches[i].type
				result[0].branchTarget[i] = info.branches[i].target
				arch = info.branches[i].arch
				if arch is None:
					result[0].branchArch[i] = None
				else:
					result[0].branchArch[i] = arch.handle
			return True
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_instruction_info")
			return False

	def _get_instruction_text(self, ctxt, data, addr, length, result, count):
		try:
			buf = ctypes.create_string_buffer(length[0])
			ctypes.memmove(buf, data, length[0])
			info = self.get_instruction_text(buf.raw, addr)
			if info is None:
				return False
			tokens = info[0]
			length[0] = info[1]
			count[0] = len(tokens)
			token_buf = function.InstructionTextToken._get_core_struct(tokens)
			result[0] = token_buf
			ptr = ctypes.cast(token_buf, ctypes.c_void_p)
			self._pending_token_lists[ptr.value] = (ptr.value, token_buf)
			return True
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_instruction_text")
			return False

	def _get_instruction_text_with_context(self, ctxt, data, addr, length, context_token, result, count):
		try:
			buf = ctypes.create_string_buffer(length[0])
			ctypes.memmove(buf, data, length[0])
			context = self.function_arch_contexts.get(context_token, None)
			info = self.get_instruction_text_with_context(buf.raw, addr, context)
			if info is None:
				return False
			tokens = info[0]
			length[0] = info[1]
			count[0] = len(tokens)
			token_buf = function.InstructionTextToken._get_core_struct(tokens)
			result[0] = token_buf
			ptr = ctypes.cast(token_buf, ctypes.c_void_p)
			self._pending_token_lists[ptr.value] = (ptr.value, token_buf)
			return True
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_instruction_text_with_context")
			return False

	def _free_instruction_text(self, tokens, count):
		try:
			buf = ctypes.cast(tokens, ctypes.c_void_p)
			if buf.value not in self._pending_token_lists:
				raise ValueError("freeing token list that wasn't allocated")
			del self._pending_token_lists[buf.value]
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._free_instruction_text")

	def _get_instruction_low_level_il(self, ctxt, data, addr, length, il):
		try:
			buf = ctypes.create_string_buffer(length[0])
			ctypes.memmove(buf, data, length[0])
			result = self.get_instruction_low_level_il(
			    buf.raw, addr, lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il))
			)
			if result is None:
				return False
			length[0] = result
			return True
		except OSError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_instruction_low_level_il")
			return False

	def _analyze_basic_blocks(self, ctx, func, ptr_bn_bb_context):
		try:
			bn_bb_context = ptr_bn_bb_context.contents
			context = BasicBlockAnalysisContext.from_core_struct(bn_bb_context)
			self.analyze_basic_blocks(function.Function(handle=core.BNNewFunctionReference(func)), context)
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._analyze_basic_blocks")

	def _lift_function(self, ctx, func, ptr_bn_fl_context):
		try:
			bn_fl_context = ptr_bn_fl_context.contents
			context = FunctionLifterContext.from_core_struct(func, bn_fl_context)
			return self.lift_function(lowlevelil.LowLevelILFunction(arch=self, handle=core.BNNewLowLevelILFunctionReference(func)), context)
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._lift_function")
			return False

	def _free_function_arch_context(self, ctx, context_token):
		try:
			self.function_arch_contexts.pop(context_token, None)
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._free_function_arch_context")

	def _get_register_name(self, ctxt, reg):
		try:
			if reg in self._regs_by_index:
				return core.BNAllocString(self._regs_by_index[reg])
			return core.BNAllocString("")
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_register_name")
			return core.BNAllocString("")

	def _get_flag_name(self, ctxt, flag):
		try:
			if flag in self._flags_by_index:
				return core.BNAllocString(self._flags_by_index[flag])
			return core.BNAllocString("")
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_flag_name")
			return core.BNAllocString("")

	def _get_flag_write_type_name(self, ctxt, write_type: FlagWriteTypeIndex):
		try:
			if write_type in self._flag_write_types_by_index:
				return core.BNAllocString(self._flag_write_types_by_index[write_type])
			return core.BNAllocString("")
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_flag_write_type_name")
			return core.BNAllocString("")

	def _get_semantic_flag_class_name(self, ctxt, sem_class):
		try:
			if sem_class in self._semantic_flag_classes_by_index:
				return core.BNAllocString(self._semantic_flag_classes_by_index[sem_class])
			return core.BNAllocString("")
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_semantic_flag_class_name")
			return core.BNAllocString("")

	def _get_semantic_flag_group_name(self, ctxt, sem_group):
		try:
			if sem_group in self._semantic_flag_groups_by_index:
				return core.BNAllocString(self._semantic_flag_groups_by_index[sem_group])
			return core.BNAllocString("")
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_semantic_flag_group_name")
			return core.BNAllocString("")

	def _get_full_width_registers(self, ctxt, count):
		try:
			regs = list(self._full_width_regs.values())
			count[0] = len(regs)
			reg_buf = (ctypes.c_uint * len(regs))()
			for i in range(0, len(regs)):
				reg_buf[i] = regs[i]
			result = ctypes.cast(reg_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, reg_buf)
			return result.value
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_full_width_registers")
			count[0] = 0
			return None

	def _get_all_registers(self, ctxt, count):
		try:
			regs = list(self._regs_by_index.keys())
			count[0] = len(regs)
			reg_buf = (ctypes.c_uint * len(regs))()
			for i in range(0, len(regs)):
				reg_buf[i] = regs[i]
			result = ctypes.cast(reg_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, reg_buf)
			return result.value
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_all_registers")
			count[0] = 0
			return None

	def _get_all_flags(self, ctxt, count):
		try:
			flags = list(self._flags_by_index.keys())
			count[0] = len(flags)
			flag_buf = (ctypes.c_uint * len(flags))()
			for i in range(0, len(flags)):
				flag_buf[i] = flags[i]
			result = ctypes.cast(flag_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, flag_buf)
			return result.value
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_all_flags")
			count[0] = 0
			return None

	def _get_all_flag_write_types(self, ctxt, count):
		try:
			write_types = list(self._flag_write_types_by_index.keys())
			count[0] = len(write_types)
			type_buf = (ctypes.c_uint * len(write_types))()
			for i in range(0, len(write_types)):
				type_buf[i] = write_types[i]
			result = ctypes.cast(type_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, type_buf)
			return result.value
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_all_flag_write_types")
			count[0] = 0
			return None

	def _get_all_semantic_flag_classes(self, ctxt, count):
		try:
			sem_classes = list(self._semantic_flag_classes_by_index.keys())
			count[0] = len(sem_classes)
			class_buf = (ctypes.c_uint * len(sem_classes))()
			for i in range(0, len(sem_classes)):
				class_buf[i] = sem_classes[i]
			result = ctypes.cast(class_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, class_buf)
			return result.value
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_all_semantic_flag_classes")
			count[0] = 0
			return None

	def _get_all_semantic_flag_groups(self, ctxt, count):
		try:
			sem_groups = list(self._semantic_flag_groups_by_index.keys())
			count[0] = len(sem_groups)
			group_buf = (ctypes.c_uint * len(sem_groups))()
			for i in range(0, len(sem_groups)):
				group_buf[i] = sem_groups[i]
			result = ctypes.cast(group_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, group_buf)
			return result.value
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_all_semantic_flag_groups")
			count[0] = 0
			return None

	def _get_flag_role(self, ctxt, flag: FlagIndex, sem_class: Optional[SemanticClassName] = None):
		if sem_class in self._semantic_flag_classes:
			assert sem_class is not None
			_sem_class = self._semantic_flag_classes[sem_class]
		else:
			_sem_class = None
		return self.get_flag_role(flag, _sem_class)

	def _get_flags_required_for_flag_condition(self, ctxt, cond, sem_class, count):
		try:
			if sem_class in self._semantic_flag_classes_by_index:
				sem_class = self._semantic_flag_classes_by_index[sem_class]
			else:
				sem_class = None
			flag_names = self.get_flags_required_for_flag_condition(cond, sem_class)
			flags = []
			for name in flag_names:
				flags.append(self._flags[name])
			count[0] = len(flags)
			flag_buf = (ctypes.c_uint * len(flags))()
			for i in range(0, len(flags)):
				flag_buf[i] = flags[i]
			result = ctypes.cast(flag_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, flag_buf)
			return result.value
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_flags_required_for_flag_condition")
			count[0] = 0
			return None

	def _get_flags_required_for_semantic_flag_group(self, ctxt, sem_group, count):
		try:
			if sem_group in self._flags_required_by_semantic_flag_group:
				flags = self._flags_required_by_semantic_flag_group[sem_group]
			else:
				flags = []
			count[0] = len(flags)
			flag_buf = (ctypes.c_uint * len(flags))()
			for i in range(0, len(flags)):
				flag_buf[i] = flags[i]
			result = ctypes.cast(flag_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, flag_buf)
			return result.value
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_flags_required_for_semantic_flag_group")
			count[0] = 0
			return None

	def _get_flag_conditions_for_semantic_flag_group(self, ctxt, sem_group, count):
		try:
			if sem_group in self._flag_conditions_for_semantic_flag_group:
				class_cond = self._flag_conditions_for_semantic_flag_group[sem_group]
			else:
				class_cond = {}
			count[0] = len(class_cond)
			cond_buf = (core.BNFlagConditionForSemanticClass * len(class_cond))()
			i = 0
			for class_index in class_cond.keys():
				cond_buf[i].semanticClass = class_index
				cond_buf[i].condition = class_cond[class_index]
				i += 1
			result = ctypes.cast(cond_buf, ctypes.c_void_p)
			self._pending_condition_lists[result.value] = (result, cond_buf)
			return result.value
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_flag_conditions_for_semantic_flag_group")
			count[0] = 0
			return None

	def _free_flag_conditions_for_semantic_flag_group(self, ctxt, conditions, count):
		try:
			buf = ctypes.cast(conditions, ctypes.c_void_p)
			if buf.value not in self._pending_condition_lists:
				raise ValueError("freeing condition list that wasn't allocated")
			del self._pending_condition_lists[buf.value]
		except (ValueError, KeyError):
			log_error_for_exception("Unhandled Python exception in Architecture._free_flag_conditions_for_semantic_flag_group")

	def _get_flags_written_by_flag_write_type(self, ctxt, write_type, count):
		try:
			if write_type in self._flags_written_by_flag_write_type:
				flags = self._flags_written_by_flag_write_type[write_type]
			else:
				flags = []
			count[0] = len(flags)
			flag_buf = (ctypes.c_uint * len(flags))()
			for i in range(0, len(flags)):
				flag_buf[i] = flags[i]
			result = ctypes.cast(flag_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, flag_buf)
			return result.value
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_flags_written_by_flag_write_type")
			count[0] = 0
			return None

	def _get_semantic_class_for_flag_write_type(self, ctxt, write_type):
		try:
			if write_type in self._semantic_class_for_flag_write_type:
				return self._semantic_class_for_flag_write_type[write_type]
			else:
				return 0
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_semantic_class_for_flag_write_type")
			return 0

	def _get_flag_write_low_level_il(self, ctxt, op, size, write_type, flag, operands, operand_count, il):
		try:
			write_type_name = None
			if write_type != 0:
				write_type_name = self._flag_write_types_by_index[write_type]
			flag_name = self._flags_by_index[flag]
			operand_list = []
			for i in range(operand_count):
				if operand_count == 3 and i == 2 and not operands[i].constant and (
						op == LowLevelILOperation.LLIL_ADC
						or op == LowLevelILOperation.LLIL_SBB
						or op == LowLevelILOperation.LLIL_RLC
						or op == LowLevelILOperation.LLIL_RRC):
					operand_list.append(lowlevelil.ILFlag(self, operands[i].reg))
				elif operands[i].constant:
					operand_list.append(operands[i].value)
				elif lowlevelil.LLIL_REG_IS_TEMP(operands[i].reg):
					operand_list.append(lowlevelil.ILRegister(self, operands[i].reg))
				else:
					operand_list.append(lowlevelil.ILRegister(self, operands[i].reg))
			return self.get_flag_write_low_level_il(
			    op, size, write_type_name, flag_name, operand_list,
			    lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il))
			)
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_flag_write_low_level_il")
			return False

	def _get_flag_condition_low_level_il(self, ctxt, cond, sem_class, il):
		try:
			if sem_class in self._semantic_flag_classes_by_index:
				sem_class_name = self._semantic_flag_classes_by_index[sem_class]
			else:
				sem_class_name = None
			return self.get_flag_condition_low_level_il(
			    cond, sem_class_name, lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il))
			)
		except OSError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_flag_condition_low_level_il")
			return 0

	def _get_semantic_flag_group_low_level_il(self, ctxt, sem_group, il):
		try:
			if sem_group in self._semantic_flag_groups_by_index:
				sem_group_name = self._semantic_flag_groups_by_index[sem_group]
			else:
				sem_group_name = None
			return self.get_semantic_flag_group_low_level_il(
			    sem_group_name, lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il))
			)
		except OSError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_semantic_flag_group_low_level_il")
			return 0

	def _free_register_list(self, ctxt, regs, count):
		try:
			buf = ctypes.cast(regs, ctypes.c_void_p)
			if buf.value not in self._pending_reg_lists:
				raise ValueError("freeing register list that wasn't allocated")
			del self._pending_reg_lists[buf.value]
		except (ValueError, KeyError):
			log_error_for_exception("Unhandled Python exception in Architecture._free_register_list")

	def _get_register_info(self, ctxt, reg, result):
		try:
			if reg not in self._regs_by_index:
				result[0].fullWidthRegister = 0
				result[0].offset = 0
				result[0].size = 0
				result[0].extend = ImplicitRegisterExtend.NoExtend
				return
			info = self.regs[self._regs_by_index[reg]]
			result[0].fullWidthRegister = self._all_regs[info.full_width_reg]
			result[0].offset = info.offset
			result[0].size = info.size
			if isinstance(info.extend, str):
				result[0].extend = ImplicitRegisterExtend[info.extend]
			else:
				result[0].extend = info.extend
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_register_info")
			result[0].fullWidthRegister = 0
			result[0].offset = 0
			result[0].size = 0
			result[0].extend = ImplicitRegisterExtend.NoExtend

	def _get_stack_pointer_register(self, ctxt):
		if self.stack_pointer is None:
			return 0
		try:
			return self._all_regs[self.stack_pointer]
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_stack_pointer_register")
			return 0

	def _get_link_register(self, ctxt):
		try:
			if self.link_reg is None:
				return 0xffffffff
			return self._all_regs[self.link_reg]
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_link_register")
			return 0

	def _get_global_registers(self, ctxt, count):
		try:
			count[0] = len(self.global_regs)
			reg_buf = (ctypes.c_uint * len(self.global_regs))()
			for i in range(0, len(self.global_regs)):
				reg_buf[i] = self._all_regs[self.global_regs[i]]
			result = ctypes.cast(reg_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, reg_buf)
			return result.value
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_global_registers")
			count[0] = 0
			return None

	def _get_system_registers(self, ctxt, count):
		try:
			count[0] = len(self.system_regs)
			reg_buf = (ctypes.c_uint * len(self.system_regs))()
			for i in range(0, len(self.system_regs)):
				reg_buf[i] = self._all_regs[self.system_regs[i]]
			result = ctypes.cast(reg_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, reg_buf)
			return result.value
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_system_registers")
			count[0] = 0
			return None

	def _get_register_stack_name(self, ctxt, reg_stack):
		try:
			if reg_stack in self._reg_stacks_by_index:
				return core.BNAllocString(self._reg_stacks_by_index[reg_stack])
			return core.BNAllocString("")
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_register_stack_name")
			return core.BNAllocString("")

	def _get_all_register_stacks(self, ctxt, count):
		try:
			regs = list(self._reg_stacks_by_index.keys())
			count[0] = len(regs)
			reg_buf = (ctypes.c_uint * len(regs))()
			for i in range(0, len(regs)):
				reg_buf[i] = regs[i]
			result = ctypes.cast(reg_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, reg_buf)
			return result.value
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_all_register_stacks")
			count[0] = 0
			return None

	def _get_register_stack_info(self, ctxt, reg_stack, result):
		try:
			if reg_stack not in self._reg_stacks_by_index:
				result[0].firstStorageReg = 0
				result[0].firstTopRelativeReg = 0
				result[0].storageCount = 0
				result[0].topRelativeCount = 0
				result[0].stackTopReg = 0
				return
			info = self.reg_stacks[self._reg_stacks_by_index[reg_stack]]
			result[0].firstStorageReg = self._all_regs[info.storage_regs[0]]
			result[0].storageCount = len(info.storage_regs)
			if len(info.top_relative_regs) > 0:
				result[0].firstTopRelativeReg = self._all_regs[info.top_relative_regs[0]]
				result[0].topRelativeCount = len(info.top_relative_regs)
			else:
				result[0].firstTopRelativeReg = 0
				result[0].topRelativeCount = 0
			result[0].stackTopReg = self._all_regs[info.stack_top_reg]
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_register_stack_info")
			result[0].firstStorageReg = 0
			result[0].firstTopRelativeReg = 0
			result[0].storageCount = 0
			result[0].topRelativeCount = 0
			result[0].stackTopReg = 0

	def _get_intrinsic_class(self, ctxt, intrinsic):
		if intrinsic in self._intrinsic_class_by_index:
			return self._intrinsic_class_by_index[intrinsic]
		return IntrinsicClass.GeneralIntrinsicClass

	def _get_intrinsic_name(self, ctxt, intrinsic):
		try:
			if intrinsic in self._intrinsics_by_index:
				return core.BNAllocString(self._intrinsics_by_index[intrinsic][0])
			return core.BNAllocString("")
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_intrinsic_name")
			return core.BNAllocString("")

	def _get_all_intrinsics(self, ctxt, count):
		try:
			regs = list(self._intrinsics_by_index.keys())
			count[0] = len(regs)
			reg_buf = (ctypes.c_uint * len(regs))()
			for i in range(0, len(regs)):
				reg_buf[i] = regs[i]
			result = ctypes.cast(reg_buf, ctypes.c_void_p)
			self._pending_reg_lists[result.value] = (result, reg_buf)
			return result.value
		except KeyError:
			log_error_for_exception("Unhandled Python exception in Architecture._get_all_intrinsics")
			count[0] = 0
			return None

	def _get_intrinsic_inputs(self, ctxt, intrinsic, count):
		try:
			if intrinsic in self._intrinsics_by_index:
				inputs = self._intrinsics_by_index[intrinsic][1].inputs
				count[0] = len(inputs)
				input_buf = (core.BNNameAndType * len(inputs))()
				for i in range(0, len(inputs)):
					input_buf[i].name = inputs[i].name
					input_buf[i].type = core.BNNewTypeReference(inputs[i].type.handle)
					input_buf[i].typeConfidence = inputs[i].type.confidence
				result = ctypes.cast(input_buf, ctypes.c_void_p)
				self._pending_name_and_type_lists[result.value] = (result, input_buf, len(inputs))
				return result.value
			count[0] = 0
			return None
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_intrinsic_inputs")
			count[0] = 0
			return None

	def _free_name_and_type_list(self, ctxt, buf_raw, length):
		try:
			buf = ctypes.cast(buf_raw, ctypes.c_void_p)
			if buf.value not in self._pending_name_and_type_lists:
				raise ValueError("freeing name and type list that wasn't allocated")
			name_and_types = self._pending_name_and_type_lists[buf.value][1]
			count = self._pending_name_and_type_lists[buf.value][2]
			for i in range(0, count):
				core.BNFreeType(name_and_types[i].type)
			del self._pending_name_and_type_lists[buf.value]
		except (ValueError, KeyError):
			log_error_for_exception("Unhandled Python exception in Architecture._free_name_and_type_list")

	def _get_intrinsic_outputs(self, ctxt, intrinsic, count):
		try:
			if intrinsic in self._intrinsics_by_index:
				outputs = self._intrinsics_by_index[intrinsic][1].outputs
				count[0] = len(outputs)
				output_buf = (core.BNTypeWithConfidence * len(outputs))()
				for i in range(0, len(outputs)):
					output_buf[i].type = core.BNNewTypeReference(outputs[i].handle)
					output_buf[i].confidence = outputs[i].confidence
				result = ctypes.cast(output_buf, ctypes.c_void_p)
				self._pending_type_lists[result.value] = (result, output_buf, len(outputs))
				return result.value
			count[0] = 0
			return None
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._get_intrinsic_outputs")
			count[0] = 0
			return None

	def _free_type_list(self, ctxt, buf_raw, length):
		try:
			buf = ctypes.cast(buf_raw, ctypes.c_void_p)
			if buf.value not in self._pending_type_lists:
				raise ValueError("freeing type list that wasn't allocated")
			_types = self._pending_type_lists[buf.value][1]
			count = self._pending_type_lists[buf.value][2]
			for i in range(0, count):
				core.BNFreeType(_types[i].type)
			del self._pending_type_lists[buf.value]
		except (ValueError, KeyError):
			log_error_for_exception("Unhandled Python exception in Architecture._free_type_list")

	def _can_assemble(self, ctxt):
		try:
			return self.can_assemble
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._can_assemble")
			return False

	def _assemble(self, ctxt, code, addr, result, errors):
		"""
		This function calls the `assemble` command for the actual architecture plugin.
		If the plugin does not provide an `assemble(self, code, addr)`-style function,
		it uses the default function provided in CoreArchitecture.
		"""
		try:
			data = self.assemble(core.pyNativeStr(code), addr)
			if data is None:
				return False
			buf = ctypes.create_string_buffer(len(data))
			ctypes.memmove(buf, data, len(data))
			core.BNSetDataBufferContents(result, buf, len(data))
			return True
		except ValueError as e:  # Overridden `assemble` functions should raise a ValueError if the input was invalid (with a reasonable error message)
			log_debug_for_exception("Assemble failed")
			errors[0] = core.BNAllocString(str(e))
			return False
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._assemble")
			errors[0] = core.BNAllocString("Unhandled exception during assembly.\n")
			return False

	def _is_never_branch_patch_available(self, ctxt, data, addr, length):
		try:
			buf = ctypes.create_string_buffer(length)
			ctypes.memmove(buf, data, length)
			return self.is_never_branch_patch_available(buf.raw, addr)
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._is_never_branch_patch_available")
			return False

	def _is_always_branch_patch_available(self, ctxt, data, addr, length):
		try:
			buf = ctypes.create_string_buffer(length)
			ctypes.memmove(buf, data, length)
			return self.is_always_branch_patch_available(buf.raw, addr)
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._is_always_branch_patch_available")
			return False

	def _is_invert_branch_patch_available(self, ctxt, data, addr, length):
		try:
			buf = ctypes.create_string_buffer(length)
			ctypes.memmove(buf, data, length)
			return self.is_invert_branch_patch_available(buf.raw, addr)
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._is_invert_branch_patch_available")
			return False

	def _is_skip_and_return_zero_patch_available(self, ctxt, data, addr, length):
		try:
			buf = ctypes.create_string_buffer(length)
			ctypes.memmove(buf, data, length)
			return self.is_skip_and_return_zero_patch_available(buf.raw, addr)
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._is_skip_and_return_zero_patch_available")
			return False

	def _is_skip_and_return_value_patch_available(self, ctxt, data, addr, length):
		try:
			buf = ctypes.create_string_buffer(length)
			ctypes.memmove(buf, data, length)
			return self.is_skip_and_return_value_patch_available(buf.raw, addr)
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._is_skip_and_return_value_patch_available")
			return False

	def _convert_to_nop(self, ctxt, data, addr, length):
		try:
			buf = ctypes.create_string_buffer(length)
			ctypes.memmove(buf, data, length)
			result = self.convert_to_nop(buf.raw, addr)
			if result is None:
				return False
			if len(result) > length:
				result = result[0:length]
			ctypes.memmove(data, result, len(result))
			return True
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._convert_to_nop")
			return False

	def _always_branch(self, ctxt, data, addr, length):
		try:
			buf = ctypes.create_string_buffer(length)
			ctypes.memmove(buf, data, length)
			result = self.always_branch(buf.raw, addr)
			if result is None:
				return False
			if len(result) > length:
				result = result[0:length]
			ctypes.memmove(data, result, len(result))
			return True
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._always_branch")
			return False

	def _invert_branch(self, ctxt, data, addr, length):
		try:
			buf = ctypes.create_string_buffer(length)
			ctypes.memmove(buf, data, length)
			result = self.invert_branch(buf.raw, addr)
			if result is None:
				return False
			if len(result) > length:
				result = result[0:length]
			ctypes.memmove(data, result, len(result))
			return True
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._invert_branch")
			return False

	def _skip_and_return_value(self, ctxt, data, addr, length, value):
		try:
			buf = ctypes.create_string_buffer(length)
			ctypes.memmove(buf, data, length)
			result = self.skip_and_return_value(buf.raw, addr, value)
			if result is None:
				return False
			if len(result) > length:
				result = result[0:length]
			ctypes.memmove(data, result, len(result))
			return True
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture._skip_and_return_value")
			return False

	def get_associated_arch_by_address(self, addr: int) -> Tuple['Architecture', int]:
		return self, addr

	def get_instruction_info(self, data: bytes, addr: int) -> Optional[InstructionInfo]:
		"""
		``get_instruction_info`` returns an InstructionInfo object for the instruction at the given virtual address
		``addr`` with data ``data``.

		.. note:: Architecture subclasses should implement this method.

		.. note:: The instruction info object should always set the InstructionInfo.length to the instruction length, \
		and the branches of the proper types should be added if the instruction is a branch.

		If the instruction is a branch instruction architecture plugins should add a branch of the proper type:

			===================== ===================================================
			BranchType            Description
			===================== ===================================================
			UnconditionalBranch   Branch will always be taken
			FalseBranch           False branch condition
			TrueBranch            True branch condition
			CallDestination       Branch is a call instruction (Branch with Link)
			FunctionReturn        Branch returns from a function
			SystemCall            System call instruction
			IndirectBranch        Branch destination is a memory address or register
			UnresolvedBranch      Branch destination is an unknown address
			===================== ===================================================

		:param str data: a maximum of max_instruction_length bytes from the binary at virtual address ``addr``
		:param int addr: virtual address of bytes in ``data``
		:return: the InstructionInfo for the current instruction
		:rtype: InstructionInfo
		"""
		raise NotImplementedError

	def get_instruction_text(self, data: bytes, addr: int) -> Optional[Tuple[List['function.InstructionTextToken'], int]]:
		"""
		``get_instruction_text`` returns a tuple containing a list of decoded InstructionTextToken objects and the bytes used at the given virtual
		address ``addr`` with data ``data``.

		.. note:: Architecture subclasses should implement this method.

		:param str data: a maximum of max_instruction_length bytes from the binary at virtual address ``addr``
		:param int addr: virtual address of bytes in ``data``
		:return: a tuple containing the InstructionTextToken list and length of bytes decoded
		:rtype: tuple(list(InstructionTextToken), int)
		"""
		raise NotImplementedError

	def get_instruction_text_with_context(self, data: bytes, addr: int, context: Any) -> Optional[Tuple[List['function.InstructionTextToken'], int]]:
		"""
		``get_instruction_text`` returns a tuple containing a list of decoded InstructionTextToken objects and the bytes used at the given virtual
		address ``addr`` with data ``data``.

		.. note:: Architecture subclasses should implement this method if they require context from analyze_basic_blocks for instruction decoding.

		:param str data: a maximum of max_instruction_length bytes from the binary at virtual address ``addr``
		:param int addr: virtual address of bytes in ``data``
		:param Any context: function architecture context
		:return: a tuple containing the InstructionTextToken list and length of bytes decoded
		"""
		return self.get_instruction_text(data, addr)

	def get_instruction_low_level_il_instruction(
	    self, bv: 'binaryview.BinaryView', addr: int
	) -> 'lowlevelil.LowLevelILInstruction':
		il = lowlevelil.LowLevelILFunction(self)
		data = bv.read(addr, self.max_instr_length)
		self.get_instruction_low_level_il(data, addr, il)
		return il[0]

	def get_instruction_low_level_il(self, data: bytes, addr: int, il: lowlevelil.LowLevelILFunction) -> Optional[int]:
		"""
		``get_instruction_low_level_il`` appends lowlevelil.ExpressionIndex objects to ``il`` for the instruction at the given
		virtual address ``addr`` with data ``data``.

		This is used to analyze arbitrary data at an address, if you are working with an existing binary, you likely
		want to be using :func:`Function.get_low_level_il_at`.

		.. note:: Architecture subclasses should implement this method.

		:param str data: a maximum of max_instruction_length bytes from the binary at virtual address ``addr``
		:param int addr: virtual address of bytes in ``data``
		:param LowLevelILFunction il: The function the current instruction belongs to
		:return: the length of the current instruction
		:rtype: int
		"""
		raise NotImplementedError

	def analyze_basic_blocks(self, func: 'function.Function', context: BasicBlockAnalysisContext) -> None:
		"""
		``analyze_basic_blocks`` performs basic block recovery and commits the results to the function analysis

		.. note:: Architecture subclasses should only implement this method if function-level analysis is required

		:param Function func: the function to analyze
		:param BasicBlockAnalysisContext context: the analysis context
		"""

		try:
			core.BNArchitectureDefaultAnalyzeBasicBlocks(func.handle, context._handle)
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture.analyze_basic_blocks")

	def lift_function(self, func: "lowlevelil.LowLevelILFunction", context: FunctionLifterContext) -> bool:
		"""
		``lift_function`` performs lifting of the function and commits the results to the function analysis

		.. note:: Architecture subclasses should only implement this method if function-level analysis is required

		:param LowLevelILFunction func: the function to analyze
		:param FunctionLifterContext context: the lifting context
		:return: True on success, False otherwise
		"""

		try:
			return core.BNArchitectureDefaultLiftFunction(func.handle, context._handle)
		except Exception:
			log_error_for_exception("Unhandled Python exception in Architecture.lift_function")
			return False

	def get_low_level_il_from_bytes(self, data: bytes, addr: int) -> 'lowlevelil.LowLevelILInstruction':
		"""
		``get_low_level_il_from_bytes`` converts the instruction in bytes to ``il`` at the given virtual address

		:param str data: the bytes of the instruction
		:param int addr: virtual address of bytes in ``data``
		:return: a list of low level il instructions
		:rtype: LowLevelILInstruction
		:Example:

			>>> list(arch.get_low_level_il_from_bytes(b'\\xeb\\xfe', 0x40DEAD))
			<il: jump(0x40dead)>
			>>>
		"""
		func = lowlevelil.LowLevelILFunction(self)
		self.get_instruction_low_level_il(data, addr, func)
		return func[0]

	def get_reg_name(self, reg: RegisterIndex) -> RegisterName:
		"""
		``get_reg_name`` gets a register name from a register index.

		:param RegisterIndex reg: register index
		:return: the corresponding register name
		:rtype: RegisterName
		"""
		return RegisterName(core.BNGetArchitectureRegisterName(self.handle, reg))

	def get_reg_stack_name(self, reg_stack: RegisterStackIndex) -> RegisterStackName:
		"""
		``get_reg_stack_name`` gets a register stack name from a register stack number.

		:param int reg_stack: register stack number
		:return: the corresponding register string
		:rtype: RegisterStackName
		"""
		return RegisterStackName(core.BNGetArchitectureRegisterStackName(self.handle, reg_stack))

	def get_reg_stack_for_reg(self, reg: RegisterName) -> Optional[RegisterStackName]:
		_reg = self.get_reg_index(reg)
		result = core.BNGetArchitectureRegisterStackForRegister(self.handle, _reg)
		if result == 0xffffffff:
			return None
		return self.get_reg_stack_name(RegisterStackIndex(result))

	def get_flag_name(self, flag: FlagIndex) -> FlagName:
		"""
		``get_flag_name`` gets a flag name from a flag index.

		:param int flag: flag index
		:return: the corresponding flag name string
		:rtype: FlagName
		"""
		return FlagName(core.BNGetArchitectureFlagName(self.handle, flag))

	def get_reg_index(self, reg: RegisterType) -> RegisterIndex:
		if isinstance(reg, str):
			try:
				index = self.regs[reg].index
				assert index is not None
				return index
			except KeyError:
				log_error_for_exception(f"Failed to map string {reg} to register index")
		elif isinstance(reg, lowlevelil.ILRegister):
			return reg.index
		elif isinstance(reg, int):
			return RegisterIndex(reg)
		raise Exception("Attempting to get register index of non-existant register")

	def get_reg_stack_index(self, reg_stack: RegisterStackType) -> RegisterStackIndex:
		if isinstance(reg_stack, str):
			reg_stack_info = self.reg_stacks[reg_stack]
			if reg_stack_info is not None and reg_stack_info.index is not None:
				return reg_stack_info.index
		elif isinstance(reg_stack, lowlevelil.ILRegisterStack):
			return reg_stack.index
		elif isinstance(reg_stack, int):
			return RegisterStackIndex(reg_stack)
		raise Exception("reg_stack is not convertable to index")

	def get_flag_index(self, flag: FlagType) -> FlagIndex:
		if isinstance(flag, str):
			return self._flags[FlagName(flag)]
		elif isinstance(flag, lowlevelil.ILFlag):
			return flag.index
		elif isinstance(flag, int):
			return FlagIndex(flag)
		raise Exception("flag is not convertable to index")

	def get_semantic_flag_class_index(self, sem_class: Optional[SemanticClassType]) -> SemanticClassIndex:
		if sem_class is None:
			return SemanticClassIndex(0)
		if isinstance(sem_class, str):
			return self._semantic_flag_classes[SemanticClassName(sem_class)]
		elif isinstance(sem_class, lowlevelil.ILSemanticFlagClass):
			return sem_class.index
		elif isinstance(sem_class, int):
			return SemanticClassIndex(sem_class)
		raise Exception("sem_class is not convertable to index")

	def get_semantic_flag_class_name(self, class_index: SemanticClassIndex) -> SemanticClassName:
		"""
		``get_semantic_flag_class_name`` gets the name of a semantic flag class from the index.

		:param int class_index: class_index
		:return: the name of the semantic flag class
		:rtype: str
		"""
		if not isinstance(class_index, int):
			raise ValueError("argument 'class_index' must be an integer")
		return self._semantic_flag_classes_by_index[class_index]

	def get_semantic_flag_group_index(self, sem_group: SemanticGroupType) -> SemanticGroupIndex:
		if isinstance(sem_group, str):
			return self._semantic_flag_groups[SemanticGroupName(sem_group)]
		elif isinstance(sem_group, lowlevelil.ILSemanticFlagGroup):
			return sem_group.index
		return sem_group

	def get_semantic_flag_group_name(self, group_index: SemanticGroupIndex) -> SemanticGroupName:
		"""
		``get_semantic_flag_group_name`` gets the name of a semantic flag group from the index.

		:param int group_index: group_index
		:return: the name of the semantic flag group
		:rtype: str
		"""
		if not isinstance(group_index, int):
			raise ValueError("argument 'group_index' must be an integer")
		return self._semantic_flag_groups_by_index[group_index]

	def get_intrinsic_class(self, intrinsic: IntrinsicIndex) -> IntrinsicClass:
		"""
		``get_intrinsic_class`` gets the intrinsic class from an intrinsic number.

		:param int intrinsic: intrinsic number
		:return: intrinsic class
		:rtype: IntrinsicClass
		"""
		return IntrinsicClass(core.BNGetArchitectureIntrinsicClass(self.handle, intrinsic))

	def get_intrinsic_name(self, intrinsic: IntrinsicIndex) -> IntrinsicName:
		"""
		``get_intrinsic_name`` gets an intrinsic name from an intrinsic number.

		:param int intrinsic: intrinsic number
		:return: the corresponding intrinsic string
		:rtype: IntrinsicName
		"""
		return IntrinsicName(core.BNGetArchitectureIntrinsicName(self.handle, intrinsic))

	def get_intrinsic_index(self, intrinsic: IntrinsicType) -> IntrinsicIndex:
		"""
		``get_intrinsic_index`` gets an intrinsic index given an IntrinsicType.

		:param IntrinsicType intrinsic: intrinsic number
		:return: the corresponding intrinsic string
		:rtype: IntrinsicIndex
		"""
		if isinstance(intrinsic, str):
			return self._intrinsics[IntrinsicName(intrinsic)]
		elif isinstance(intrinsic, lowlevelil.ILIntrinsic):
			return intrinsic.index
		elif isinstance(intrinsic, int):
			return IntrinsicIndex(intrinsic)
		raise Exception("intrinsic is not convertable to index")

	def get_flag_write_type_name(self, write_type: FlagWriteTypeIndex) -> FlagWriteTypeName:
		"""
		``get_flag_write_type_name`` gets the flag write type name for the given flag.

		:param FlagWriteTypeIndex write_type: flag
		:return: flag write type name
		:rtype: FlagWriteTypeName
		"""
		return FlagWriteTypeName(core.BNGetArchitectureFlagWriteTypeName(self.handle, write_type))

	def get_flag_by_name(self, flag: FlagName) -> FlagIndex:
		"""
		``get_flag_by_name`` get flag name for flag index.

		:param FlagName flag: flag name
		:return: flag index for flag name
		:rtype: FlagIndex
		"""
		return self._flags[flag]

	def get_flag_write_type_by_name(self, write_type: FlagWriteTypeName) -> FlagWriteTypeIndex:
		"""
		``get_flag_write_type_by_name`` gets the flag write type name for the flag write type.

		:param str write_type: flag write type
		:return: flag write type
		:rtype: int
		"""
		if write_type == '':
			return FlagWriteTypeIndex(0)
		return self._flag_write_types[write_type]

	def get_semantic_flag_class_by_name(self, sem_class: SemanticClassName) -> SemanticClassIndex:
		"""
		``get_semantic_flag_class_by_name`` gets the semantic flag class index by name.

		:param int sem_class: semantic flag class
		:return: semantic flag class index
		:rtype: str
		"""
		return self._semantic_flag_classes[sem_class]

	def get_semantic_flag_group_by_name(self, sem_group: SemanticGroupName) -> SemanticGroupIndex:
		"""
		``get_semantic_flag_group_by_name`` gets the semantic flag group index by name.

		:param SemanticGroupName sem_group: semantic flag group name
		:return: semantic flag group index
		:rtype: int
		"""
		return self._semantic_flag_groups[sem_group]

	def get_flag_role(self, flag: FlagIndex, sem_class: Optional[SemanticClassIndex] = None) -> FlagRole:
		"""
		``get_flag_role`` gets the role of a given flag.

		:param int flag: flag
		:param int sem_class: optional semantic flag class
		:return: flag role
		:rtype: FlagRole
		"""
		if flag in self._flag_roles:
			return self._flag_roles[flag]
		return FlagRole.SpecialFlagRole

	def get_flag_write_low_level_il(
	    self, op: LowLevelILOperation, size: int, write_type: Optional[FlagWriteTypeName], flag: FlagType,
	    operands: List['lowlevelil.ILOperandType'], il: 'lowlevelil.LowLevelILFunction'
	) -> 'lowlevelil.ExpressionIndex':
		"""
		:param LowLevelILOperation op:
		:param int size:
		:param str write_type:
		:param FlagType flag:
		:param operands: a list of either items that are either string registers, flags, or constant integer values
		:type operands: list(str) or list(int)
		:param LowLevelILFunction il:
		:rtype: lowlevelil.ExpressionIndex
		"""
		flag = self.get_flag_index(flag)
		if flag not in self._flag_roles:
			return il.unimplemented()
		return self.get_default_flag_write_low_level_il(op, size, self._flag_roles[flag], operands, il)

	def get_default_flag_write_low_level_il(
	    self, op: 'lowlevelil.LowLevelILOperation', size: int, role: FlagRole,
	    operands: List['lowlevelil.ILOperandType'], il: 'lowlevelil.LowLevelILFunction'
	) -> 'lowlevelil.ExpressionIndex':
		"""
		:param LowLevelILOperation op:
		:param int size:
		:param FlagRole role:
		:param operands: a list of either items that are either string register names or constant integer values
		:type operands: list(str) or list(int)
		:param LowLevelILFunction il:
		:rtype: ExpressionIndex index
		"""
		operand_list = (core.BNRegisterOrConstant * len(operands))()
		for i in range(len(operands)):
			operand = operands[i]
			if isinstance(operand, str):
				operand_list[i].constant = False
				operand_list[i].reg = self.regs[RegisterName(operand)].index
			elif isinstance(operand, lowlevelil.ILFlag):
				assert len(operands) == 3 and i == 2 and (
						op == LowLevelILOperation.LLIL_ADC
						or op == LowLevelILOperation.LLIL_SBB
						or op == LowLevelILOperation.LLIL_RLC
						or op == LowLevelILOperation.LLIL_RRC
				), "Flag operands only allowed for adc/sbb/rlc/rrc"
				operand_list[i].constant = False
				operand_list[i].reg = operand.index
			elif isinstance(operand, lowlevelil.ILRegister):
				operand_list[i].constant = False
				operand_list[i].reg = operand.index
			else:
				operand_list[i].constant = True
				operand_list[i].value = operand
		return lowlevelil.ExpressionIndex(
		    core.BNGetDefaultArchitectureFlagWriteLowLevelIL(
		        self.handle, op, size, role, operand_list, len(operand_list), il.handle
		    )
		)

	def get_flag_condition_low_level_il(
	    self, cond: 'lowlevelil.LowLevelILFlagCondition', sem_class: Optional[SemanticClassType],
	    il: 'lowlevelil.LowLevelILFunction'
	) -> 'lowlevelil.ExpressionIndex':
		"""
		:param LowLevelILFlagCondition cond: Flag condition to be computed
		:param SemanticClassType sem_class: Semantic class to be used (None for default semantics)
		:param LowLevelILFunction il: LowLevelILFunction object to append ExpressionIndex objects to
		:rtype: ExpressionIndex
		"""
		return self.get_default_flag_condition_low_level_il(cond, sem_class, il)

	def get_default_flag_condition_low_level_il(
	    self, cond: 'lowlevelil.LowLevelILFlagCondition', sem_class: Optional[SemanticClassType],
	    il: 'lowlevelil.LowLevelILFunction'
	) -> 'lowlevelil.ExpressionIndex':
		"""
		:param LowLevelILFlagCondition cond:
		:param SemanticClassType sem_class:
		:param LowLevelILFunction il:
		:rtype: ExpressionIndex
		"""
		_class_index = None
		_class_index = self.get_semantic_flag_class_index(sem_class)
		return lowlevelil.ExpressionIndex(
		    core.BNGetDefaultArchitectureFlagConditionLowLevelIL(self.handle, cond, _class_index, il.handle)
		)

	def get_semantic_flag_group_low_level_il(
	    self, sem_group: Optional[SemanticGroupType], il: 'lowlevelil.LowLevelILFunction'
	) -> 'lowlevelil.ExpressionIndex':
		"""
		:param Optional[SemanticGroupType] sem_group:
		:param LowLevelILFunction il:
		:rtype: lowlevelil.ExpressionIndex
		"""
		return il.unimplemented()

	def get_flags_required_for_flag_condition(
	    self, cond: 'lowlevelil.LowLevelILFlagCondition', sem_class: Optional[SemanticClassType] = None
	):
		if cond in self.flags_required_for_flag_condition:
			return self.flags_required_for_flag_condition[cond]
		return []

	def get_modified_regs_on_write(self, reg: RegisterName) -> List[RegisterName]:
		"""
		``get_modified_regs_on_write`` returns a list of register names that are modified when ``reg`` is written.

		:param str reg: string register name
		:return: list of register names
		:rtype: list(str)
		"""
		reg = core.BNGetArchitectureRegisterByName(self.handle, str(reg))
		count = ctypes.c_ulonglong()
		regs = core.BNGetModifiedArchitectureRegistersOnWrite(self.handle, reg, count)
		assert regs is not None, "core.BNGetModifiedArchitectureRegistersOnWrite is not None"
		result: List[RegisterName] = []
		for i in range(0, count.value):
			result.append(RegisterName(core.BNGetArchitectureRegisterName(self.handle, regs[i])))
		core.BNFreeRegisterList(regs)
		return result

	def assemble(self, code: str, addr: int = 0) -> bytes:
		"""
		``assemble`` converts the string of assembly instructions ``code`` loaded at virtual address ``addr`` to the
		byte representation of those instructions.

		.. note:: Architecture subclasses should implement this method.

		Architecture plugins can override this method to provide assembler functionality. This can be done by
		simply shelling out to an assembler like yasm or llvm-mc, since this method isn't performance sensitive.

		.. note:: It is important that the assembler used accepts a syntax identical to the one emitted by the \
		disassembler. This will prevent confusing the user.

		If there is an error in the input assembly, this function should raise a ValueError (with a reasonable error message).

		:param str code: string representation of the instructions to be assembled
		:param int addr: virtual address that the instructions will be loaded at
		:return: the bytes for the assembled instructions
		:rtype: Python3 - a 'bytes' object; Python2 - a 'bytes' object
		:Example:

			>>> arch.assemble("je 10")
			b'\\x0f\\x84\\x04\\x00\\x00\\x00'
			>>>
		"""
		return NotImplemented

	def is_never_branch_patch_available(self, data: bytes, addr: int = 0) -> bool:
		"""
		``is_never_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be made to **never branch**.

		.. note:: Architecture subclasses should implement this method.

		:param str data: bytes for the instruction to be checked
		:param int addr: the virtual address of the instruction to be patched
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> arch.is_never_branch_patch_available(arch.assemble("je 10"), 0)
			True
			>>> arch.is_never_branch_patch_available(arch.assemble("nop"), 0)
			False
			>>>
		"""
		return NotImplemented

	def is_always_branch_patch_available(self, data: bytes, addr: int = 0) -> bool:
		"""
		``is_always_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be made to
		**always branch**.

		.. note:: Architecture subclasses should implement this method.

		:param str data: bytes for the instruction to be checked
		:param int addr: the virtual address of the instruction to be patched
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> arch.is_always_branch_patch_available(arch.assemble("je 10"), 0)
			True
			>>> arch.is_always_branch_patch_available(arch.assemble("nop"), 0)
			False
			>>>
		"""
		return NotImplemented

	def is_invert_branch_patch_available(self, data: bytes, addr: int = 0) -> bool:
		"""
		``is_always_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be inverted.

		.. note:: Architecture subclasses should implement this method.

		:param str data: bytes for the instruction to be checked
		:param int addr: the virtual address of the instruction to be patched
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> arch.is_invert_branch_patch_available(arch.assemble("je 10"), 0)
			True
			>>> arch.is_invert_branch_patch_available(arch.assemble("nop"), 0)
			False
			>>>
		"""
		return NotImplemented

	def is_skip_and_return_zero_patch_available(self, data: bytes, addr: int = 0) -> bool:
		"""
		``is_skip_and_return_zero_patch_available`` determines if the instruction ``data`` at ``addr`` is a *call-like*
		instruction that can be made into an instruction *returns zero*.

		.. note:: Architecture subclasses should implement this method.

		:param str data: bytes for the instruction to be checked
		:param int addr: the virtual address of the instruction to be patched
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> arch.is_skip_and_return_zero_patch_available(arch.assemble("call 0"), 0)
			True
			>>> arch.is_skip_and_return_zero_patch_available(arch.assemble("call eax"), 0)
			True
			>>> arch.is_skip_and_return_zero_patch_available(arch.assemble("jmp eax"), 0)
			False
			>>>
		"""
		return NotImplemented

	def is_skip_and_return_value_patch_available(self, data: bytes, addr: int = 0) -> bool:
		"""
		``is_skip_and_return_value_patch_available`` determines if the instruction ``data`` at ``addr`` is a *call-like*
		instruction that can be made into an instruction *returns a value*.

		.. note:: Architecture subclasses should implement this method.

		:param str data: bytes for the instruction to be checked
		:param int addr: the virtual address of the instruction to be patched
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> arch.is_skip_and_return_value_patch_available(arch.assemble("call 0"), 0)
			True
			>>> arch.is_skip_and_return_value_patch_available(arch.assemble("jmp eax"), 0)
			False
			>>>
		"""
		return NotImplemented

	def convert_to_nop(self, data: bytes, addr: int = 0) -> Optional[bytes]:
		"""
		``convert_to_nop`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of nop
		instructions of the same length as data.

		.. note:: Architecture subclasses should implement this method.

		:param str data: bytes for the instruction to be converted
		:param int addr: the virtual address of the instruction to be patched
		:return: string containing len(data) worth of no-operation instructions
		:rtype: str
		:Example:

			>>> arch.convert_to_nop(b"\\x00\\x00", 0)
			b'\\x90\\x90'
			>>>
		"""
		return NotImplemented

	def always_branch(self, data: bytes, addr: int = 0) -> Optional[bytes]:
		"""
		``always_branch`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of bytes
		of the same length which always branches.

		.. note:: Architecture subclasses should implement this method.

		:param str data: bytes for the instruction to be converted
		:param int addr: the virtual address of the instruction to be patched
		:return: string containing len(data) which always branches to the same location as the provided instruction
		:rtype: str
		:Example:

			>>> data = arch.always_branch(arch.assemble("je 10"), 0)
			>>> arch.get_instruction_text(data, 0)
			(['nop', '     '], 1)
			>>> arch.get_instruction_text(data[1:], 0)
			(['jmp', '     ', '0x9'], 5)
			>>>
		"""
		return NotImplemented

	def invert_branch(self, data: bytes, addr: int = 0) -> Optional[bytes]:
		"""
		``invert_branch`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of bytes
		of the same length which inverts the branch of provided instruction.

		.. note:: Architecture subclasses should implement this method.

		:param str data: bytes for the instruction to be converted
		:param int addr: the virtual address of the instruction to be patched
		:return: string containing len(data) which always branches to the same location as the provided instruction
		:rtype: str
		:Example:

			>>> arch.get_instruction_text(arch.invert_branch(arch.assemble("je 10"), 0), 0)
			(['jne', '     ', '0xa'], 6)
			>>> arch.get_instruction_text(arch.invert_branch(arch.assemble("jo 10"), 0), 0)
			(['jno', '     ', '0xa'], 6)
			>>> arch.get_instruction_text(arch.invert_branch(arch.assemble("jge 10"), 0), 0)
			(['jl', '      ', '0xa'], 6)
			>>>
		"""
		return NotImplemented

	def skip_and_return_value(self, data: bytes, addr: int, value: int) -> Optional[bytes]:
		"""
		``skip_and_return_value`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of
		bytes of the same length which doesn't call and instead *return a value*.

		.. note:: Architecture subclasses should implement this method.

		:param str data: bytes for the instruction to be converted
		:param int addr: the virtual address of the instruction to be patched
		:return: string containing len(data) which always branches to the same location as the provided instruction
		:rtype: str
		:Example:

			>>> arch.get_instruction_text(arch.skip_and_return_value(arch.assemble("call 10"), 0, 0), 0)
			(['mov', '     ', 'eax', ', ', '0x0'], 5)
			>>>
		"""
		return NotImplemented

	def register_calling_convention(self, cc: 'callingconvention.CallingConvention') -> None:
		"""
		``register_calling_convention`` registers a new calling convention for the Architecture.

		:param CallingConvention cc: CallingConvention object to be registered
		:rtype: None
		"""
		core.BNRegisterCallingConvention(self.handle, cc.handle)

	@property
	def default_calling_convention(self):
		"""
		Default calling convention.

		.. note:: Make sure the calling convention has been registered with `Architecture.register_calling_convention`.

		:getter: returns a CallingConvention object for the default calling convention, if one exists.
		:setter: sets the default calling convention
		:type: Optional['callingconvention.CallingConvention']
		"""
		cc_handle = core.BNGetArchitectureDefaultCallingConvention(self.handle)
		if cc_handle is None:
			return None
		return callingconvention.CallingConvention(handle=cc_handle)

	@default_calling_convention.setter
	def default_calling_convention(self, cc: 'callingconvention.CallingConvention'):
		core.BNSetArchitectureDefaultCallingConvention(self.handle, cc.handle)

	@property
	def cdecl_calling_convention(self):
		"""
		Cdecl calling convention.

		.. note:: Make sure the calling convention has been registered with `Architecture.register_calling_convention`.

		:getter: returns a CallingConvention object for the cdecl calling convention, if one exists.
		:setter: sets the cdecl calling convention
		:type: Optional['callingconvention.CallingConvention']
		"""
		cc_handle = core.BNGetArchitectureCdeclCallingConvention(self.handle)
		if cc_handle is None:
			return None
		return callingconvention.CallingConvention(handle=cc_handle)

	@cdecl_calling_convention.setter
	def cdecl_calling_convention(self, cc: 'callingconvention.CallingConvention'):
		core.BNSetArchitectureCdeclCallingConvention(self.handle, cc.handle)

	@property
	def stdcall_calling_convention(self):
		"""
		Stdcall calling convention.

		.. note:: Make sure the calling convention has been registered with `Architecture.register_calling_convention`.

		:getter: returns a CallingConvention object for the stdcall calling convention, if one exists.
		:setter: sets the stdcall calling convention
		:type: Optional['callingconvention.CallingConvention']
		"""
		cc_handle = core.BNGetArchitectureStdcallCallingConvention(self.handle)
		if cc_handle is None:
			return None
		return callingconvention.CallingConvention(handle=cc_handle)

	@stdcall_calling_convention.setter
	def stdcall_calling_convention(self, cc: 'callingconvention.CallingConvention'):
		core.BNSetArchitectureStdcallCallingConvention(self.handle, cc.handle)

	@property
	def fastcall_calling_convention(self):
		"""
		Fastcall calling convention.

		.. note:: Make sure the calling convention has been registered with `Architecture.register_calling_convention`.

		:getter: returns a CallingConvention object for the fastcall calling convention, if one exists.
		:setter: sets the fastcall calling convention
		:type: Optional['callingconvention.CallingConvention']
		"""
		cc_handle = core.BNGetArchitectureFastcallCallingConvention(self.handle)
		if cc_handle is None:
			return None
		return callingconvention.CallingConvention(handle=cc_handle)

	@fastcall_calling_convention.setter
	def fastcall_calling_convention(self, cc: 'callingconvention.CallingConvention'):
		core.BNSetArchitectureFastcallCallingConvention(self.handle, cc.handle)


_architecture_cache = {}


class CoreArchitecture(Architecture):
	def __init__(self, handle: core.BNArchitecture):
		super(CoreArchitecture, self).__init__()

		self.handle = core.handle_of_type(handle, core.BNArchitecture)
		self.name = core.BNGetArchitectureName(self.handle)
		self.endianness = Endianness(core.BNGetArchitectureEndianness(self.handle))
		self.address_size = core.BNGetArchitectureAddressSize(self.handle)
		self.default_int_size = core.BNGetArchitectureDefaultIntegerSize(self.handle)
		self.instr_alignment = core.BNGetArchitectureInstructionAlignment(self.handle)
		self.max_instr_length = core.BNGetArchitectureMaxInstructionLength(self.handle)
		self.opcode_display_length = core.BNGetArchitectureOpcodeDisplayLength(self.handle)
		self.stack_pointer: str = core.BNGetArchitectureRegisterName(
		    self.handle, core.BNGetArchitectureStackPointerRegister(self.handle)
		)

		link_reg = core.BNGetArchitectureLinkRegister(self.handle)
		if link_reg == 0xffffffff:
			self.link_reg = None
		else:
			self.link_reg = core.BNGetArchitectureRegisterName(self.handle, link_reg)

		count = ctypes.c_ulonglong()
		regs = core.BNGetAllArchitectureRegisters(self.handle, count)
		assert regs is not None, "core.BNGetAllArchitectureRegisters returned None"
		self._all_regs = {}
		self._regs_by_index = {}
		self._full_width_regs = {}
		self.regs = {}
		for i in range(0, count.value):
			name = RegisterName(core.BNGetArchitectureRegisterName(self.handle, regs[i]))
			assert name is not None, ""
			info = core.BNGetArchitectureRegisterInfo(self.handle, regs[i])
			full_width_reg = RegisterName(core.BNGetArchitectureRegisterName(self.handle, info.fullWidthRegister))
			self.regs[name] = RegisterInfo(
			    full_width_reg, info.size, info.offset, ImplicitRegisterExtend(info.extend), regs[i]
			)
			self._all_regs[name] = regs[i]
			self._regs_by_index[regs[i]] = name
		for i in range(0, count.value):
			info = core.BNGetArchitectureRegisterInfo(self.handle, regs[i])
			full_width_reg = RegisterName(core.BNGetArchitectureRegisterName(self.handle, info.fullWidthRegister))
			if full_width_reg not in self._full_width_regs:
				self._full_width_regs[full_width_reg] = self._all_regs[full_width_reg]
		core.BNFreeRegisterList(regs)

		count = ctypes.c_ulonglong()
		flags = core.BNGetAllArchitectureFlags(self.handle, count)
		assert flags is not None, "core.BNGetAllArchitectureFlags returned None"
		self._flags = {}
		self._flags_by_index = {}
		self.flags = []
		for i in range(0, count.value):
			name = FlagName(core.BNGetArchitectureFlagName(self.handle, flags[i]))
			self._flags[name] = flags[i]
			self._flags_by_index[flags[i]] = name
			self.flags.append(name)
		core.BNFreeRegisterList(flags)

		count = ctypes.c_ulonglong()
		write_types = core.BNGetAllArchitectureFlagWriteTypes(self.handle, count)
		assert write_types is not None, "core.BNGetAllArchitectureFlagWriteTypes returned None"
		self._flag_write_types: Dict[str, FlagWriteTypeIndex] = {}
		self._flag_write_types_by_index = {}
		self.flag_write_types = []
		for i in range(0, count.value):
			name = FlagWriteTypeName(core.BNGetArchitectureFlagWriteTypeName(self.handle, write_types[i]))
			self._flag_write_types[name] = write_types[i]
			self._flag_write_types_by_index[write_types[i]] = name
			self.flag_write_types.append(name)
		core.BNFreeRegisterList(write_types)

		count = ctypes.c_ulonglong()
		sem_classes = core.BNGetAllArchitectureSemanticFlagClasses(self.handle, count)
		assert sem_classes is not None, "core.BNGetAllArchitectureSemanticFlagClasses returned None"
		self._semantic_flag_classes = {}
		self._semantic_flag_classes_by_index = {}
		self.semantic_flag_classes = []
		for i in range(0, count.value):
			name = SemanticClassName(core.BNGetArchitectureSemanticFlagClassName(self.handle, sem_classes[i]))
			self._semantic_flag_classes[name] = sem_classes[i]
			self._semantic_flag_classes_by_index[sem_classes[i]] = name
			self.semantic_flag_classes.append(name)
		core.BNFreeRegisterList(sem_classes)

		count = ctypes.c_ulonglong()
		sem_groups = core.BNGetAllArchitectureSemanticFlagGroups(self.handle, count)
		assert sem_groups is not None, "core.BNGetAllArchitectureSemanticFlagGroups returned Non"
		self._semantic_flag_groups = {}
		self._semantic_flag_groups_by_index = {}
		self.semantic_flag_groups = []
		for i in range(0, count.value):
			name = SemanticGroupName(core.BNGetArchitectureSemanticFlagGroupName(self.handle, sem_groups[i]))
			self._semantic_flag_groups[name] = sem_groups[i]
			self._semantic_flag_groups_by_index[sem_groups[i]] = name
			self.semantic_flag_groups.append(name)
		core.BNFreeRegisterList(sem_groups)

		self._flag_roles = {}
		self.flag_roles = {}
		for flag in self.flags:
			role = FlagRole(core.BNGetArchitectureFlagRole(self.handle, self._flags[flag], 0))
			self.flag_roles[flag] = role
			self._flag_roles[self._flags[flag]] = role

		self.flags_required_for_flag_condition: Dict[LowLevelILFlagCondition, List[FlagName]] = {}
		for cond in LowLevelILFlagCondition:
			count = ctypes.c_ulonglong()
			flags = core.BNGetArchitectureFlagsRequiredForFlagCondition(self.handle, cond, 0, count)
			assert flags is not None, "core.BNGetArchitectureFlagsRequiredForFlagCondition returned None"
			flag_names = []
			for i in range(0, count.value):
				flag_names.append(self._flags_by_index[flags[i]])
			core.BNFreeRegisterList(flags)
			self.flags_required_for_flag_condition[cond] = flag_names

		self._flags_required_by_semantic_flag_group = {}
		self.flags_required_for_semantic_flag_group = {}
		for group in self.semantic_flag_groups:
			count = ctypes.c_ulonglong()
			flags = core.BNGetArchitectureFlagsRequiredForSemanticFlagGroup(
			    self.handle, self._semantic_flag_groups[group], count
			)
			assert flags is not None, "core.BNGetArchitectureFlagsRequiredForSemanticFlagGroup returned None"
			flag_indexes = []
			flag_names = []
			for i in range(0, count.value):
				flag_indexes.append(flags[i])
				flag_names.append(self._flags_by_index[flags[i]])
			core.BNFreeRegisterList(flags)
			self._flags_required_by_semantic_flag_group[self._semantic_flag_groups[group]] = flag_indexes
			self.flags_required_for_semantic_flag_group[group] = flag_names

		self._flag_conditions_for_semantic_flag_group = {}
		self.flag_conditions_for_semantic_flag_group = {}
		for group in self.semantic_flag_groups:
			count = ctypes.c_ulonglong()
			conditions = core.BNGetArchitectureFlagConditionsForSemanticFlagGroup(
			    self.handle, self._semantic_flag_groups[group], count
			)
			assert conditions is not None, "core.BNGetArchitectureFlagConditionsForSemanticFlagGroup returned None"
			class_index_cond = {}
			class_cond = {}
			for i in range(0, count.value):
				class_index_cond[conditions[i].semanticClass] = conditions[i].condition
				if conditions[i].semanticClass == 0:
					class_cond[None] = conditions[i].condition
				elif conditions[i].semanticClass in self._semantic_flag_classes_by_index:
					class_cond[self._semantic_flag_classes_by_index[conditions[i].semanticClass]
					           ] = conditions[i].condition
			core.BNFreeFlagConditionsForSemanticFlagGroup(conditions)
			self._flag_conditions_for_semantic_flag_group[self._semantic_flag_groups[group]] = class_index_cond
			self.flag_conditions_for_semantic_flag_group[group] = class_cond

		self._flags_written_by_flag_write_type = {}
		self.flags_written_by_flag_write_type = {}
		for write_type in self.flag_write_types:
			count = ctypes.c_ulonglong()
			flags = core.BNGetArchitectureFlagsWrittenByFlagWriteType(
			    self.handle, self._flag_write_types[write_type], count
			)
			assert flags is not None, "core.BNGetArchitectureFlagsWrittenByFlagWriteType returned None"
			flag_indexes = []
			flag_names = []
			for i in range(0, count.value):
				flag_indexes.append(flags[i])
				flag_names.append(self._flags_by_index[flags[i]])
			core.BNFreeRegisterList(flags)
			self._flags_written_by_flag_write_type[self._flag_write_types[write_type]] = flag_indexes
			self.flags_written_by_flag_write_type[write_type] = flag_names

		self._semantic_class_for_flag_write_type = {}
		self.semantic_class_for_flag_write_type = {}
		for write_type in self.flag_write_types:
			sem_class = core.BNGetArchitectureSemanticClassForFlagWriteType(
			    self.handle, self._flag_write_types[write_type]
			)
			if sem_class == 0:
				sem_class_name = None
			else:
				sem_class_name = self._semantic_flag_classes_by_index[sem_class]
			self._semantic_class_for_flag_write_type[self._flag_write_types[write_type]] = sem_class
			self.semantic_class_for_flag_write_type[write_type] = sem_class_name

		count = ctypes.c_ulonglong()
		regs = core.BNGetArchitectureGlobalRegisters(self.handle, count)
		assert regs is not None, "core.BNGetArchitectureGlobalRegisters returned None"
		self.global_regs: List[RegisterName] = []
		for i in range(0, count.value):
			self.global_regs.append(RegisterName(core.BNGetArchitectureRegisterName(self.handle, regs[i])))
		core.BNFreeRegisterList(regs)

		count = ctypes.c_ulonglong()
		regs = core.BNGetArchitectureSystemRegisters(self.handle, count)
		self.system_regs: List[RegisterName] = []
		for i in range(0, count.value):
			assert regs is not None, "core.BNGetArchitectureSystemRegisters returned None"
			self.system_regs.append(RegisterName(core.BNGetArchitectureRegisterName(self.handle, regs[i])))
		core.BNFreeRegisterList(regs)

		count = ctypes.c_ulonglong()
		regs = core.BNGetAllArchitectureRegisterStacks(self.handle, count)
		assert regs is not None, "core.BNGetAllArchitectureRegisterStacks returned None"
		self._all_reg_stacks = {}
		self._reg_stacks_by_index = {}
		self.reg_stacks = {}
		for i in range(0, count.value):
			name = RegisterStackName(core.BNGetArchitectureRegisterStackName(self.handle, regs[i]))
			info = core.BNGetArchitectureRegisterStackInfo(self.handle, regs[i])
			storage: List[RegisterName] = []
			for j in range(0, info.storageCount):
				storage.append(RegisterName(core.BNGetArchitectureRegisterName(self.handle, info.firstStorageReg + j)))
			top_rel: List[RegisterName] = []
			for j in range(0, info.topRelativeCount):
				reg_name = RegisterName(core.BNGetArchitectureRegisterName(self.handle, info.firstTopRelativeReg + j))
				top_rel.append(reg_name)
			top = core.BNGetArchitectureRegisterName(self.handle, info.stackTopReg)
			self.reg_stacks[name] = RegisterStackInfo(storage, top_rel, RegisterName(top), regs[i])
			self._all_reg_stacks[name] = regs[i]
			self._reg_stacks_by_index[regs[i]] = name
		core.BNFreeRegisterList(regs)

		count = ctypes.c_ulonglong()
		intrinsics = core.BNGetAllArchitectureIntrinsics(self.handle, count)
		assert intrinsics is not None, "core.BNGetAllArchitectureIntrinsics returned None"
		self._intrinsics: Dict[IntrinsicName, IntrinsicIndex] = {}
		self._intrinsic_class_by_index: Dict[IntrinsicIndex, IntrinsicClass] = {}
		self._intrinsics_by_index: Dict[IntrinsicIndex, Tuple[IntrinsicName, IntrinsicInfo]] = {}
		self._intrinsics_info: Dict[IntrinsicName, IntrinsicInfo] = {}
		for i in range(count.value):
			intrinsic_class = IntrinsicClass(core.BNGetArchitectureIntrinsicClass(self.handle, intrinsics[i]))
			name = IntrinsicName(core.BNGetArchitectureIntrinsicName(self.handle, intrinsics[i]))
			input_count = ctypes.c_ulonglong()
			inputs = core.BNGetArchitectureIntrinsicInputs(self.handle, intrinsics[i], input_count)
			assert inputs is not None, "core.BNGetArchitectureIntrinsicInputs returned None"
			input_list = []
			for j in range(0, input_count.value):
				input_name = inputs[j].name
				type_obj = types.Type.create(
				    core.BNNewTypeReference(inputs[j].type), confidence=inputs[j].typeConfidence
				)
				input_list.append(IntrinsicInput(type_obj, input_name))
			core.BNFreeNameAndTypeList(inputs, input_count.value)
			output_count = ctypes.c_ulonglong()
			outputs = core.BNGetArchitectureIntrinsicOutputs(self.handle, intrinsics[i], output_count)
			assert outputs is not None, "core.BNGetArchitectureIntrinsicOutputs returned None"
			output_list = []
			for j in range(output_count.value):
				output_list.append(
				    types.Type.create(core.BNNewTypeReference(outputs[j].type), confidence=outputs[j].confidence)
				)
			core.BNFreeOutputTypeList(outputs, output_count.value)
			if intrinsic_class is not IntrinsicClass.GeneralIntrinsicClass:
				self._intrinsic_class_by_index[intrinsics[i]] = intrinsic_class
			self._intrinsics_info[name] = IntrinsicInfo(input_list, output_list)
			self._intrinsics[name] = intrinsics[i]
			self._intrinsics_by_index[intrinsics[i]] = (name, self._intrinsics_info[name])
			self.intrinsics[name] = self._intrinsics_info[name]
		core.BNFreeRegisterList(intrinsics)
		if type(self) is CoreArchitecture:
			global _architecture_cache
			_architecture_cache[ctypes.addressof(handle.contents)] = self

	@classmethod
	def _from_cache(cls, handle) -> 'Architecture':
		global _architecture_cache
		return _architecture_cache.get(ctypes.addressof(handle.contents)) or cls(handle)

	def get_associated_arch_by_address(self, addr: int) -> Tuple['Architecture', int]:
		new_addr = ctypes.c_ulonglong()
		new_addr.value = addr
		result = core.BNGetAssociatedArchitectureByAddress(self.handle, new_addr)
		return CoreArchitecture._from_cache(handle=result), new_addr.value

	def get_instruction_info(self, data: bytes, addr: int) -> Optional[InstructionInfo]:
		"""
		``get_instruction_info`` returns an InstructionInfo object for the instruction at the given virtual address
		``addr`` with data ``data``.

		.. note:: The instruction info object should always set the InstructionInfo.length to the instruction length, \
		and the branches of the proper types should be added if the instruction is a branch.

		:param bytes data: a maximum of max_instruction_length bytes from the binary at virtual address ``addr``
		:param int addr: virtual address of bytes in ``data``
		:return: the InstructionInfo for the current instruction
		:rtype: InstructionInfo
		"""
		info = core.BNInstructionInfo()
		buf = (ctypes.c_ubyte * len(data))()
		ctypes.memmove(buf, data, len(data))
		if not core.BNGetInstructionInfo(self.handle, buf, addr, len(data), info):
			return None
		result = InstructionInfo()
		result.length = info.length
		result.arch_transition_by_target_addr = info.archTransitionByTargetAddr
		result.branch_delay = info.delaySlots
		for i in range(0, info.branchCount):
			target = info.branchTarget[i]
			if info.branchArch[i]:
				arch = CoreArchitecture._from_cache(info.branchArch[i])
			else:
				arch = None
			result.add_branch(BranchType(info.branchType[i]), target, arch)
		return result

	def get_instruction_text(self, data: bytes, addr: int) -> Optional[Tuple[List['function.InstructionTextToken'], int]]:
		"""
		``get_instruction_text`` returns a list of InstructionTextToken objects for the instruction at the given virtual
		address ``addr`` with data ``data``.

		:param bytes data: a maximum of max_instruction_length bytes from the binary at virtual address ``addr``
		:param int addr: virtual address of bytes in ``data``
		:return: an InstructionTextToken list for the current instruction
		:rtype: list(InstructionTextToken)
		"""
		count = ctypes.c_ulonglong()
		length = ctypes.c_ulonglong()
		length.value = len(data)
		buf = (ctypes.c_ubyte * len(data))()
		ctypes.memmove(buf, data, len(data))
		tokens = ctypes.POINTER(core.BNInstructionTextToken)()
		result = []
		result_length = 0
		if core.BNGetInstructionText(self.handle, buf, addr, length, tokens, count):
			result = function.InstructionTextToken._from_core_struct(tokens, count.value)
			result_length = length.value
			core.BNFreeInstructionText(tokens, count.value)
		return result, result_length

	def get_instruction_low_level_il(self, data: bytes, addr: int, il: lowlevelil.LowLevelILFunction) -> Optional[int]:
		"""
		``get_instruction_low_level_il`` appends lowlevelil.ExpressionIndex objects to ``il`` for the instruction at the given
		virtual address ``addr`` with data ``data``.

		This is used to analyze arbitrary data at an address, if you are working with an existing binary, you likely
		want to be using :func:`Function.get_low_level_il_at`.

		:param bytes data: a maximum of max_instruction_length bytes from the binary at virtual address ``addr``
		:param int addr: virtual address of bytes in ``data``
		:param LowLevelILFunction il: The function the current instruction belongs to
		:return: the length of the current instruction
		:rtype: Optional[int]
		"""
		length = ctypes.c_ulonglong()
		length.value = len(data)
		buf = (ctypes.c_ubyte * len(data))()
		ctypes.memmove(buf, data, len(data))
		if core.BNGetInstructionLowLevelIL(self.handle, buf, addr, length, il.handle):
			return length.value
		return None

	def get_flag_write_low_level_il(
	    self, op: LowLevelILOperation, size: int, write_type: FlagWriteTypeName, flag: FlagType,
	    operands: List['lowlevelil.ILRegisterType'], il: 'lowlevelil.LowLevelILFunction'
	) -> 'lowlevelil.ExpressionIndex':
		"""
		:param LowLevelILOperation op:
		:param int size:
		:param str write_type:
		:param operands: a list of either items that are either string register names or constant integer values
		:type operands: list(str) or list(int)
		:param LowLevelILFunction il:
		:rtype: ExpressionIndex
		"""
		flag = self.get_flag_index(flag)
		operand_list = (core.BNRegisterOrConstant * len(operands))()
		for i in range(len(operands)):
			operand = operands[i]
			if isinstance(operand, str):
				operand_list[i].constant = False
				operand_list[i].reg = self.regs[RegisterName(operand)].index
			elif isinstance(operand, lowlevelil.ILRegister):
				operand_list[i].constant = False
				operand_list[i].reg = operand.index
			elif isinstance(operand, lowlevelil.ILFlag):
				operand_list[i].constant = False
				operand_list[i].reg = operand.index
			else:
				operand_list[i].constant = True
				operand_list[i].value = operand
		return lowlevelil.ExpressionIndex(
		    core.BNGetArchitectureFlagWriteLowLevelIL(
		        self.handle, op, size, self._flag_write_types[write_type], flag, operand_list, len(operand_list),
		        il.handle
		    )
		)

	def get_flag_condition_low_level_il(
	    self, cond: LowLevelILFlagCondition, sem_class: SemanticClassType, il: 'lowlevelil.LowLevelILFunction'
	) -> 'lowlevelil.ExpressionIndex':
		"""
		:param LowLevelILFlagCondition cond: Flag condition to be computed
		:param str sem_class: Semantic class to be used (None for default semantics)
		:param LowLevelILFunction il: LowLevelILFunction object to append ExpressionIndex objects to
		:rtype: ExpressionIndex
		"""
		class_index = self.get_semantic_flag_class_index(sem_class)
		return lowlevelil.ExpressionIndex(
		    core.BNGetArchitectureFlagConditionLowLevelIL(self.handle, cond, class_index, il.handle)
		)

	def get_semantic_flag_group_low_level_il(
	    self, sem_group: SemanticGroupName, il: 'lowlevelil.LowLevelILFunction'
	) -> 'lowlevelil.ExpressionIndex':
		"""
		:param str sem_group:
		:param LowLevelILFunction il:
		:rtype: ExpressionIndex
		"""
		group_index = self.get_semantic_flag_group_index(sem_group)
		return lowlevelil.ExpressionIndex(
		    core.BNGetArchitectureSemanticFlagGroupLowLevelIL(self.handle, group_index, il.handle)
		)

	def assemble(self, code: str, addr: int = 0) -> bytes:
		"""
		``assemble`` converts the string of assembly instructions ``code`` loaded at virtual address ``addr`` to the
		byte representation of those instructions.

		:param str code: string representation of the instructions to be assembled
		:param int addr: virtual address that the instructions will be loaded at
		:return: the bytes for the assembled instructions
		:rtype: Python3 - a 'bytes' object; Python2 - a 'bytes' object
		:Example:

			>>> arch.assemble("je 10")
			b'\\x0f\\x84\\x04\\x00\\x00\\x00'
			>>>
		"""
		result = databuffer.DataBuffer()
		errors = ctypes.c_char_p()
		if not core.BNAssemble(self.handle, code, addr, result.handle, errors):
			error_str = errors.value
			core.free_string(errors)
			raise ValueError(f"Could not assemble: {error_str}")
		return bytes(result)

	def is_never_branch_patch_available(self, data: bytes, addr: int = 0) -> bool:
		"""
		``is_never_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be made to **never branch**.

		:param str data: bytes for the instruction to be checked
		:param int addr: the virtual address of the instruction to be patched
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> arch.is_never_branch_patch_available(arch.assemble("je 10"), 0)
			True
			>>> arch.is_never_branch_patch_available(arch.assemble("nop"), 0)
			False
			>>>
		"""
		buf = (ctypes.c_ubyte * len(data))()
		ctypes.memmove(buf, data, len(data))
		return core.BNIsArchitectureNeverBranchPatchAvailable(self.handle, buf, addr, len(data))

	def is_always_branch_patch_available(self, data: bytes, addr: int = 0) -> bool:
		"""
		``is_always_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be made to
		**always branch**.

		:param str data: bytes for the instruction to be checked
		:param int addr: the virtual address of the instruction to be patched
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> arch.is_always_branch_patch_available(arch.assemble("je 10"), 0)
			True
			>>> arch.is_always_branch_patch_available(arch.assemble("nop"), 0)
			False
			>>>
		"""
		buf = (ctypes.c_ubyte * len(data))()
		ctypes.memmove(buf, data, len(data))
		return core.BNIsArchitectureAlwaysBranchPatchAvailable(self.handle, buf, addr, len(data))

	def is_invert_branch_patch_available(self, data: bytes, addr: int = 0) -> bool:
		"""
		``is_always_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be inverted.

		:param str data: bytes for the instruction to be checked
		:param int addr: the virtual address of the instruction to be patched
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> arch.is_invert_branch_patch_available(arch.assemble("je 10"), 0)
			True
			>>> arch.is_invert_branch_patch_available(arch.assemble("nop"), 0)
			False
			>>>
		"""
		buf = (ctypes.c_ubyte * len(data))()
		ctypes.memmove(buf, data, len(data))
		return core.BNIsArchitectureInvertBranchPatchAvailable(self.handle, buf, addr, len(data))

	def is_skip_and_return_zero_patch_available(self, data: bytes, addr: int = 0) -> bool:
		"""
		``is_skip_and_return_zero_patch_available`` determines if the instruction ``data`` at ``addr`` is a *call-like*
		instruction that can be made into an instruction *returns zero*.

		:param str data: bytes for the instruction to be checked
		:param int addr: the virtual address of the instruction to be patched
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> arch.is_skip_and_return_zero_patch_available(arch.assemble("call 0"), 0)
			True
			>>> arch.is_skip_and_return_zero_patch_available(arch.assemble("call eax"), 0)
			True
			>>> arch.is_skip_and_return_zero_patch_available(arch.assemble("jmp eax"), 0)
			False
			>>>
		"""
		buf = (ctypes.c_ubyte * len(data))()
		ctypes.memmove(buf, data, len(data))
		return core.BNIsArchitectureSkipAndReturnZeroPatchAvailable(self.handle, buf, addr, len(data))

	def is_skip_and_return_value_patch_available(self, data: bytes, addr: int = 0) -> bool:
		"""
		``is_skip_and_return_value_patch_available`` determines if the instruction ``data`` at ``addr`` is a *call-like*
		instruction that can be made into an instruction *returns a value*.

		:param str data: bytes for the instruction to be checked
		:param int addr: the virtual address of the instruction to be patched
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> arch.is_skip_and_return_value_patch_available(arch.assemble("call 0"), 0)
			True
			>>> arch.is_skip_and_return_value_patch_available(arch.assemble("jmp eax"), 0)
			False
			>>>
		"""
		buf = (ctypes.c_ubyte * len(data))()
		ctypes.memmove(buf, data, len(data))
		return core.BNIsArchitectureSkipAndReturnValuePatchAvailable(self.handle, buf, addr, len(data))

	def convert_to_nop(self, data: bytes, addr: int = 0) -> Optional[bytes]:
		"""
		``convert_to_nop`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of nop
		instructions of the same length as data.

		:param str data: bytes for the instruction to be converted
		:param int addr: the virtual address of the instruction to be patched
		:return: string containing len(data) worth of no-operation instructions
		:rtype: str
		:Example:

			>>> arch.convert_to_nop(b"\\x00\\x00", 0)
			b'\\x90\\x90'
			>>>
		"""
		buf = (ctypes.c_ubyte * len(data))()
		ctypes.memmove(buf, data, len(data))
		if not core.BNArchitectureConvertToNop(self.handle, buf, addr, len(data)):
			return None
		result = ctypes.create_string_buffer(len(data))
		ctypes.memmove(result, buf, len(data))
		return result.raw

	def always_branch(self, data: bytes, addr: int = 0) -> Optional[bytes]:
		"""
		``always_branch`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of bytes
		of the same length which always branches.

		:param str data: bytes for the instruction to be converted
		:param int addr: the virtual address of the instruction to be patched
		:return: string containing len(data) which always branches to the same location as the provided instruction
		:rtype: str
		:Example:

			>>> data = arch.always_branch(arch.assemble("je 10"), 0)
			>>> arch.get_instruction_text(data, 0)
			(['nop', '     '], 1)
			>>> arch.get_instruction_text(bytes[1:], 0)
			(['jmp', '     ', '0x9'], 5)
			>>>
		"""
		buf = (ctypes.c_ubyte * len(data))()
		ctypes.memmove(buf, data, len(data))
		if not core.BNArchitectureAlwaysBranch(self.handle, buf, addr, len(data)):
			return None
		result = ctypes.create_string_buffer(len(data))
		ctypes.memmove(result, buf, len(data))
		return result.raw

	def invert_branch(self, data: bytes, addr: int = 0) -> Optional[bytes]:
		"""
		``invert_branch`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of bytes
		of the same length which inverts the branch of provided instruction.

		:param str data: bytes for the instruction to be converted
		:param int addr: the virtual address of the instruction to be patched
		:return: string containing len(data) which always branches to the same location as the provided instruction
		:rtype: str
		:Example:

			>>> arch.get_instruction_text(arch.invert_branch(arch.assemble("je 10"), 0), 0)
			(['jne', '     ', '0xa'], 6)
			>>> arch.get_instruction_text(arch.invert_branch(arch.assemble("jo 10"), 0), 0)
			(['jno', '     ', '0xa'], 6)
			>>> arch.get_instruction_text(arch.invert_branch(arch.assemble("jge 10"), 0), 0)
			(['jl', '      ', '0xa'], 6)
			>>>
		"""
		buf = (ctypes.c_ubyte * len(data))()
		ctypes.memmove(buf, data, len(data))
		if not core.BNArchitectureInvertBranch(self.handle, buf, addr, len(data)):
			return None
		result = ctypes.create_string_buffer(len(data))
		ctypes.memmove(result, buf, len(data))
		return result.raw

	def skip_and_return_value(self, data: bytes, addr: int, value: int) -> Optional[bytes]:
		"""
		``skip_and_return_value`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of
		bytes of the same length which doesn't call and instead *return a value*.

		:param str data: bytes for the instruction to be converted
		:param int addr: the virtual address of the instruction to be patched
		:param int value: the value to return
		:return: string containing len(data) which always branches to the same location as the provided instruction
		:rtype: str
		:Example:

			>>> arch.get_instruction_text(arch.skip_and_return_value(arch.assemble("call 10"), 0, 0), 0)
			(['mov', '     ', 'eax', ', ', '0x0'], 5)
			>>>
		"""
		buf = (ctypes.c_ubyte * len(data))()
		ctypes.memmove(buf, data, len(data))
		if not core.BNArchitectureSkipAndReturnValue(self.handle, buf, addr, len(data), value):
			return None
		result = ctypes.create_string_buffer(len(data))
		ctypes.memmove(result, buf, len(data))
		return result.raw

	def get_flag_role(self, flag: FlagIndex, sem_class: Optional[SemanticClassIndex] = None) -> FlagRole:
		"""
		``get_flag_role`` gets the role of a given flag.

		:param int flag: flag
		:param int sem_class: optional semantic flag class
		:return: flag role
		:rtype: FlagRole
		"""
		flag = self.get_flag_index(flag)
		_sem_class = self.get_semantic_flag_class_index(sem_class)
		return FlagRole(core.BNGetArchitectureFlagRole(self.handle, flag, _sem_class))

	def get_flags_required_for_flag_condition(
	    self, cond: LowLevelILFlagCondition, sem_class: Optional[SemanticClassType] = None
	) -> List[FlagName]:
		_sem_class = self.get_semantic_flag_class_index(sem_class)
		count = ctypes.c_ulonglong()
		flags = core.BNGetArchitectureFlagsRequiredForFlagCondition(self.handle, cond, _sem_class, count)
		assert flags is not None, "core.BNGetArchitectureFlagsRequiredForFlagCondition returned None"
		flag_names = []
		for i in range(0, count.value):
			flag_names.append(self._flags_by_index[flags[i]])
		core.BNFreeRegisterList(flags)
		return flag_names


class ArchitectureHook(CoreArchitecture):
	def __init__(self, base_arch: 'Architecture'):
		self._base_arch = base_arch
		super(ArchitectureHook, self).__init__(base_arch.handle)

		# To improve performance of simpler hooks, use null callback for functions that are not being overridden
		if self.get_associated_arch_by_address.__code__ == CoreArchitecture.get_associated_arch_by_address.__code__:
			self._cb.getAssociatedArchitectureByAddress = self._cb.getAssociatedArchitectureByAddress.__class__()
		if self.get_instruction_info.__code__ == CoreArchitecture.get_instruction_info.__code__:
			self._cb.getInstructionInfo = self._cb.getInstructionInfo.__class__()
		if self.get_instruction_text.__code__ == CoreArchitecture.get_instruction_text.__code__:
			self._cb.getInstructionText = self._cb.getInstructionText.__class__()
		if self.get_instruction_text_with_context.__code__ == CoreArchitecture.get_instruction_text_with_context.__code__:
			self._cb.getInstructionTextWithContext = self._cb.getInstructionTextWithContext.__class__()
		if self.__class__.stack_pointer is None:
			self._cb.getStackPointerRegister = self._cb.getStackPointerRegister.__class__()
		if self.__class__.link_reg is None:
			self._cb.getLinkRegister = self._cb.getLinkRegister.__class__()
		if len(self.__class__.regs) == 0:
			self._cb.getRegisterInfo = self._cb.getRegisterInfo.__class__()
			self._cb.getRegisterName = self._cb.getRegisterName.__class__()
		if len(self.__class__.reg_stacks) == 0:
			self._cb.getRegisterStackName = self._cb.getRegisterStackName.__class__()
			self._cb.getRegisterStackInfo = self._cb.getRegisterStackInfo.__class__()
		if len(self.__class__.intrinsics) == 0:
			self._cb.getIntrinsicClass = self._cb.getIntrinsicClass.__class__()
			self._cb.getIntrinsicName = self._cb.getIntrinsicName.__class__()
			self._cb.getIntrinsicInputs = self._cb.getIntrinsicInputs.__class__()
			self._cb.freeNameAndTypeList = self._cb.freeNameAndTypeList.__class__()
			self._cb.getIntrinsicOutputs = self._cb.getIntrinsicOutputs.__class__()
			self._cb.freeTypeList = self._cb.freeTypeList.__class__()

	def register(self) -> None:
		self.__class__._registered_cb = self._cb
		self.handle = core.BNRegisterArchitectureHook(self._base_arch.handle, self._cb)
		core.BNFinalizeArchitectureHook(self._base_arch.handle)

	@property
	def base_arch(self) -> 'Architecture':
		return self._base_arch

	@base_arch.setter
	def base_arch(self, value: 'Architecture') -> None:
		self._base_arch = value


@dataclass
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**
		StackVariableToken         **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**
		AddressSeparatorToken      **Not emitted by architectures**
		NewLineToken               New lines
		========================== ============================================

	"""
	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] = field(default_factory=list)
	width: int = 0
	il_expr_index: int = 0xffffffffffffffff

	def __post_init__(self):
		if self.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):
				try:
					text = text.decode("utf-8")
				except UnicodeDecodeError:
					text = text.decode("charmap")
			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
			il_expr_index = tokens[j].exprIndex
			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, il_expr_index
			    )
			)
		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))()
			result[j].exprIndex = tokens[j].il_expr_index
			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)