summaryrefslogtreecommitdiff
path: root/python/binaryview.py
blob: 9d095388615109f7f9c97510c8cabfb0e4b1613c (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
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
# coding=utf-8
# Copyright (c) 2015-2020 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 struct
import traceback
import ctypes
import abc
import numbers
import json
import inspect

from collections import OrderedDict

# Binary Ninja components
from binaryninja import _binaryninjacore as core
from binaryninja.enums import (AnalysisState, SymbolType, InstructionTextTokenType,
	Endianness, ModificationStatus, StringType, SegmentFlag, SectionSemantics, FindFlag,
	TypeClass, SaveOption, BinaryViewEventType)
import binaryninja
from binaryninja import associateddatastore # required for _BinaryViewAssociatedDataStore
from binaryninja import log
from binaryninja import types
from binaryninja import typelibrary
from binaryninja import fileaccessor
from binaryninja import databuffer
from binaryninja import basicblock
from binaryninja import lineardisassembly
from binaryninja import metadata
from binaryninja import highlight
from binaryninja import function
from binaryninja import settings
from binaryninja import pyNativeStr

# 2-3 compatibility
from binaryninja import range
from binaryninja import with_metaclass
from binaryninja import cstr

class BinaryDataNotification(object):
	def __init__(self):
		pass

	def data_written(self, view, offset, length):
		pass

	def data_inserted(self, view, offset, length):
		pass

	def data_removed(self, view, offset, length):
		pass

	def function_added(self, view, func):
		pass

	def function_removed(self, view, func):
		pass

	def function_updated(self, view, func):
		pass

	def function_update_requested(self, view, func):
		pass

	def data_var_added(self, view, var):
		pass

	def data_var_removed(self, view, var):
		pass

	def data_var_updated(self, view, var):
		pass

	def data_metadata_updated(self, view, offset):
		pass

	def tag_type_updated(self, view, tag_type):
		pass

	def tag_added(self, view, tag, ref_type, auto_defined, arch, func, addr):
		pass

	def tag_updated(self, view, tag, ref_type, auto_defined, arch, func, addr):
		pass

	def tag_removed(self, view, tag, ref_type, auto_defined, arch, func, addr):
		pass

	def symbol_added(self, view, sym):
		pass

	def symbol_updated(self, view, sym):
		pass

	def symbol_removed(self, view, sym):
		pass

	def string_found(self, view, string_type, offset, length):
		pass

	def string_removed(self, view, string_type, offset, length):
		pass

	def type_defined(self, view, name, type):
		pass

	def type_undefined(self, view, name, type):
		pass

_decodings = {
	StringType.AsciiString: "ascii",
	StringType.Utf8String: "utf-8",
	StringType.Utf16String: "utf-16",
	StringType.Utf32String: "utf-32",
}


class StringReference(object):
	def __init__(self, bv, string_type, start, length):
		self._type = string_type
		self._start = start
		self._length = length
		self._view = bv

	def __repr__(self):
		return "<%s: %#x, len %#x>" % (self._type, self._start, self._length)

	def __str__(self):
		return pyNativeStr(self.raw)

	def __len__(self):
		return self._length

	@property
	def value(self):
		return self._view.read(self._start, self._length).decode(_decodings[self._type])

	@property
	def raw(self):
		return self._view.read(self._start, self._length)

	@property
	def type(self):
		""" """
		return self._type

	@type.setter
	def type(self, value):
		self._type = value

	@property
	def start(self):
		""" """
		return self._start

	@start.setter
	def start(self, value):
		self._start = value

	@property
	def length(self):
		""" """
		return self._length

	@property
	def view(self):
		""" """
		return self._view


_pending_analysis_completion_events = {}
class AnalysisCompletionEvent(object):
	"""
	The ``AnalysisCompletionEvent`` object provides an asynchronous mechanism for receiving
	callbacks when analysis is complete. The callback runs once. A completion event must be added
	for each new analysis in order to be notified of each analysis completion.  The
	AnalysisCompletionEvent class takes responsibility for keeping track of the object's lifetime.

	:Example:
		>>> def on_complete(self):
		...     print("Analysis Complete", self._view)
		...
		>>> evt = AnalysisCompletionEvent(bv, on_complete)
		>>>
	"""
	def __init__(self, view, callback):
		self._view = view
		self.callback = callback
		self._cb = ctypes.CFUNCTYPE(None, ctypes.c_void_p)(self._notify)
		self.handle = core.BNAddAnalysisCompletionEvent(self._view.handle, None, self._cb)
		global _pending_analysis_completion_events
		_pending_analysis_completion_events[id(self)] = self

	def __del__(self):
		global _pending_analysis_completion_events
		if id(self) in _pending_analysis_completion_events:
			del _pending_analysis_completion_events[id(self)]
		core.BNFreeAnalysisCompletionEvent(self.handle)

	def _notify(self, ctxt):
		global _pending_analysis_completion_events
		if id(self) in _pending_analysis_completion_events:
			del _pending_analysis_completion_events[id(self)]
		try:
			arg_offset = inspect.ismethod(self.callback)
			callback_spec = inspect.getargspec(self.callback)
			if len(callback_spec.args) > arg_offset:
				self.callback(self)
			else:
				self.callback()
		except:
			log.log_error(traceback.format_exc())

	def _empty_callback(self):
		pass

	def cancel(self):
		"""
		The ``cancel`` method will cancel analysis for an :class:`AnalysisCompletionEvent`.

		.. warning: This method should only be used when the system is being shut down and no further analysis should be done afterward.

		"""
		self.callback = self._empty_callback
		core.BNCancelAnalysisCompletionEvent(self.handle)
		global _pending_analysis_completion_events
		if id(self) in _pending_analysis_completion_events:
			del _pending_analysis_completion_events[id(self)]

	@property
	def view(self):
		""" """
		return self._view

	@view.setter
	def view(self, value):
		self._view = value

# This has no functional purposes;
# we just need it to stop Python from prematurely freeing the object
_binaryview_events = {}
class BinaryViewEvent(object):
	"""
	The ``BinaryViewEvent`` object provides a mechanism for receiving callbacks	when a BinaryView
	is Finalized or the initial analysis is finished. The BinaryView finalized callbacks run before the
	intialanalysis starts. The callbacks run one-after-another in the same order as they get registered.
	It is a good place to modify the BinaryView to add extra information to it.

	The callback function receives a BinaryView as its parameter. It is possible to call
	BinaryView.add_analysis_completion_event() on it to set up other callbacks for analysis completion.

	:Example:
		>>> def callback(bv):
   		...		print('start: 0x%x' % bv.start)
		...
		>>> BinaryViewEvent.add_binaryview_finalized_event(callback)
	"""
	@classmethod
	def register(cls, event_type, callback):
		callback_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView))(lambda ctxt, view: cls._notify(view, callback))
		core.BNRegisterBinaryViewEvent(event_type, callback_obj, None)
		global _binaryview_events
		_binaryview_events[len(_binaryview_events)] = callback_obj

	@classmethod
	def _notify(cls, view, callback):
		try:
			file_metadata = binaryninja.filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryninja.binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			callback(view_obj)
		except:
			binaryninja.log.log_error(traceback.format_exc())

			
class ActiveAnalysisInfo(object):
	def __init__(self, func, analysis_time, update_count, submit_count):
		self._func = func
		self._analysis_time = analysis_time
		self._update_count = update_count
		self._submit_count = submit_count

	def __repr__(self):
		return "<ActiveAnalysisInfo %s, analysis_time %d, update_count %d, submit_count %d>" % (self._func, self._analysis_time, self._update_count, self._submit_count)

	@property
	def func(self):
		""" """
		return self._func

	@func.setter
	def func(self, value):
		self._func = value

	@property
	def analysis_time(self):
		""" """
		return self._analysis_time

	@analysis_time.setter
	def analysis_time(self, value):
		self._analysis_time = value

	@property
	def update_count(self):
		""" """
		return self._update_count

	@update_count.setter
	def update_count(self, value):
		self._update_count = value

	@property
	def submit_count(self):
		""" """
		return self._submit_count

	@submit_count.setter
	def submit_count(self, value):
		self._submit_count = value


class AnalysisInfo(object):
	def __init__(self, state, analysis_time, active_info):
		self._state = AnalysisState(state)
		self._analysis_time = analysis_time
		self._active_info = active_info

	def __repr__(self):
		return "<AnalysisInfo %s, analysis_time %d, active_info %s>" % (self._state, self._analysis_time, self._active_info)

	@property
	def state(self):
		""" """
		return self._state

	@state.setter
	def state(self, value):
		self._state = value

	@property
	def analysis_time(self):
		""" """
		return self._analysis_time

	@analysis_time.setter
	def analysis_time(self, value):
		self._analysis_time = value

	@property
	def active_info(self):
		""" """
		return self._active_info

	@active_info.setter
	def active_info(self, value):
		self._active_info = value


class AnalysisProgress(object):
	def __init__(self, state, count, total):
		self._state = state
		self._count = count
		self._total = total

	def __str__(self):
		if self._state == AnalysisState.DisassembleState:
			return "Disassembling (%d/%d)" % (self._count, self._total)
		if self._state == AnalysisState.AnalyzeState:
			return "Analyzing (%d/%d)" % (self._count, self._total)
		if self._state == AnalysisState.ExtendedAnalyzeState:
			return "Extended Analysis"
		return "Idle"

	def __repr__(self):
		return "<progress: %s>" % str(self)

	@property
	def state(self):
		""" """
		return self._state

	@state.setter
	def state(self, value):
		self._state = value

	@property
	def count(self):
		""" """
		return self._count

	@count.setter
	def count(self, value):
		self._count = value

	@property
	def total(self):
		""" """
		return self._total

	@total.setter
	def total(self, value):
		self._total = value


class DataVariable(object):
	def __init__(self, addr, var_type, auto_discovered, view=None):
		self._address = addr
		self._type = var_type
		self._auto_discovered = auto_discovered
		self._view = view

	@property
	def data_refs_from(self):
		"""data cross references from this data variable (read-only)"""
		return self._view.get_data_refs_from(self._address, max(1, len(self)))

	@property
	def data_refs(self):
		"""data cross references to this data variable (read-only)"""
		return self._view.get_data_refs(self._address, max(1, len(self)))

	@property
	def code_refs(self):
		"""code references to this data variable (read-only)"""
		return self._view.get_code_refs(self._address, max(1, len(self)))

	def __len__(self):
		return len(self._type)

	def __repr__(self):
		return "<var 0x%x: %s>" % (self._address, str(self._type))

	@property
	def address(self):
		""" """
		return self._address

	@address.setter
	def address(self, value):
		self._address = value

	@property
	def type(self):
		""" """
		return self._type

	@type.setter
	def type(self, value):
		self._type = value

	@property
	def auto_discovered(self):
		""" """
		return self._auto_discovered

	@auto_discovered.setter
	def auto_discovered(self, value):
		self._auto_discovered = value

	@property
	def view(self):
		""" """
		return self._view

	@view.setter
	def view(self, value):
		self._view = value


class BinaryDataNotificationCallbacks(object):
	def __init__(self, view, notify):
		self._view = view
		self._notify = notify
		self._cb = core.BNBinaryDataNotification()
		self._cb.context = 0
		self._cb.dataWritten = self._cb.dataWritten.__class__(self._data_written)
		self._cb.dataInserted = self._cb.dataInserted.__class__(self._data_inserted)
		self._cb.dataRemoved = self._cb.dataRemoved.__class__(self._data_removed)
		self._cb.functionAdded = self._cb.functionAdded.__class__(self._function_added)
		self._cb.functionRemoved = self._cb.functionRemoved.__class__(self._function_removed)
		self._cb.functionUpdated = self._cb.functionUpdated.__class__(self._function_updated)
		self._cb.functionUpdateRequested = self._cb.functionUpdateRequested.__class__(self._function_update_requested)
		self._cb.dataVariableAdded = self._cb.dataVariableAdded.__class__(self._data_var_added)
		self._cb.dataVariableRemoved = self._cb.dataVariableRemoved.__class__(self._data_var_removed)
		self._cb.dataVariableUpdated = self._cb.dataVariableUpdated.__class__(self._data_var_updated)
		self._cb.dataMetadataUpdated = self._cb.dataMetadataUpdated.__class__(self._data_metadata_updated)
		self._cb.tagTypeUpdated = self._cb.tagTypeUpdated.__class__(self._tag_type_updated)
		self._cb.tagAdded = self._cb.tagAdded.__class__(self._tag_added)
		self._cb.tagUpdated = self._cb.tagUpdated.__class__(self._tag_updated)
		self._cb.tagRemoved = self._cb.tagRemoved.__class__(self._tag_removed)
		self._cb.symbolAdded = self._cb.symbolAdded.__class__(self._symbol_added)
		self._cb.symbolUpdated = self._cb.symbolUpdated.__class__(self._symbol_updated)
		self._cb.symbolRemoved = self._cb.symbolRemoved.__class__(self._symbol_removed)
		self._cb.stringFound = self._cb.stringFound.__class__(self._string_found)
		self._cb.stringRemoved = self._cb.stringRemoved.__class__(self._string_removed)
		self._cb.typeDefined = self._cb.typeDefined.__class__(self._type_defined)
		self._cb.typeUndefined = self._cb.typeUndefined.__class__(self._type_undefined)

	def _register(self):
		core.BNRegisterDataNotification(self._view.handle, self._cb)

	def _unregister(self):
		core.BNUnregisterDataNotification(self._view.handle, self._cb)

	def _data_written(self, ctxt, view, offset, length):
		try:
			self._notify.data_written(self._view, offset, length)
		except OSError:
			log.log_error(traceback.format_exc())

	def _data_inserted(self, ctxt, view, offset, length):
		try:
			self._notify.data_inserted(self._view, offset, length)
		except:
			log.log_error(traceback.format_exc())

	def _data_removed(self, ctxt, view, offset, length):
		try:
			self._notify.data_removed(self._view, offset, length)
		except:
			log.log_error(traceback.format_exc())

	def _function_added(self, ctxt, view, func):
		try:
			self._notify.function_added(self._view, binaryninja.function.Function(self._view, core.BNNewFunctionReference(func)))
		except:
			log.log_error(traceback.format_exc())

	def _function_removed(self, ctxt, view, func):
		try:
			self._notify.function_removed(self._view, binaryninja.function.Function(self._view, core.BNNewFunctionReference(func)))
		except:
			log.log_error(traceback.format_exc())

	def _function_updated(self, ctxt, view, func):
		try:
			self._notify.function_updated(self._view, binaryninja.function.Function(self._view, core.BNNewFunctionReference(func)))
		except:
			log.log_error(traceback.format_exc())

	def _function_update_requested(self, ctxt, view, func):
		try:
			self._notify.function_update_requested(self._view, binaryninja.function.Function(self._view, core.BNNewFunctionReference(func)))
		except:
			log.log_error(traceback.format_exc())

	def _data_var_added(self, ctxt, view, var):
		try:
			address = var[0].address
			var_type = types.Type(core.BNNewTypeReference(var[0].type), platform = self._view.platform, confidence = var[0].typeConfidence)
			auto_discovered = var[0].autoDiscovered
			self._notify.data_var_added(self._view, DataVariable(address, var_type, auto_discovered, self._view))
		except:
			log.log_error(traceback.format_exc())

	def _data_var_removed(self, ctxt, view, var):
		try:
			address = var[0].address
			var_type = types.Type(core.BNNewTypeReference(var[0].type), platform = self._view.platform, confidence = var[0].typeConfidence)
			auto_discovered = var[0].autoDiscovered
			self._notify.data_var_removed(self._view, DataVariable(address, var_type, auto_discovered, self._view))
		except:
			log.log_error(traceback.format_exc())

	def _data_var_updated(self, ctxt, view, var):
		try:
			address = var[0].address
			var_type = types.Type(core.BNNewTypeReference(var[0].type), platform = self._view.platform, confidence = var[0].typeConfidence)
			auto_discovered = var[0].autoDiscovered
			self._notify.data_var_updated(self._view, DataVariable(address, var_type, auto_discovered, self._view))
		except:
			log.log_error(traceback.format_exc())

	def _data_metadata_updated(self, ctxt, view, offset):
		try:
			self._notify.data_metadata_updated(self._view, offset)
		except:
			log.log_error(traceback.format_exc())

	def _tag_type_updated(self, ctxt, view, tag_type):
		try:
			self._notify.tag_type_updated(self._view, TagType(core.BNNewTagTypeReference(tag_type)))
		except:
			log.log_error(traceback.format_exc())

	def _tag_added(self, ctxt, view, tag_ref):
		try:
			ref_type = tag_ref[0].refType
			auto_defined = tag_ref[0].autoDefined
			tag = tag_ref[0].tag
			arch = tag_ref[0].arch
			func = tag_ref[0].func
			addr = tag_ref[0].addr
			self._notify.tag_added(self._view, Tag(core.BNNewTagReference(tag)), ref_type, auto_defined, arch, func, addr)
		except:
			log.log_error(traceback.format_exc())

	def _tag_updated(self, ctxt, view, tag_ref):
		try:
			ref_type = tag_ref[0].refType
			auto_defined = tag_ref[0].autoDefined
			tag = tag_ref[0].tag
			arch = tag_ref[0].arch
			func = tag_ref[0].func
			addr = tag_ref[0].addr
			self._notify.tag_updated(self._view, Tag(core.BNNewTagReference(tag)), ref_type, auto_defined, arch, func, addr)
		except:
			log.log_error(traceback.format_exc())

	def _tag_removed(self, ctxt, view, tag_ref):
		try:
			ref_type = tag_ref[0].refType
			auto_defined = tag_ref[0].autoDefined
			tag = tag_ref[0].tag
			arch = tag_ref[0].arch
			func = tag_ref[0].func
			addr = tag_ref[0].addr
			self._notify.tag_removed(self._view, Tag(core.BNNewTagReference(tag)), ref_type, auto_defined, arch, func, addr)
		except:
			log.log_error(traceback.format_exc())

	def _symbol_added(self, ctxt, view, sym):
		try:
			self._notify.symbol_added(self._view, types.Symbol(None, None, None, handle = core.BNNewSymbolReference(sym)))
		except:
			log.log_error(traceback.format_exc())

	def _symbol_updated(self, ctxt, view, sym):
		try:
			self._notify.symbol_updated(self._view, types.Symbol(None, None, None, handle = core.BNNewSymbolReference(sym)))
		except:
			log.log_error(traceback.format_exc())

	def _symbol_removed(self, ctxt, view, sym):
		try:
			self._notify.symbol_removed(self._view, types.Symbol(None, None, None, handle = core.BNNewSymbolReference(sym)))
		except:
			log.log_error(traceback.format_exc())

	def _string_found(self, ctxt, view, string_type, offset, length):
		try:
			self._notify.string_found(self._view, StringType(string_type), offset, length)
		except:
			log.log_error(traceback.format_exc())

	def _string_removed(self, ctxt, view, string_type, offset, length):
		try:
			self._notify.string_removed(self._view, StringType(string_type), offset, length)
		except:
			log.log_error(traceback.format_exc())

	def _type_defined(self, ctxt, view, name, type_obj):
		try:
			qualified_name = types.QualifiedName._from_core_struct(name[0])
			self._notify.type_defined(self._view, qualified_name, types.Type(core.BNNewTypeReference(type_obj), platform = self._view.platform))
		except:
			log.log_error(traceback.format_exc())

	def _type_undefined(self, ctxt, view, name, type_obj):
		try:
			qualified_name = types.QualifiedName._from_core_struct(name[0])
			self._notify.type_undefined(self._view, qualified_name, types.Type(core.BNNewTypeReference(type_obj), platform = self._view.platform))
		except:
			log.log_error(traceback.format_exc())

	@property
	def view(self):
		""" """
		return self._view

	@view.setter
	def view(self, value):
		self._view = value

	@property
	def notify(self):
		""" """
		return self._notify

	@notify.setter
	def notify(self, value):
		self._notify = value


class _BinaryViewTypeMetaclass(type):

	@property
	def list(self):
		"""List all BinaryView types (read-only)"""
		binaryninja._init_plugins()
		count = ctypes.c_ulonglong()
		types = core.BNGetBinaryViewTypes(count)
		result = []
		for i in range(0, count.value):
			result.append(BinaryViewType(types[i]))
		core.BNFreeBinaryViewTypeList(types)
		return result

	def __iter__(self):
		binaryninja._init_plugins()
		count = ctypes.c_ulonglong()
		types = core.BNGetBinaryViewTypes(count)
		try:
			for i in range(0, count.value):
				yield BinaryViewType(types[i])
		finally:
			core.BNFreeBinaryViewTypeList(types)

	def __getitem__(self, value):
		binaryninja._init_plugins()
		view_type = core.BNGetBinaryViewTypeByName(str(value))
		if view_type is None:
			raise KeyError("'%s' is not a valid view type" % str(value))
		return BinaryViewType(view_type)


class BinaryViewType(with_metaclass(_BinaryViewTypeMetaclass, object)):

	def __init__(self, handle):
		self.handle = core.handle_of_type(handle, core.BNBinaryViewType)

	def __repr__(self):
		return "<view type: '%s'>" % 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))

	@property
	def list(self):
		"""Allow tab completion to discover metaclass list property"""
		pass

	@property
	def name(self):
		"""BinaryView name (read-only)"""
		return core.BNGetBinaryViewTypeName(self.handle)

	@property
	def long_name(self):
		"""BinaryView long name (read-only)"""
		return core.BNGetBinaryViewTypeLongName(self.handle)

	@property
	def is_deprecated(self):
		"""returns if the BinaryViewType is deprecated (read-only)"""
		return core.BNIsBinaryViewTypeDeprecated(self.handle)

	def create(self, data):
		view = core.BNCreateBinaryViewOfType(self.handle, data.handle)
		if view is None:
			return None
		return BinaryView(file_metadata=data.file, handle=view)

	def open(self, src, file_metadata=None):
		"""
		``open`` opens an instance of a particular BinaryViewType and returns it, or None if not possible.

		:param str src: path to filename or bndb to open
		:param FileMetadata file_metadata: Optional parameter for a :py:class:`FileMetadata` object
		:return: returns a :py:class:`BinaryView` object for the given filename
		:rtype: :py:class:`BinaryView` or ``None``
		"""

		data = BinaryView.open(src, file_metadata)
		if data is None:
			return None
		return self.create(data)

	@classmethod
	def get_view_of_file(cls, filename, update_analysis=True, progress_func=None):
		"""
		``get_view_of_file`` opens and returns the first available :py:class:`BinaryView`, excluding a Raw :py:class:`BinaryViewType` unless no other view is available

		:param str filename: path to filename or bndb to open
		:param bool update_analysis: whether or not to run :func:`update_analysis_and_wait` after opening a :py:class:`BinaryView`, defaults to ``True``
		:param callback progress_func: optional function to be called with the current progress and total count
		:return: returns a :py:class:`BinaryView` object for the given filename
		:rtype: :py:class:`BinaryView` or ``None``
		"""
		sqlite = b"SQLite format 3"
		if not isinstance(filename, str):
			filename = str(filename)

		isDatabase = filename.endswith(".bndb")
		if isDatabase:
			f = open(filename, 'rb')
			if f is None or f.read(len(sqlite)) != sqlite:
				return None
			f.close()
			view = binaryninja.filemetadata.FileMetadata().open_existing_database(filename, progress_func)
		else:
			view = BinaryView.open(filename)

		if view is None:
			return None
		for available in view.available_view_types:
			if available.name != "Raw":
				if isDatabase:
					bv = view.get_view_of_type(available.name)
				else:
					bv = available.open(filename)
				break
		else:
			if isDatabase:
				bv = view.get_view_of_type("Raw")
			else:
				bv = cls["Raw"].open(filename)

		if bv is not None and update_analysis:
			bv.update_analysis_and_wait()
		return bv

	@classmethod
	def get_view_of_file_with_options(cls, filename, update_analysis=True, progress_func=None, options={}):
		"""
		``get_view_of_file_with_options`` opens, generates default load options (which are overridable), and returns the first available \
		:py:class:`BinaryView`. If no :py:class:`BinaryViewType` is available, then a ``Mapped`` :py:class:`BinaryViewType` is used to load \
		the :py:class:`BinaryView` with the specified load options. The ``Mapped`` view type attempts to auto-detect the architecture of the \
		file during initialization. If no architecture is detected or specified in the load options, then the ``Mapped`` view type fails to \
		initialize and returns ``None``.

		.. note:: Calling this method without providing options is not necessarily equivalent to simply calling :func:`get_view_of_file`. This is because \
		a :py:class:`BinaryViewType` is in control of generating load options, this method allows an alternative default way to open a file. For \
		example, opening a relocatable object file with :func:`get_view_of_file` sets 'loader.imageBase' to `0`, whereas opening with \
		:func:`get_view_of_file_with_options` sets **'loader.imageBase'** to ``0x400000`` for 64-bit binaries, or ``0x10000`` for 32-bit binaries, by default.

		:param str filename: path to filename or bndb to open
		:param bool update_analysis: whether or not to run :func:`update_analysis_and_wait` after opening a :py:class:`BinaryView`, defaults to ``True``
		:param callback progress_func: optional function to be called with the current progress and total count
		:param dict options: a dictionary in the form {setting identifier string : object value}
		:return: returns a :py:class:`BinaryView` object for the given filename or ``None``
		:rtype: :py:class:`BinaryView` or ``None``

		:Example:

			>>> BinaryViewType.get_view_of_file_with_options('/bin/ls', options={'loader.imageBase': 0xfffffff0000, 'loader.macho.processFunctionStarts' : False})
			<BinaryView: '/bin/ls', start 0xfffffff0000, len 0xa290>
			>>>
		"""
		sqlite = b"SQLite format 3"
		isDatabase = filename.endswith(".bndb")
		if isDatabase:
			f = open(filename, 'rb')
			if f is None or f.read(len(sqlite)) != sqlite:
				return None
			f.close()
			view = binaryninja.filemetadata.FileMetadata().open_database_for_configuration(filename)
		else:
			view = BinaryView.open(filename)

		if view is None:
			return None
		bvt = None
		for available in view.available_view_types:
			if available.name != "Raw":
				bvt = available
				break

		if bvt is None:
			bvt = cls["Mapped"]

		default_settings = settings.Settings(bvt.name + "_settings")
		default_settings.deserialize_schema(settings.Settings().serialize_schema())
		default_settings.set_resource_id(bvt.name)

		load_settings = None
		if isDatabase:
			load_settings = view.get_load_settings(bvt.name)
		if load_settings is None:
			load_settings = bvt.get_load_settings_for_data(view)
		if load_settings is None:
			log.log_error(f"Could not get load settings for binary view of type `{bvt.name}`")
			return view
		load_settings.set_resource_id(bvt.name)
		view.set_load_settings(bvt.name, load_settings)

		for key, value in options.items():
			if load_settings.contains(key):
				if not load_settings.set_json(key, json.dumps(value), view):
					raise ValueError("Setting: {} set operation failed!".format(key))
			elif default_settings.contains(key):
				if not default_settings.set_json(key, json.dumps(value), view):
					raise ValueError("Setting: {} set operation failed!".format(key))
			else:
				raise NotImplementedError("Setting: {} not available!".format(key))

		if isDatabase:
			view = view.file.open_existing_database(filename, progress_func)
			bv = view.get_view_of_type(bvt.name)
		else:
			bv = bvt.create(view)

		if bv is None:
			return view
		elif update_analysis:
			bv.update_analysis_and_wait()
		return bv

	def parse(self, data):
		view = core.BNParseBinaryViewOfType(self.handle, data.handle)
		if view is None:
			return None
		return BinaryView(file_metadata=data.file, handle=view)

	def is_valid_for_data(self, data):
		return core.BNIsBinaryViewTypeValidForData(self.handle, data.handle)

	def get_default_load_settings_for_data(self, data):
		load_settings = core.BNGetBinaryViewDefaultLoadSettingsForData(self.handle, data.handle)
		if load_settings is None:
			return None
		return settings.Settings(handle=load_settings)

	def get_load_settings_for_data(self, data):
		view_handle = None
		if data is not None:
			view_handle = data.handle
		load_settings = core.BNGetBinaryViewLoadSettingsForData(self.handle, view_handle)
		if load_settings is None:
			return None
		return settings.Settings(handle=load_settings)

	def register_arch(self, ident, endian, arch):
		core.BNRegisterArchitectureForViewType(self.handle, ident, endian, arch.handle)

	def get_arch(self, ident, endian):
		arch = core.BNGetArchitectureForViewType(self.handle, ident, endian)
		if arch is None:
			return None
		return binaryninja.architecture.CoreArchitecture._from_cache(arch)

	def register_platform(self, ident, arch, plat):
		core.BNRegisterPlatformForViewType(self.handle, ident, arch.handle, plat.handle)

	def register_default_platform(self, arch, plat):
		core.BNRegisterDefaultPlatformForViewType(self.handle, arch.handle, plat.handle)

	def get_platform(self, ident, arch):
		plat = core.BNGetPlatformForViewType(self.handle, ident, arch.handle)
		if plat is None:
			return None
		return binaryninja.platform.Platform(handle = plat)

	@staticmethod
	def add_binaryview_finalized_event(callback):
		BinaryViewEvent.register(BinaryViewEventType.BinaryViewFinalizationEvent, callback)

	@staticmethod
	def add_binaryview_initial_analysis_completion_event(callback):
		BinaryViewEvent.register(BinaryViewEventType.BinaryViewInitialAnalysisCompletionEvent, callback)


class Segment(object):
	def __init__(self, handle):
		self.handle = handle

	def __del__(self):
		core.BNFreeSegment(self.handle)

	def __repr__(self):
		return "<segment: %#x-%#x, %s%s%s>" % (self.start, self.end,
			"r" if self.readable else "-",
			"w" if self.writable else "-",
			"x" if self.executable else "-")

	def __len__(self):
		return core.BNSegmentGetLength(self.handle)

	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))

	@property
	def start(self):
		return core.BNSegmentGetStart(self.handle)

	@property
	def end(self):
		return core.BNSegmentGetEnd(self.handle)

	@property
	def executable(self):
		return (core.BNSegmentGetFlags(self.handle) & SegmentFlag.SegmentExecutable) != 0

	@property
	def writable(self):
		return (core.BNSegmentGetFlags(self.handle) & SegmentFlag.SegmentWritable) != 0

	@property
	def readable(self):
		return (core.BNSegmentGetFlags(self.handle) & SegmentFlag.SegmentReadable) != 0

	@property
	def data_length(self):
		return core.BNSegmentGetDataLength(self.handle)

	@property
	def data_offset(self):
		return core.BNSegmentGetDataOffset(self.handle)

	@property
	def data_end(self):
		return core.BNSegmentGetDataEnd(self.handle)

	@property
	def relocation_count(self):
		return core.BNSegmentGetRelocationsCount(self.handle)

	@property
	def auto_defined(self):
		return core.BNSegmentIsAutoDefined(self.handle)

	@property
	def relocation_ranges(self):
		"""List of relocation range tuples (read-only)"""

		count = ctypes.c_ulonglong()
		ranges = core.BNSegmentGetRelocationRanges(self.handle, count)
		result = []
		for i in range(0, count.value):
			result.append((ranges[i].start, ranges[i].end))
		core.BNFreeRelocationRanges(ranges, count)
		return result

	def relocation_ranges_at(self, addr):
		"""List of relocation range tuples (read-only)"""

		count = ctypes.c_ulonglong()
		ranges = core.BNSegmentGetRelocationRangesAtAddress(self.handle, addr, count)
		result = []
		for i in range(0, count.value):
			result.append((ranges[i].start, ranges[i].end))
		core.BNFreeRelocationRanges(ranges, count)
		return result



class Section(object):
	def __init__(self, handle):
		self.handle = core.handle_of_type(handle, core.BNSection)

	def __del__(self):
		core.BNFreeSection(self.handle)

	def __repr__(self):
		return "<section %s: %#x-%#x>" % (self.name, self.start, self.end)

	def __len__(self):
		return core.BNSectionGetLength(self.handle)

	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))

	@property
	def name(self):
		return core.BNSectionGetName(self.handle)

	@property
	def type(self):
		return core.BNSectionGetType(self.handle)

	@property
	def start(self):
		return core.BNSectionGetStart(self.handle)

	@property
	def linked_section(self):
		return core.BNSectionGetLinkedSection(self.handle)

	@property
	def info_section(self):
		return core.BNSectionGetInfoSection(self.handle)

	@property
	def info_data(self):
		return core.BNSectionGetInfoData(self.handle)

	@property
	def align(self):
		return core.BNSectionGetAlign(self.handle)

	@property
	def entry_size(self):
		return core.BNSectionGetEntrySize(self.handle)

	@property
	def semantics(self):
		return SectionSemantics(core.BNSectionGetSemantics(self.handle))

	@property
	def auto_defined(self):
		return core.BNSectionIsAutoDefined(self.handle)

	@property
	def end(self):
		return self.start + len(self)


class AddressRange(object):
	def __init__(self, start, end):
		self._start = start
		self._end = end

	def __repr__(self):
		return "<%#x-%#x>" % (self._start, self._end)

	def __len__(self):
		return self._end - self.start

	def __eq__(self, other):
		if not isinstance(other, self.__class__):
			return NotImplemented
		return (self._start, self._end) == (other._start, other._end)

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

	def __hash__(self):
		return hash((self._start, self._end))

	@property
	def length(self):
		return self._end - self._start

	@property
	def start(self):
		""" """
		return self._start

	@start.setter
	def start(self, value):
		self._start = value

	@property
	def end(self):
		""" """
		return self._end

	@end.setter
	def end(self, value):
		self._end = value


class TagType(object):
	def __init__(self, handle):
		self.handle = core.handle_of_type(handle, core.BNTagType)

	def __del__(self):
		core.BNFreeTagType(self.handle)

	def __repr__(self):
		return "<tag type %s: %s>" % (self.name, self.icon)

	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))

	@property
	def name(self):
		"""Name of the TagType"""
		return core.BNTagTypeGetName(self.handle)

	@name.setter
	def name(self, value):
		core.BNTagTypeSetName(self.handle, value)

	@property
	def icon(self):
		"""Unicode str containing an emoji to be used as an icon"""
		return core.BNTagTypeGetIcon(self.handle)

	@icon.setter
	def icon(self, value):
		core.BNTagTypeSetIcon(self.handle, value)

	@property
	def visible(self):
		"""Boolean for whether the tags of this type are visible"""
		return core.BNTagTypeGetVisible(self.handle)

	@visible.setter
	def visible(self, value):
		core.BNTagTypeSetVisible(self.handle, value)

	@property
	def type(self):
		"""Type from enums.TagTypeType"""
		return core.BNTagTypeGetType(self.handle)

	@type.setter
	def type(self, value):
		core.BNTagTypeSetType(self.handle, value)



class Tag(object):
	def __init__(self, handle):
		self.handle = core.handle_of_type(handle, core.BNTag)

	def __del__(self):
		core.BNFreeTag(self.handle)

	def __repr__(self):
		return "<tag %s %s: %s>" % (self.type.icon, self.type.name, self.data)

	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))

	@property
	def type(self):
		return TagType(core.BNTagGetType(self.handle))

	@property
	def data(self):
		return core.BNTagGetData(self.handle)

	@data.setter
	def data(self, value):
		core.BNTagSetData(self.handle, value)


class _BinaryViewAssociatedDataStore(associateddatastore._AssociatedDataStore):
	_defaults = {}


class BinaryView(object):
	"""
	``class BinaryView`` implements a view on binary data, and presents a queryable interface of a binary file. One key
	job of BinaryView is file format parsing which allows Binary Ninja to read, write, insert, remove portions
	of the file given a virtual address. For the purposes of this documentation we define a virtual address as the
	memory address that the various pieces of the physical file will be loaded at.

	A binary file does not have to have just one BinaryView, thus much of the interface to manipulate disassembly exists
	within or is accessed through a BinaryView. All files are guaranteed to have at least the ``Raw`` BinaryView. The
	``Raw`` BinaryView is simply a hex editor, but is helpful for manipulating binary files via their absolute addresses.

	BinaryViews are plugins and thus registered with Binary Ninja at startup, and thus should **never** be instantiated
	directly as this is already done. The list of available BinaryViews can be seen in the BinaryViewType class which
	provides an iterator and map of the various installed BinaryViews::

		>>> list(BinaryViewType)
		[<view type: 'Raw'>, <view type: 'ELF'>, <view type: 'Mach-O'>, <view type: 'PE'>]
		>>> BinaryViewType['ELF']
		<view type: 'ELF'>

	To open a file with a given BinaryView the following code can be used::

		>>> bv = BinaryViewType.get_view_of_file("/bin/ls")
		>>> bv
		<BinaryView: '/bin/ls', start 0x100000000, len 0xa000>

	`By convention in the rest of this document we will use bv to mean an open BinaryView of an executable file.`
	When a BinaryView is open on an executable view, analysis does not automatically run, this can be done by running
	the :func:`update_analysis_and_wait` method which disassembles the executable and returns when all disassembly is
	finished::

		>>> bv.update_analysis_and_wait()
		>>>

	Since BinaryNinja's analysis is multi-threaded (depending on version) this can also be done in the background by
	using the :func:`update_analysis` method instead.

	By standard python convention methods which start with '_' should be considered private and should not be called
	externally. Additionally, methods which begin with ``perform_`` should not be called either and are
	used explicitly for subclassing the BinaryView.

	.. note:: An important note on the ``*_user_*()`` methods. Binary Ninja makes a distinction between edits \
	performed by the user and actions performed by auto analysis.  Auto analysis actions that can quickly be recalculated \
	are not saved to the database. Auto analysis actions that take a long time and all user edits are stored in the \
	database (e.g. :func:`remove_user_function` rather than :func:`remove_function`). Thus use ``_user_`` methods if saving \
	to the database is desired.
	"""
	name = None
	long_name = None
	_registered = False
	_registered_cb = None
	registered_view_type = None
	_next_address = 0
	_associated_data = {}
	_registered_instances = []

	def __init__(self, file_metadata=None, parent_view=None, handle=None):
		if handle is not None:
			self.handle = core.handle_of_type(handle, core.BNBinaryView)
			if file_metadata is None:
				self._file = binaryninja.filemetadata.FileMetadata(handle=core.BNGetFileForView(handle))
			else:
				self._file = file_metadata
		elif self.__class__ is BinaryView:
			binaryninja._init_plugins()
			if file_metadata is None:
				file_metadata = binaryninja.filemetadata.FileMetadata()
			self.handle = core.BNCreateBinaryDataView(file_metadata.handle)
			self._file = binaryninja.filemetadata.FileMetadata(handle=core.BNNewFileReference(file_metadata.handle))
		else:
			binaryninja._init_plugins()
			if not self.__class__._registered:
				raise TypeError("view type not registered")
			self._cb = core.BNCustomBinaryView()
			self._cb.context = 0
			self._cb.init = self._cb.init.__class__(self._init)
			self._cb.externalRefTaken = self._cb.externalRefTaken.__class__(self._external_ref_taken)
			self._cb.externalRefReleased = self._cb.externalRefReleased.__class__(self._external_ref_released)
			self._cb.read = self._cb.read.__class__(self._read)
			self._cb.write = self._cb.write.__class__(self._write)
			self._cb.insert = self._cb.insert.__class__(self._insert)
			self._cb.remove = self._cb.remove.__class__(self._remove)
			self._cb.getModification = self._cb.getModification.__class__(self._get_modification)
			self._cb.isValidOffset = self._cb.isValidOffset.__class__(self._is_valid_offset)
			self._cb.isOffsetReadable = self._cb.isOffsetReadable.__class__(self._is_offset_readable)
			self._cb.isOffsetWritable = self._cb.isOffsetWritable.__class__(self._is_offset_writable)
			self._cb.isOffsetExecutable = self._cb.isOffsetExecutable.__class__(self._is_offset_executable)
			self._cb.getNextValidOffset = self._cb.getNextValidOffset.__class__(self._get_next_valid_offset)
			self._cb.getStart = self._cb.getStart.__class__(self._get_start)
			self._cb.getLength = self._cb.getLength.__class__(self._get_length)
			self._cb.getEntryPoint = self._cb.getEntryPoint.__class__(self._get_entry_point)
			self._cb.isExecutable = self._cb.isExecutable.__class__(self._is_executable)
			self._cb.getDefaultEndianness = self._cb.getDefaultEndianness.__class__(self._get_default_endianness)
			self._cb.isRelocatable = self._cb.isRelocatable.__class__(self._is_relocatable)
			self._cb.getAddressSize = self._cb.getAddressSize.__class__(self._get_address_size)
			self._cb.save = self._cb.save.__class__(self._save)
			self._file = file_metadata
			if parent_view is not None:
				parent_view = parent_view.handle
			self.handle = core.BNCreateCustomBinaryView(self.__class__.name, file_metadata.handle, parent_view, self._cb)
		self._notifications = {}
		self._next_address = None  # Do NOT try to access view before init() is called, use placeholder

	def __enter__(self):
		return self

	def __exit__(self, type, value, traceback):
		self.file.close()

	def __del__(self):
		for i in self.notifications.values():
			i._unregister()
		core.BNFreeBinaryView(self.handle)

	def __repr__(self):
		start = self.start
		length = len(self)
		if start != 0:
			size = "start %#x, len %#x" % (start, length)
		else:
			size = "len %#x" % length
		filename = self._file.filename
		if len(filename) > 0:
			return "<BinaryView: '%s', %s>" % (filename, size)
		return "<BinaryView: %s>" % (size)

	def __len__(self):
		return int(core.BNGetViewLength(self.handle))

	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 __iter__(self):
		count = ctypes.c_ulonglong(0)
		funcs = core.BNGetAnalysisFunctionList(self.handle, count)
		try:
			for i in range(0, count.value):
				yield binaryninja.function.Function(self, core.BNNewFunctionReference(funcs[i]))
		finally:
			core.BNFreeFunctionList(funcs, count.value)


	def __getitem__(self, i):
		if isinstance(i, tuple):
			result = bytes()
			for s in i:
				result += self.__getitem__(s)
			return result
		elif isinstance(i, slice):
			if i.step is not None:
				raise IndexError("step not implemented")
			i = i.indices(self.end)
			start = i[0]
			stop = i[1]
			if stop <= start:
				return ""
			return self.read(start, stop - start)
		elif i < 0:
			if i >= -len(self):
				value = self.read(int(len(self) + i), 1)
				if len(value) == 0:
					return IndexError("index not readable")
				return value
			raise IndexError("index out of range")
		elif (i >= self.start) and (i < self.end):
			value = self.read(int(i), 1)
			if len(value) == 0:
				return IndexError("index not readable")
			return value
		else:
			raise IndexError("index out of range")

	def __setitem__(self, i, value):
		if isinstance(i, slice):
			if i.step is not None:
				raise IndexError("step not supported on assignment")
			i = i.indices(self.end)
			start = i[0]
			stop = i[1]
			if stop < start:
				stop = start
			if len(value) != (stop - start):
				self.remove(start, stop - start)
				self.insert(start, value)
			else:
				self.write(start, value)
		elif i < 0:
			if i >= -len(self):
				if len(value) != 1:
					raise ValueError("expected single byte for assignment")
				if self.write(int(len(self) + i), value) != 1:
					raise IndexError("index not writable")
			else:
				raise IndexError("index out of range")
		elif (i >= self.start) and (i < self.end):
			if len(value) != 1:
				raise ValueError("expected single byte for assignment")
			if self.write(int(i), value) != 1:
				raise IndexError("index not writable")
		else:
			raise IndexError("index out of range")

	@classmethod
	def register(cls):
		binaryninja._init_plugins()
		if cls.name is None:
			raise ValueError("view 'name' not defined")
		if cls.long_name is None:
			cls.long_name = cls.name
		cls._registered_cb = core.BNCustomBinaryViewType()
		cls._registered_cb.context = 0
		cls._registered_cb.create = cls._registered_cb.create.__class__(cls._create)
		cls._registered_cb.parse = cls._registered_cb.parse.__class__(cls._parse)
		cls._registered_cb.isValidForData = cls._registered_cb.isValidForData.__class__(cls._is_valid_for_data)
		cls._registered_cb.getLoadSettingsForData = cls._registered_cb.getLoadSettingsForData.__class__(cls._get_load_settings_for_data)
		cls.registered_view_type = BinaryViewType(core.BNRegisterBinaryViewType(cls.name, cls.long_name, cls._registered_cb))
		cls._registered = True

	@classmethod
	def _create(cls, ctxt, data):
		try:
			file_metadata = binaryninja.filemetadata.FileMetadata(handle=core.BNGetFileForView(data))
			view = cls(BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(data)))
			if view is None:
				return None
			# FIXME: There is probably a better way to convey this information...
			view.__dict__.update({'parse_only' : False})
			return ctypes.cast(core.BNNewViewReference(view.handle), ctypes.c_void_p).value
		except:
			log.log_error(traceback.format_exc())
			return None

	@classmethod
	def _parse(cls, ctxt, data):
		try:
			file_metadata = binaryninja.filemetadata.FileMetadata(handle=core.BNGetFileForView(data))
			view = cls(BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(data)))
			if view is None:
				return None
			# FIXME: There is probably a better way to convey this information...
			view.__dict__.update({'parse_only' : True})
			return ctypes.cast(core.BNNewViewReference(view.handle), ctypes.c_void_p).value
		except:
			log.log_error(traceback.format_exc())
			return None

	@classmethod
	def _is_valid_for_data(cls, ctxt, data):
		try:
			return cls.is_valid_for_data(BinaryView(handle=core.BNNewViewReference(data)))
		except:
			log.log_error(traceback.format_exc())
			return False

	@classmethod
	def _get_load_settings_for_data(cls, ctxt, data):
		try:
			attr = getattr(cls, "get_load_settings_for_data", None)
			if callable(attr):
				result = cls.get_load_settings_for_data(BinaryView(handle=core.BNNewViewReference(data)))
				return ctypes.cast(core.BNNewSettingsReference(result.handle), ctypes.c_void_p).value
			else:
				return None
		except:
			log.log_error(traceback.format_exc())
			return None

	@classmethod
	def open(cls, src, file_metadata=None):
		binaryninja._init_plugins()
		if isinstance(src, fileaccessor.FileAccessor):
			if file_metadata is None:
				file_metadata = binaryninja.filemetadata.FileMetadata()
			view = core.BNCreateBinaryDataViewFromFile(file_metadata.handle, src._cb)
		else:
			if file_metadata is None:
				file_metadata = binaryninja.filemetadata.FileMetadata(str(src))
			view = core.BNCreateBinaryDataViewFromFilename(file_metadata.handle, str(src))
		if view is None:
			return None
		result = BinaryView(file_metadata=file_metadata, handle=view)
		return result

	@classmethod
	def new(cls, data=None, file_metadata=None):
		binaryninja._init_plugins()
		if file_metadata is None:
			file_metadata = binaryninja.filemetadata.FileMetadata()
		if data is None:
			view = core.BNCreateBinaryDataView(file_metadata.handle)
		else:
			buf = databuffer.DataBuffer(data)
			view = core.BNCreateBinaryDataViewFromBuffer(file_metadata.handle, buf.handle)
		if view is None:
			return None
		result = BinaryView(file_metadata=file_metadata, handle=view)
		return result

	@classmethod
	def _unregister(cls, view):
		handle = ctypes.cast(view, ctypes.c_void_p)
		if handle.value in cls._associated_data:
			del cls._associated_data[handle.value]

	@classmethod
	def set_default_session_data(cls, name, value):
		"""
		``set_default_session_data`` saves a variable to the BinaryView.
		:param str name: name of the variable to be saved
		:param str value: value of the variable to be saved

		:Example:
			>>> BinaryView.set_default_session_data("variable_name", "value")
			>>> bv.session_data.variable_name
			'value'
		"""
		_BinaryViewAssociatedDataStore.set_default(name, value)

	@property
	def basic_blocks(self):
		"""A generator of all BasicBlock objects in the BinaryView"""
		for func in self:
			for block in func.basic_blocks:
				yield block

	@property
	def llil_basic_blocks(self):
		"""A generator of all LowLevelILBasicBlock objects in the BinaryView"""
		for func in self:
			for il_block in func.low_level_il.basic_blocks:
				yield il_block

	@property
	def mlil_basic_blocks(self):
		"""A generator of all MediumLevelILBasicBlock objects in the BinaryView"""
		for func in self:
			for il_block in func.mlil.basic_blocks:
				yield il_block

	@property
	def hlil_basic_blocks(self):
		"""A generator of all HighLevelILBasicBlock objects in the BinaryView"""
		for func in self:
			for il_block in func.hlil.basic_blocks:
				yield il_block

	@property
	def instructions(self):
		"""A generator of instruction tokens and their start addresses"""
		for block in self.basic_blocks:
			start = block.start
			for i in block:
				yield (i[0], start)
				start += i[1]

	@property
	def llil_instructions(self):
		"""A generator of llil instructions"""
		for block in self.llil_basic_blocks:
			for i in block:
				yield i

	@property
	def mlil_instructions(self):
		"""A generator of mlil instructions"""
		for block in self.mlil_basic_blocks:
			for i in block:
				yield i

	@property
	def hlil_instructions(self):
		"""A generator of hlil instructions"""
		for block in self.hlil_basic_blocks:
			for i in block:
				yield i

	@property
	def parent_view(self):
		"""View that contains the raw data used by this view (read-only)"""
		result = core.BNGetParentView(self.handle)
		if result is None:
			return None
		return BinaryView(handle=result)

	@property
	def modified(self):
		"""boolean modification state of the BinaryView (read/write)"""
		return self._file.modified

	@modified.setter
	def modified(self, value):
		self._file.modified = value

	@property
	def analysis_changed(self):
		"""boolean analysis state changed of the currently running analysis (read-only)"""
		return self._file.analysis_changed

	@property
	def has_database(self):
		"""boolean has a database been written to disk (read-only)"""
		return self._file.has_database

	@property
	def view(self):
		return self._file.view

	@view.setter
	def view(self, value):
		self._file.view = value

	@property
	def offset(self):
		return self._file.offset

	@offset.setter
	def offset(self, value):
		self._file.offset = value

	@property
	def file(self):
		""":py:class:`FileMetadata` backing the BinaryView """
		return self._file

	@file.setter
	def file(self, value):
		self._file = value

	@property
	def notifications(self):
		return self._notifications

	@notifications.setter
	def notifications(self, value):
		self._notifications = value

	@property
	def next_address(self):
		""":py:class:`FileMetadata` backing the BinaryView """
		return self._next_address

	@next_address.setter
	def next_address(self, value):
		self._next_address = value

	@property
	def start(self):
		"""Start offset of the binary (read-only)"""
		return core.BNGetStartOffset(self.handle)

	@property
	def end(self):
		"""End offset of the binary (read-only)"""
		return core.BNGetEndOffset(self.handle)

	@property
	def entry_point(self):
		"""Entry point of the binary (read-only)"""
		return core.BNGetEntryPoint(self.handle)

	@property
	def arch(self):
		"""The architecture associated with the current :py:class:`BinaryView` (read/write)"""
		arch = core.BNGetDefaultArchitecture(self.handle)
		if arch is None:
			return None
		return binaryninja.architecture.CoreArchitecture._from_cache(handle=arch)

	@arch.setter
	def arch(self, value):
		if value is None:
			core.BNSetDefaultArchitecture(self.handle, None)
		else:
			core.BNSetDefaultArchitecture(self.handle, value.handle)

	@property
	def platform(self):
		"""The platform associated with the current BinaryView (read/write)"""
		plat = core.BNGetDefaultPlatform(self.handle)
		if plat is None:
			return None
		return binaryninja.platform.Platform(self.arch, handle=plat)

	@platform.setter
	def platform(self, value):
		if value is None:
			core.BNSetDefaultPlatform(self.handle, None)
		else:
			core.BNSetDefaultPlatform(self.handle, value.handle)

	@property
	def endianness(self):
		"""Endianness of the binary (read-only)"""
		return Endianness(core.BNGetDefaultEndianness(self.handle))

	@property
	def relocatable(self):
		"""Boolean - is the binary relocatable (read-only)"""
		return core.BNIsRelocatable(self.handle)

	@property
	def address_size(self):
		"""Address size of the binary (read-only)"""
		return core.BNGetViewAddressSize(self.handle)

	@property
	def executable(self):
		"""Whether the binary is an executable (read-only)"""
		return core.BNIsExecutableView(self.handle)

	@property
	def functions(self):
		"""List of functions (read-only)"""
		count = ctypes.c_ulonglong(0)
		funcs = core.BNGetAnalysisFunctionList(self.handle, count)
		result = []
		for i in range(0, count.value):
			result.append(binaryninja.function.Function(self, core.BNNewFunctionReference(funcs[i])))
		core.BNFreeFunctionList(funcs, count.value)
		return result

	@property
	def has_functions(self):
		"""Boolean whether the binary has functions (read-only)"""
		return core.BNHasFunctions(self.handle)

	@property
	def has_symbols(self):
		"""Boolean whether the binary has symbols (read-only)"""
		return core.BNHasSymbols(self.handle)

	@property
	def has_data_variables(self):
		"""Boolean whether the binary has functions (read-only)"""
		return core.BNHasDataVariables(self.handle)

	@property
	def entry_function(self):
		"""Entry function (read-only)"""
		func = core.BNGetAnalysisEntryPoint(self.handle)
		if func is None:
			return None
		return binaryninja.function.Function(self, func)

	@property
	def symbols(self):
		"""Dict of symbols (read-only)"""
		count = ctypes.c_ulonglong(0)
		syms = core.BNGetSymbols(self.handle, count, None)
		result = {}
		for i in range(0, count.value):
			sym = types.Symbol(None, None, None, handle=core.BNNewSymbolReference(syms[i]))
			if sym.raw_name in result:
				result[sym.raw_name] = [result[sym.raw_name], sym]
			else:
				result[sym.raw_name] = sym
		core.BNFreeSymbolList(syms, count.value)
		return result

	@classmethod
	def internal_namespace(self):
		"""Internal namespace for the current BinaryView"""
		ns = core.BNGetInternalNameSpace()
		result = types.NameSpace._from_core_struct(ns)
		core.BNFreeNameSpace(ns)
		return result

	@classmethod
	def external_namespace(self):
		"""External namespace for the current BinaryView"""
		ns = core.BNGetExternalNameSpace()
		result = types.NameSpace._from_core_struct(ns)
		core.BNFreeNameSpace(ns)
		return result

	@property
	def namespaces(self):
		"""Returns a list of namespaces for the current BinaryView"""
		count = ctypes.c_ulonglong(0)
		nameSpaceList = core.BNGetNameSpaces(self.handle, count)
		result = []
		for i in range(count.value):
			result.append(types.NameSpace._from_core_struct(nameSpaceList[i]))
		core.BNFreeNameSpaceList(nameSpaceList, count.value)
		return result

	@property
	def view_type(self):
		"""View type (read-only)"""
		return core.BNGetViewType(self.handle)

	@property
	def available_view_types(self):
		"""Available view types (read-only)"""
		count = ctypes.c_ulonglong(0)
		types = core.BNGetBinaryViewTypesForData(self.handle, count)
		result = []
		for i in range(0, count.value):
			result.append(BinaryViewType(types[i]))
		core.BNFreeBinaryViewTypeList(types)
		return result

	@property
	def strings(self):
		"""List of strings (read-only)"""
		return self.get_strings()

	@property
	def saved(self):
		"""boolean state of whether or not the file has been saved (read/write)"""
		return self._file.saved

	@saved.setter
	def saved(self, value):
		self._file.saved = value

	@property
	def analysis_info(self):
		"""Provides instantaneous analysis state information and a list of current functions under analysis (read-only).
		All times are given in units of milliseconds (ms). Per-function `analysis_time` is the aggregation of time spent
		performing incremental updates and is reset on a full function update. Per-function `update_count` tracks the
		current number of incremental updates and is reset on a full function update. Per-function `submit_count` tracks the
		current number of full updates that have completed.

		.. note:: `submit_count` is currently not reset across analysis updates.

		"""
		info_ref = core.BNGetAnalysisInfo(self.handle)
		info = info_ref[0]
		active_info_list = []
		for i in range(0, info.count):
			func = binaryninja.function.Function(self, core.BNNewFunctionReference(info.activeInfo[i].func))
			active_info = ActiveAnalysisInfo(func, info.activeInfo[i].analysisTime, info.activeInfo[i].updateCount, info.activeInfo[i].submitCount)
			active_info_list.append(active_info)
		result = AnalysisInfo(info.state, info.analysisTime, active_info_list)
		core.BNFreeAnalysisInfo(info_ref)
		return result

	@property
	def analysis_progress(self):
		"""Status of current analysis (read-only)"""
		result = core.BNGetAnalysisProgress(self.handle)
		return AnalysisProgress(result.state, result.count, result.total)

	@property
	def linear_disassembly(self):
		"""Iterator for all lines in the linear disassembly of the view"""
		return self.get_linear_disassembly(None)

	@property
	def data_vars(self):
		"""List of data variables (read-only)"""
		count = ctypes.c_ulonglong(0)
		var_list = core.BNGetDataVariables(self.handle, count)
		result = {}
		for i in range(0, count.value):
			addr = var_list[i].address
			var_type = types.Type(core.BNNewTypeReference(var_list[i].type), platform = self.platform, confidence = var_list[i].typeConfidence)
			auto_discovered = var_list[i].autoDiscovered
			result[addr] = DataVariable(addr, var_type, auto_discovered, self)
		core.BNFreeDataVariables(var_list, count.value)
		return result

	@property
	def types(self):
		"""List of defined types (read-only)"""
		count = ctypes.c_ulonglong(0)
		type_list = core.BNGetAnalysisTypeList(self.handle, count)
		result = {}
		for i in range(0, count.value):
			name = types.QualifiedName._from_core_struct(type_list[i].name)
			result[name] = types.Type(core.BNNewTypeReference(type_list[i].type), platform = self.platform)
		core.BNFreeTypeList(type_list, count.value)
		return result

	@property
	def type_names(self):
		"""List of defined type names (read-only)"""
		count = ctypes.c_ulonglong(0)
		name_list = core.BNGetAnalysisTypeNames(self.handle, count, "")
		result = []
		for i in range(0, count.value):
			result.append(types.QualifiedName._from_core_struct(name_list[i]))
		core.BNFreeTypeNameList(name_list, count.value)
		return result


	@property
	def type_libraries(self):
		"""List of imported type libraries (read-only)"""
		count = ctypes.c_ulonglong(0)
		libraries = core.BNGetBinaryViewTypeLibraries(self.handle, count)
		result = []
		for i in range(0, count.value):
			result.append(typelibrary.TypeLibrary(core.BNNewTypeLibraryReference(libraries[i])))
		core.BNFreeTypeLibraryList(libraries, count.value)
		return result


	@property
	def segments(self):
		"""List of segments (read-only)"""
		count = ctypes.c_ulonglong(0)
		segment_list = core.BNGetSegments(self.handle, count)
		result = []
		for i in range(0, count.value):
			result.append(Segment(core.BNNewSegmentReference(segment_list[i])))
		core.BNFreeSegmentList(segment_list, count.value)
		return result

	@property
	def sections(self):
		"""Dictionary of sections (read-only)"""
		count = ctypes.c_ulonglong(0)
		section_list = core.BNGetSections(self.handle, count)
		result = {}
		for i in range(0, count.value):
			result[core.BNSectionGetName(section_list[i])] = Section(core.BNNewSectionReference(section_list[i]))
		core.BNFreeSectionList(section_list, count.value)
		return result

	@property
	def allocated_ranges(self):
		"""List of valid address ranges for this view (read-only)"""
		count = ctypes.c_ulonglong(0)
		range_list = core.BNGetAllocatedRanges(self.handle, count)
		result = []
		for i in range(0, count.value):
			result.append(AddressRange(range_list[i].start, range_list[i].end))
		core.BNFreeAddressRanges(range_list)
		return result

	@property
	def session_data(self):
		"""Dictionary object where plugins can store arbitrary data associated with the view"""
		handle = ctypes.cast(self.handle, ctypes.c_void_p)
		if handle.value not in BinaryView._associated_data:
			obj = _BinaryViewAssociatedDataStore()
			BinaryView._associated_data[handle.value] = obj
			return obj
		else:
			return BinaryView._associated_data[handle.value]

	@property
	def global_pointer_value(self):
		"""Discovered value of the global pointer register, if the binary uses one (read-only)"""
		result = core.BNGetGlobalPointerValue(self.handle)
		return binaryninja.function.RegisterValue(self.arch, result.value, confidence = result.confidence)

	@property
	def parameters_for_analysis(self):
		return core.BNGetParametersForAnalysis(self.handle)

	@parameters_for_analysis.setter
	def parameters_for_analysis(self, params):
		core.BNSetParametersForAnalysis(self.handle, params)

	@property
	def max_function_size_for_analysis(self):
		"""Maximum size of function (sum of basic block sizes in bytes) for auto analysis"""
		return core.BNGetMaxFunctionSizeForAnalysis(self.handle)

	@max_function_size_for_analysis.setter
	def max_function_size_for_analysis(self, size):
		core.BNSetMaxFunctionSizeForAnalysis(self.handle, size)

	@property
	def relocation_ranges(self):
		"""List of relocation range tuples (read-only)"""

		count = ctypes.c_ulonglong()
		ranges = core.BNGetRelocationRanges(self.handle, count)
		result = []
		for i in range(0, count.value):
			result.append((ranges[i].start, ranges[i].end))
		core.BNFreeRelocationRanges(ranges, count)
		return result

	def relocation_ranges_at(self, addr):
		"""List of relocation range tuples for a given address"""

		count = ctypes.c_ulonglong()
		ranges = core.BNGetRelocationRangesAtAddress(self.handle, addr, count)
		result = []
		for i in range(0, count.value):
			result.append((ranges[i].start, ranges[i].end))
		core.BNFreeRelocationRanges(ranges, count)
		return result

	@property
	def new_auto_function_analysis_suppressed(self):
		"""Whether or not automatically discovered functions will be analyzed"""
		return core.BNGetNewAutoFunctionAnalysisSuppressed(self.handle)

	@new_auto_function_analysis_suppressed.setter
	def new_auto_function_analysis_suppressed(self, suppress):
		core.BNSetNewAutoFunctionAnalysisSuppressed(self.handle, suppress)

	def _init(self, ctxt):
		try:
			return self.init()
		except:
			log.log_error(traceback.format_exc())
			return False

	def _external_ref_taken(self, ctxt):
		try:
			self.__class__._registered_instances.append(self)
		except:
			log.log_error(traceback.format_exc())

	def _external_ref_released(self, ctxt):
		try:
			self.__class__._registered_instances.remove(self)
		except:
			log.log_error(traceback.format_exc())

	def _read(self, ctxt, dest, offset, length):
		try:
			data = self.perform_read(offset, length)
			if data is None:
				return 0
			data = cstr(data)
			if len(data) > length:
				data = data[0:length]
			ctypes.memmove(dest, data, len(data))
			return len(data)
		except:
			log.log_error(traceback.format_exc())
			return 0

	def _write(self, ctxt, offset, src, length):
		try:
			data = ctypes.create_string_buffer(length)
			ctypes.memmove(data, src, length)
			return self.perform_write(offset, data.raw)
		except:
			log.log_error(traceback.format_exc())
			return 0

	def _insert(self, ctxt, offset, src, length):
		try:
			data = ctypes.create_string_buffer(length)
			ctypes.memmove(data, src, length)
			return self.perform_insert(offset, data.raw)
		except:
			log.log_error(traceback.format_exc())
			return 0

	def _remove(self, ctxt, offset, length):
		try:
			return self.perform_remove(offset, length)
		except:
			log.log_error(traceback.format_exc())
			return 0

	def _get_modification(self, ctxt, offset):
		try:
			return self.perform_get_modification(offset)
		except:
			log.log_error(traceback.format_exc())
			return ModificationStatus.Original

	def _is_valid_offset(self, ctxt, offset):
		try:
			return self.perform_is_valid_offset(offset)
		except:
			log.log_error(traceback.format_exc())
			return False

	def _is_offset_readable(self, ctxt, offset):
		try:
			return self.perform_is_offset_readable(offset)
		except:
			log.log_error(traceback.format_exc())
			return False

	def _is_offset_writable(self, ctxt, offset):
		try:
			return self.perform_is_offset_writable(offset)
		except:
			log.log_error(traceback.format_exc())
			return False

	def _is_offset_executable(self, ctxt, offset):
		try:
			return self.perform_is_offset_executable(offset)
		except:
			log.log_error(traceback.format_exc())
			return False

	def _get_next_valid_offset(self, ctxt, offset):
		try:
			return self.perform_get_next_valid_offset(offset)
		except:
			log.log_error(traceback.format_exc())
			return offset

	def _get_start(self, ctxt):
		try:
			return self.perform_get_start()
		except:
			log.log_error(traceback.format_exc())
			return 0

	def _get_length(self, ctxt):
		try:
			return self.perform_get_length()
		except:
			log.log_error(traceback.format_exc())
			return 0

	def _get_entry_point(self, ctxt):
		try:
			return self.perform_get_entry_point()
		except:
			log.log_error(traceback.format_exc())
			return 0

	def _is_executable(self, ctxt):
		try:
			return self.perform_is_executable()
		except:
			log.log_error(traceback.format_exc())
			return False

	def _get_default_endianness(self, ctxt):
		try:
			return self.perform_get_default_endianness()
		except:
			log.log_error(traceback.format_exc())
			return Endianness.LittleEndian

	def _is_relocatable(self, ctxt):
		try:
			return self.perform_is_relocatable()
		except:
			log.log_error(traceback.format_exc())
			return False

	def _get_address_size(self, ctxt):
		try:
			return self.perform_get_address_size()
		except:
			log.log_error(traceback.format_exc())
			return 8

	def _save(self, ctxt, file_accessor):
		try:
			return self.perform_save(fileaccessor.CoreFileAccessor(file_accessor))
		except:
			log.log_error(traceback.format_exc())
			return False

	def init(self):
		return True

	def get_disassembly(self, addr, arch=None):
		"""
		``get_disassembly`` simple helper function for printing disassembly of a given address

		:param int addr: virtual address of instruction
		:param Architecture arch: optional Architecture, ``self.arch`` is used if this parameter is None
		:return: a str representation of the instruction at virtual address ``addr`` or None
		:rtype: str or None
		:Example:

			>>> bv.get_disassembly(bv.entry_point)
			'push    ebp'
			>>>
		"""
		if arch is None:
			arch = self.arch
		txt, size = arch.get_instruction_text(self.read(addr, arch.max_instr_length), addr)
		self.next_address = addr + size
		if txt is None:
			return None
		return ''.join(str(a) for a in txt).strip()

	def get_next_disassembly(self, arch=None):
		"""
		``get_next_disassembly`` simple helper function for printing disassembly of the next instruction.
		The internal state of the instruction to be printed is stored in the :attr:`next_address` attribute

		:param Architecture arch: optional Architecture, ``self.arch`` is used if this parameter is None
		:return: a str representation of the instruction at virtual address :attr:`next_address`
		:rtype: str or None
		:Example:

			>>> bv.get_next_disassembly()
			'push    ebp'
			>>> bv.get_next_disassembly()
			'mov     ebp, esp'
			>>> #Now reset the starting point back to the entry point
			>>> bv.next_address = bv.entry_point
			>>> bv.get_next_disassembly()
			'push    ebp'
			>>>
		"""
		if arch is None:
			arch = self.arch
		if self.next_address is None:
			self.next_address = self.entry_point
		txt, size = arch.get_instruction_text(self.read(self.next_address, arch.max_instr_length), self.next_address)
		self.next_address += size
		if txt is None:
			return None
		return ''.join(str(a) for a in txt).strip()

	def perform_save(self, accessor):
		if self.parent_view is not None:
			return self.parent_view.save(accessor)
		return False

	@abc.abstractmethod
	def perform_get_address_size(self):
		raise NotImplementedError

	def perform_get_length(self):
		"""
		``perform_get_length`` implements a query for the size of the virtual address range used by
		the BinaryView.

		.. note:: This method **may** be overridden by custom BinaryViews. Use :func:`add_auto_segment` to provide \
		data without overriding this method.

		.. warning:: This method **must not** be called directly.

		:return: returns the size of the virtual address range used by the BinaryView.
		:rtype: int
		"""
		return 0

	def perform_read(self, addr, length):
		"""
		``perform_read`` implements a mapping between a virtual address and an absolute file offset, reading
		``length`` bytes from the rebased address ``addr``.

		.. note:: This method **may** be overridden by custom BinaryViews. Use :func:`add_auto_segment` to provide \
		data without overriding this method.

		.. warning:: This method **must not** be called directly.

		:param int addr: a virtual address to attempt to read from
		:param int length: the number of bytes to be read
		:return: length bytes read from addr, should return empty string on error
		:rtype: str
		"""
		return ""

	def perform_write(self, addr, data):
		"""
		``perform_write`` implements a mapping between a virtual address and an absolute file offset, writing
		the bytes ``data`` to rebased address ``addr``.

		.. note:: This method **may** be overridden by custom BinaryViews. Use :func:`add_auto_segment` to provide \
		data without overriding this method.

		.. warning:: This method **must not** be called directly.

		:param int addr: a virtual address
		:param str data: the data to be written
		:return: length of data written, should return 0 on error
		:rtype: int
		"""
		return 0

	def perform_insert(self, addr, data):
		"""
		``perform_insert`` implements a mapping between a virtual address and an absolute file offset, inserting
		the bytes ``data`` to rebased address ``addr``.

		.. note:: This method **may** be overridden by custom BinaryViews. If not overridden, inserting is disallowed

		.. warning:: This method **must not** be called directly.

		:param int addr: a virtual address
		:param str data: the data to be inserted
		:return: length of data inserted, should return 0 on error
		:rtype: int
		"""
		return 0

	def perform_remove(self, addr, length):
		"""
		``perform_remove`` implements a mapping between a virtual address and an absolute file offset, removing
		``length`` bytes from the rebased address ``addr``.

		.. note:: This method **may** be overridden by custom BinaryViews. If not overridden, removing data is disallowed

		.. warning:: This method **must not** be called directly.

		:param int addr: a virtual address
		:param str data: the data to be removed
		:return: length of data removed, should return 0 on error
		:rtype: int
		"""
		return 0

	def perform_get_modification(self, addr):
		"""
		``perform_get_modification`` implements query to the whether the virtual address ``addr`` is modified.

		.. note:: This method **may** be overridden by custom BinaryViews. Use :func:`add_auto_segment` to provide \
		data without overriding this method.

		.. warning:: This method **must not** be called directly.

		:param int addr: a virtual address to be checked
		:return: One of the following: Original = 0, Changed = 1, Inserted = 2
		:rtype: ModificationStatus
		"""
		return ModificationStatus.Original

	def perform_is_valid_offset(self, addr):
		"""
		``perform_is_valid_offset`` implements a check if an virtual address ``addr`` is valid.

		.. note:: This method **may** be overridden by custom BinaryViews. Use :func:`add_auto_segment` to provide \
		data without overriding this method.

		.. warning:: This method **must not** be called directly.

		:param int addr: a virtual address to be checked
		:return: true if the virtual address is valid, false if the virtual address is invalid or error
		:rtype: bool
		"""
		data = self.read(addr, 1)
		return (data is not None) and (len(data) == 1)

	def perform_is_offset_readable(self, offset):
		"""
		``perform_is_offset_readable`` implements a check if an virtual address is readable.

		.. note:: This method **may** be overridden by custom BinaryViews. Use :func:`add_auto_segment` to provide \
		data without overriding this method.

		.. warning:: This method **must not** be called directly.

		:param int offset: a virtual address to be checked
		:return: true if the virtual address is readable, false if the virtual address is not readable or error
		:rtype: bool
		"""
		return self.is_valid_offset(offset)

	def perform_is_offset_writable(self, addr):
		"""
		``perform_is_offset_writable`` implements a check if a virtual address ``addr`` is writable.

		.. note:: This method **may** be overridden by custom BinaryViews. Use :func:`add_auto_segment` to provide \
		data without overriding this method.

		.. warning:: This method **must not** be called directly.

		:param int addr: a virtual address to be checked
		:return: true if the virtual address is writable, false if the virtual address is not writable or error
		:rtype: bool
		"""
		return self.is_valid_offset(addr)

	def perform_is_offset_executable(self, addr):
		"""
		``perform_is_offset_executable`` implements a check if a virtual address ``addr`` is executable.

		.. note:: This method **may** be overridden by custom BinaryViews. Use :func:`add_auto_segment` to provide \
		data without overriding this method.

		.. warning:: This method **must not** be called directly.

		:param int addr: a virtual address to be checked
		:return: true if the virtual address is executable, false if the virtual address is not executable or error
		:rtype: int
		"""
		return self.is_valid_offset(addr)

	def perform_get_next_valid_offset(self, addr):
		"""
		``perform_get_next_valid_offset`` implements a query for the next valid readable, writable, or executable virtual
		memory address.

		.. note:: This method **may** be overridden by custom BinaryViews. Use :func:`add_auto_segment` to provide \
		data without overriding this method.

		.. warning:: This method **must not** be called directly.

		:param int addr: a virtual address to start checking from.
		:return: the next readable, writable, or executable virtual memory address
		:rtype: int
		"""
		if addr < self.perform_get_start():
			return self.perform_get_start()
		return addr

	def perform_get_start(self):
		"""
		``perform_get_start`` implements a query for the first readable, writable, or executable virtual address in
		the BinaryView.

		.. note:: This method **may** be overridden by custom BinaryViews. Use :func:`add_auto_segment` to provide \
		data without overriding this method.

		.. warning:: This method **must not** be called directly.

		:return: returns the first virtual address in the BinaryView.
		:rtype: int
		"""
		return 0

	def perform_get_entry_point(self):
		"""
		``perform_get_entry_point`` implements a query for the initial entry point for code execution.

		.. note:: This method **should** be implemented for custom BinaryViews that are executable.

		.. warning:: This method **must not** be called directly.

		:return: the virtual address of the entry point
		:rtype: int
		"""
		return 0

	def perform_is_executable(self):
		"""
		``perform_is_executable`` implements a check which returns true if the BinaryView is executable.

		.. note:: This method **must** be implemented for custom BinaryViews that are executable.

		.. warning:: This method **must not** be called directly.

		:return: true if the current BinaryView is executable, false if it is not executable or on error
		:rtype: bool
		"""
		return False

	def perform_get_default_endianness(self):
		"""
		``perform_get_default_endianness`` implements a check which returns true if the BinaryView is executable.

		.. note:: This method **may** be implemented for custom BinaryViews that are not LittleEndian.

		.. warning:: This method **must not** be called directly.

		:return: either :const:`Endianness.LittleEndian <binaryninja.enums.Endianness.LittleEndian>` or :const:`Endianness.BigEndian <binaryninja.enums.Endianness.BigEndian>`
		:rtype: Endianness
		"""
		return Endianness.LittleEndian

	def perform_is_relocatable(self):
		"""
		``perform_is_relocatable`` implements a check which returns true if the BinaryView is relocatable. Defaults to False

		.. note:: This method **may** be implemented for custom BinaryViews that are relocatable.

		.. warning:: This method **must not** be called directly.

		:return: True if the BinaryView is relocatable, False otherwise
		:rtype: boolean
		"""
		return False

	def create_database(self, filename, progress_func=None, settings=None):
		"""
		``create_database`` writes the current database (.bndb) out to the specified file.

		:param str filename: path and filename to write the bndb to, this string `should` have ".bndb" appended to it.
		:param callback progress_func: optional function to be called with the current progress and total count.
		:param SaveSettings settings: optional argument for special save options.
		:return: true on success, false on failure
		:rtype: bool
		:Example:
			>>> settings = SaveSettings()
			>>> bv.create_database(f"{bv.file.filename}.bndb", None, settings)
			True
		"""
		return self._file.create_database(filename, progress_func, settings)

	def save_auto_snapshot(self, progress_func=None, settings=None):
		"""
		``save_auto_snapshot`` saves the current database to the already created file.

		.. note:: :py:meth:`create_database` should have been called prior to executing this method

		:param callback progress_func: optional function to be called with the current progress and total count.
		:param SaveSettings settings: optional argument for special save options.
		:return: True if it successfully saved the snapshot, False otherwise
		:rtype: bool
		"""
		return self._file.save_auto_snapshot(progress_func, settings)

	def get_view_of_type(self, name):
		"""
		``get_view_of_type`` returns the BinaryView associated with the provided name if it exists.

		:param str name: Name of the view to be retrieved
		:return: BinaryView object associated with the provided name or None on failure
		:rtype: BinaryView or None
		"""
		return self._file.get_view_of_type(name)

	def begin_undo_actions(self):
		"""
		``begin_undo_actions`` start recording actions taken so the can be undone at some point.

		:rtype: None
		:Example:

			>>> bv.get_disassembly(0x100012f1)
			'xor     eax, eax'
			>>> bv.begin_undo_actions()
			>>> bv.convert_to_nop(0x100012f1)
			True
			>>> bv.commit_undo_actions()
			>>> bv.get_disassembly(0x100012f1)
			'nop'
			>>> bv.undo()
			>>> bv.get_disassembly(0x100012f1)
			'xor     eax, eax'
			>>>
		"""
		self._file.begin_undo_actions()

	def commit_undo_actions(self):
		"""
		``commit_undo_actions`` commit the actions taken since the last commit to the undo database.

		:rtype: None
		:Example:

			>>> bv.get_disassembly(0x100012f1)
			'xor     eax, eax'
			>>> bv.begin_undo_actions()
			>>> bv.convert_to_nop(0x100012f1)
			True
			>>> bv.commit_undo_actions()
			>>> bv.get_disassembly(0x100012f1)
			'nop'
			>>> bv.undo()
			>>> bv.get_disassembly(0x100012f1)
			'xor     eax, eax'
			>>>
		"""
		self._file.commit_undo_actions()

	def undo(self):
		"""
		``undo`` undo the last committed action in the undo database.

		:rtype: None
		:Example:

			>>> bv.get_disassembly(0x100012f1)
			'xor     eax, eax'
			>>> bv.begin_undo_actions()
			>>> bv.convert_to_nop(0x100012f1)
			True
			>>> bv.commit_undo_actions()
			>>> bv.get_disassembly(0x100012f1)
			'nop'
			>>> bv.undo()
			>>> bv.get_disassembly(0x100012f1)
			'xor     eax, eax'
			>>> bv.redo()
			>>> bv.get_disassembly(0x100012f1)
			'nop'
			>>>
		"""
		self._file.undo()

	def redo(self):
		"""
		``redo`` redo the last committed action in the undo database.

		:rtype: None
		:Example:

			>>> bv.get_disassembly(0x100012f1)
			'xor     eax, eax'
			>>> bv.begin_undo_actions()
			>>> bv.convert_to_nop(0x100012f1)
			True
			>>> bv.commit_undo_actions()
			>>> bv.get_disassembly(0x100012f1)
			'nop'
			>>> bv.undo()
			>>> bv.get_disassembly(0x100012f1)
			'xor     eax, eax'
			>>> bv.redo()
			>>> bv.get_disassembly(0x100012f1)
			'nop'
			>>>
		"""
		self._file.redo()

	def navigate(self, view, offset):
		"""
		``navigate`` navigates the UI to the specified virtual address

		.. note:: Despite the confusing name, ``view`` in this context is not a BinaryView but rather a string describing the different UI Views.  Check :py:attr:`view` while in different views to see examples such as ``Linear:ELF``, ``Graph:PE``.

		:param str view: virtual address to read from.
		:param int offset: address to navigate to
		:return: whether or not navigation succeeded
		:rtype: bool
		:Example:

			>>> import random
			>>> bv.navigate(bv.view, random.choice(bv.functions).start)
			True
		"""
		return self._file.navigate(view, offset)

	def read(self, addr, length):
		"""
		``read`` returns the data reads at most ``length`` bytes from virtual address ``addr``.

		..note:: Python2 returns a str, but Python3 returns a bytes object.  str(DataBufferObject) will \
 		still get you a str in either case.

		:param int addr: virtual address to read from.
		:param int length: number of bytes to read.
		:return: at most ``length`` bytes from the virtual address ``addr``, empty string on error or no data.
		:rtype: python2 - str; python3 - bytes
		:Example:

			>>> #Opening a x86_64 Mach-O binary
			>>> bv = BinaryViewType['Raw'].open("/bin/ls") #note that we are using open instead of get_view_of_file to get the raw view
			>>> bv.read(0,4)
			\'\\xcf\\xfa\\xed\\xfe\'
		"""
		if (addr < 0) or (length < 0):
			raise ValueError("length and address must both be positive")
		buf = databuffer.DataBuffer(handle=core.BNReadViewBuffer(self.handle, addr, length))
		return bytes(buf)

	def write(self, addr, data):
		"""
		``write`` writes the bytes in ``data`` to the virtual address ``addr``.

		:param int addr: virtual address to write to.
		:param Union[bytes, bytearray, str] data: data to be written at addr.
		:return: number of bytes written to virtual address ``addr``
		:rtype: int
		:Example:

			>>> bv.read(0,4)
			'BBBB'
			>>> bv.write(0, "AAAA")
			4L
			>>> bv.read(0,4)
			'AAAA'
		"""
		if not (isinstance(data, bytes) or isinstance(data, bytearray) or isinstance(data, str)):
			raise TypeError("Must be bytes, bytearray, or str")
		else:
			buf = databuffer.DataBuffer(data)
		return core.BNWriteViewBuffer(self.handle, addr, buf.handle)

	def insert(self, addr, data):
		"""
		``insert`` inserts the bytes in ``data`` to the virtual address ``addr``.

		:param int addr: virtual address to write to.
		:param Union[bytes, bytearray, str] data: data to be inserted at addr.
		:return: number of bytes inserted to virtual address ``addr``
		:rtype: int
		:Example:

			>>> bv.insert(0,"BBBB")
			4L
			>>> bv.read(0,8)
			'BBBBAAAA'
		"""
		if not (isinstance(data, bytes) or isinstance(data, bytearray) or isinstance(data, str)):
			raise TypeError("Must be bytes, bytearray, or str")
		else:
			buf = databuffer.DataBuffer(data)
		return core.BNInsertViewBuffer(self.handle, addr, buf.handle)

	def remove(self, addr, length):
		"""
		``remove`` removes at most ``length`` bytes from virtual address ``addr``.

		:param int addr: virtual address to remove from.
		:param int length: number of bytes to remove.
		:return: number of bytes removed from virtual address ``addr``
		:rtype: int
		:Example:

			>>> bv.read(0,8)
			'BBBBAAAA'
			>>> bv.remove(0,4)
			4L
			>>> bv.read(0,4)
			'AAAA'
		"""
		return core.BNRemoveViewData(self.handle, addr, length)

	def get_entropy(self, addr, length, block_size=0):
		"""
		``get_entropy`` returns the shannon entropy given the start ``addr``, ``length`` in bytes, and optionally in
		``block_size`` chunks.

		:param int addr: virtual address
		:param int length: total length in bytes
		:param int block_size: optional block size
		:return: list of entropy values for each chunk
		:rtype: list(float)
		"""
		result = []
		if length == 0:
			return result
		if block_size == 0:
			block_size = length
		data = (ctypes.c_float * ((length // block_size) + 1))()
		length = core.BNGetEntropy(self.handle, addr, length, block_size, data)

		for i in range(0, length):
			result.append(float(data[i]))
		return result

	def get_modification(self, addr, length=None):
		"""
		``get_modification`` returns the modified bytes of up to ``length`` bytes from virtual address ``addr``, or if
		``length`` is None returns the ModificationStatus.

		:param int addr: virtual address to get modification from
		:param int length: optional length of modification
		:return: Either ModificationStatus of the byte at ``addr``, or string of modified bytes at ``addr``
		:rtype: ModificationStatus or str
		"""
		if length is None:
			return ModificationStatus(core.BNGetModification(self.handle, addr))
		data = (ModificationStatus * length)()
		length = core.BNGetModificationArray(self.handle, addr, data, length)
		return data[0:length]

	def is_valid_offset(self, addr):
		"""
		``is_valid_offset`` checks if an virtual address ``addr`` is valid .

		:param int addr: a virtual address to be checked
		:return: true if the virtual address is valid, false if the virtual address is invalid or error
		:rtype: bool
		"""
		return core.BNIsValidOffset(self.handle, addr)

	def is_offset_readable(self, addr):
		"""
		``is_offset_readable`` checks if an virtual address ``addr`` is valid for reading.

		:param int addr: a virtual address to be checked
		:return: true if the virtual address is valid for reading, false if the virtual address is invalid or error
		:rtype: bool
		"""
		return core.BNIsOffsetReadable(self.handle, addr)

	def is_offset_writable(self, addr):
		"""
		``is_offset_writable`` checks if an virtual address ``addr`` is valid for writing.

		:param int addr: a virtual address to be checked
		:return: true if the virtual address is valid for writing, false if the virtual address is invalid or error
		:rtype: bool
		"""
		return core.BNIsOffsetWritable(self.handle, addr)

	def is_offset_executable(self, addr):
		"""
		``is_offset_executable`` checks if an virtual address ``addr`` is valid for executing.

		:param int addr: a virtual address to be checked
		:return: true if the virtual address is valid for executing, false if the virtual address is invalid or error
		:rtype: bool
		"""
		return core.BNIsOffsetExecutable(self.handle, addr)

	def is_offset_code_semantics(self, addr):
		"""
		``is_offset_code_semantics`` checks if an virtual address ``addr`` is semantically valid for code.

		:param int addr: a virtual address to be checked
		:return: true if the virtual address is valid for code semantics, false if the virtual address is invalid or error
		:rtype: bool
		"""
		return core.BNIsOffsetCodeSemantics(self.handle, addr)

	def is_offset_extern_semantics(self, addr):
		"""
		``is_offset_extern_semantics`` checks if an virtual address ``addr`` is semantically valid for external references.

		:param int addr: a virtual address to be checked
		:return: true if the virtual address is valid for for external references, false if the virtual address is invalid or error
		:rtype: bool
		"""
		return core.BNIsOffsetExternSemantics(self.handle, addr)

	def is_offset_writable_semantics(self, addr):
		"""
		``is_offset_writable_semantics`` checks if an virtual address ``addr`` is semantically writable. Some sections
		may have writable permissions for linking purposes but can be treated as read-only for the purposes of
		analysis.

		:param int addr: a virtual address to be checked
		:return: true if the virtual address is valid for writing, false if the virtual address is invalid or error
		:rtype: bool
		"""
		return core.BNIsOffsetWritableSemantics(self.handle, addr)

	def save(self, dest):
		"""
		``save`` saves the original binary file to the provided destination ``dest`` along with any modifications.

		:param str dest: destination path and filename of file to be written
		:return: boolean True on success, False on failure
		:rtype: bool
		"""
		if isinstance(dest, fileaccessor.FileAccessor):
			return core.BNSaveToFile(self.handle, dest._cb)
		return core.BNSaveToFilename(self.handle, str(dest))

	def register_notification(self, notify):
		"""
		`register_notification` provides a mechanism for receiving callbacks for various analysis events. A full
		list of callbacks can be seen in :py:Class:`BinaryDataNotification`.

		:param BinaryDataNotification notify: notify is a subclassed instance of :py:Class:`BinaryDataNotification`.
		:rtype: None
		"""
		cb = BinaryDataNotificationCallbacks(self, notify)
		cb._register()
		self.notifications[notify] = cb

	def unregister_notification(self, notify):
		"""
		`unregister_notification` unregisters the :py:Class:`BinaryDataNotification` object passed to
		`register_notification`

		:param BinaryDataNotification notify: notify is a subclassed instance of :py:Class:`BinaryDataNotification`.
		:rtype: None
		"""
		if notify in self.notifications:
			self.notifications[notify]._unregister()
			del self.notifications[notify]

	def add_function(self, addr, plat=None):
		"""
		``add_function`` add a new function of the given ``plat`` at the virtual address ``addr``

		:param int addr: virtual address of the function to be added
		:param Platform plat: Platform for the function to be added
		:rtype: None
		:Example:

			>>> bv.add_function(1)
			>>> bv.functions
			[<func: x86_64@0x1>]

		"""
		if self.platform is None and plat is None:
			raise Exception("Default platform not set in BinaryView")
		if plat is None:
			plat = self.platform
		if not isinstance(plat, binaryninja.platform.Platform):
			raise AttributeError("Provided platform is not of type `binaryninja.platform.Platform`")
		core.BNAddFunctionForAnalysis(self.handle, plat.handle, addr)

	def add_entry_point(self, addr, plat=None):
		"""
		``add_entry_point`` adds an virtual address to start analysis from for a given plat.

		:param int addr: virtual address to start analysis from
		:param Platform plat: Platform for the entry point analysis
		:rtype: None
		:Example:
			>>> bv.add_entry_point(0xdeadbeef)
			>>>
		"""
		if self.platform is None and plat is None:
			raise Exception("Default platform not set in BinaryView")
		if plat is None:
			plat = self.platform
		if not isinstance(plat, binaryninja.platform.Platform):
			raise AttributeError("Provided platform is not of type `binaryninja.platform.Platform`")
		core.BNAddEntryPointForAnalysis(self.handle, plat.handle, addr)

	def remove_function(self, func):
		"""
		``remove_function`` removes the function ``func`` from the list of functions

		.. warning: This method should only be used when the function that is removed is expected to re-appear after any other analysis executes that could re-add it. Most users will want to use :func:`remove_user_function` in their scripts.

		:param Function func: a Function object.
		:rtype: None
		:Example:

			>>> bv.functions
			[<func: x86_64@0x1>]
			>>> bv.remove_function(bv.functions[0])
			>>> bv.functions
			[]
		"""
		core.BNRemoveAnalysisFunction(self.handle, func.handle)

	def create_user_function(self, addr, plat=None):
		"""
		``create_user_function`` add a new *user* function of the given ``plat`` at the virtual address ``addr``

		:param int addr: virtual address of the *user* function to be added
		:param Platform plat: Platform for the function to be added
		:rtype: None
		:Example:

			>>> bv.create_user_function(1)
			>>> bv.functions
			[<func: x86_64@0x1>]

		"""
		if plat is None:
			plat = self.platform
		core.BNCreateUserFunction(self.handle, plat.handle, addr)

	def remove_user_function(self, func):
		"""
		``remove_user_function`` removes the function ``func`` from the list of functions as a user action.

		.. note:: This API will prevent the function from being re-created if any analysis later triggers that would re-add it, unlike :func:`remove_function`.

		:param Function func: a Function object.
		:rtype: None
		:Example:

			>>> bv.functions
			[<func: x86_64@0x1>]
			>>> bv.remove_user_function(bv.functions[0])
			>>> bv.functions
			[]
		"""
		core.BNRemoveUserFunction(self.handle, func.handle)

	def add_analysis_option(self, name):
		"""
		``add_analysis_option`` adds an analysis option. Analysis options elaborate the analysis phase. The user must
		start analysis by calling either :func:`update_analysis` or :func:`update_analysis_and_wait`.

		:param str name: name of the analysis option. Available options are: "linearsweep", and "signaturematcher".

		:rtype: None
		:Example:

			>>> bv.add_analysis_option("linearsweep")
			>>> bv.update_analysis_and_wait()
		"""
		core.BNAddAnalysisOption(self.handle, name)

	def update_analysis(self):
		"""
		``update_analysis`` asynchronously starts the analysis running and returns immediately. Analysis of BinaryViews
		does not occur automatically, the user must start analysis by calling either :func:`update_analysis` or
		:func:`update_analysis_and_wait`. An analysis update **must** be run after changes are made which could change
		analysis results such as adding functions.

		:rtype: None
		"""
		core.BNUpdateAnalysis(self.handle)

	def update_analysis_and_wait(self):
		"""
		``update_analysis_and_wait`` blocking call to update the analysis, this call returns when the analysis is
		complete.  Analysis of BinaryViews does not occur automatically, the user must start analysis by calling either
		:func:`update_analysis` or :func:`update_analysis_and_wait`. An analysis update **must** be run after changes are
		made which could change analysis results such as adding functions.

		:rtype: None
		"""
		core.BNUpdateAnalysisAndWait(self.handle)

	def abort_analysis(self):
		"""
		``abort_analysis`` will abort the currently running analysis.

		:rtype: None
		"""
		core.BNAbortAnalysis(self.handle)

	def define_data_var(self, addr, var_type):
		"""
		``define_data_var`` defines a non-user data variable ``var_type`` at the virtual address ``addr``.

		:param int addr: virtual address to define the given data variable
		:param Type var_type: type to be defined at the given virtual address
		:rtype: None
		:Example:

			>>> t = bv.parse_type_string("int foo")
			>>> t
			(<type: int32_t>, 'foo')
			>>> bv.define_data_var(bv.entry_point, t[0])
			>>>
		"""
		tc = core.BNTypeWithConfidence()
		tc.type = var_type.handle
		tc.confidence = var_type.confidence
		core.BNDefineDataVariable(self.handle, addr, tc)

	def define_user_data_var(self, addr, var_type):
		"""
		``define_user_data_var`` defines a user data variable ``var_type`` at the virtual address ``addr``.

		:param int addr: virtual address to define the given data variable
		:param binaryninja.Type var_type: type to be defined at the given virtual address
		:rtype: None
		:Example:

			>>> t = bv.parse_type_string("int foo")
			>>> t
			(<type: int32_t>, 'foo')
			>>> bv.define_user_data_var(bv.entry_point, t[0])
			>>>
		"""
		tc = core.BNTypeWithConfidence()
		tc.type = var_type.handle
		tc.confidence = var_type.confidence
		core.BNDefineUserDataVariable(self.handle, addr, tc)

	def undefine_data_var(self, addr):
		"""
		``undefine_data_var`` removes the non-user data variable at the virtual address ``addr``.

		:param int addr: virtual address to define the data variable to be removed
		:rtype: None
		:Example:

			>>> bv.undefine_data_var(bv.entry_point)
			>>>
		"""
		core.BNUndefineDataVariable(self.handle, addr)

	def undefine_user_data_var(self, addr):
		"""
		``undefine_user_data_var`` removes the user data variable at the virtual address ``addr``.

		:param int addr: virtual address to define the data variable to be removed
		:rtype: None
		:Example:

			>>> bv.undefine_user_data_var(bv.entry_point)
			>>>
		"""
		core.BNUndefineUserDataVariable(self.handle, addr)

	def get_data_var_at(self, addr):
		"""
		``get_data_var_at`` returns the data type at a given virtual address.

		:param int addr: virtual address to get the data type from
		:return: returns the DataVariable at the given virtual address, None on error.
		:rtype: DataVariable
		:Example:

			>>> t = bv.parse_type_string("int foo")
			>>> bv.define_data_var(bv.entry_point, t[0])
			>>> bv.get_data_var_at(bv.entry_point)
			<var 0x100001174: int32_t>

		"""
		var = core.BNDataVariable()
		if not core.BNGetDataVariableAtAddress(self.handle, addr, var):
			return None
		return DataVariable(var.address, types.Type(var.type, platform = self.platform, confidence = var.typeConfidence), var.autoDiscovered, self)

	def get_functions_containing(self, addr):
		"""
		``get_functions_containing`` returns a list of functions which contain the given address.

		:param int addr: virtual address to query.
		:rtype: list of Function objects
		"""
		basic_blocks = self.get_basic_blocks_at(addr)

		result = []
		for block in basic_blocks:
			result.append(block.function)
		return result

	def get_function_at(self, addr, plat=None):
		"""
		``get_function_at`` gets a Function object for the function that starts at virtual address ``addr``:

		:param int addr: starting virtual address of the desired function
		:param Platform plat: plat of the desired function
		:return: returns a Function object or None for the function at the virtual address provided
		:rtype: Function
		:Example:

			>>> bv.get_function_at(bv.entry_point)
			<func: x86_64@0x100001174>
			>>>
		"""
		if plat is None:
			plat = self.platform
		if plat is None:
			return None
		func = core.BNGetAnalysisFunction(self.handle, plat.handle, addr)
		if func is None:
			return None
		return binaryninja.function.Function(self, func)

	def get_functions_at(self, addr):
		"""

		``get_functions_at`` get a list of binaryninja.Function objects (one for each valid platform) that start at the
		given virtual address. Binary Ninja does not limit the number of platforms in a given file thus there may be
		multiple functions defined from different architectures at the same location. This API allows you to query all
		of valid platforms.

		You may also be interested in :func:`get_functions_containing` which is useful for requesting all function
		that contain a given address

		:param int addr: virtual address of the desired Function object list.
		:return: a list of binaryninja.Function objects defined at the provided virtual address
		:rtype: list(Function)
		"""
		count = ctypes.c_ulonglong(0)
		funcs = core.BNGetAnalysisFunctionsForAddress(self.handle, addr, count)
		result = []
		for i in range(0, count.value):
			result.append(binaryninja.function.Function(self, core.BNNewFunctionReference(funcs[i])))
		core.BNFreeFunctionList(funcs, count.value)
		return result

	def get_recent_function_at(self, addr):
		func = core.BNGetRecentAnalysisFunctionForAddress(self.handle, addr)
		if func is None:
			return None
		return binaryninja.function.Function(self, func)

	def get_basic_blocks_at(self, addr):
		"""
		``get_basic_blocks_at`` get a list of :py:Class:`BasicBlock` objects which exist at the provided virtual address.

		:param int addr: virtual address of BasicBlock desired
		:return: a list of :py:Class:`BasicBlock` objects
		:rtype: list(BasicBlock)
		"""
		count = ctypes.c_ulonglong(0)
		blocks = core.BNGetBasicBlocksForAddress(self.handle, addr, count)
		result = []
		for i in range(0, count.value):
			result.append(basicblock.BasicBlock(core.BNNewBasicBlockReference(blocks[i]), self))
		core.BNFreeBasicBlockList(blocks, count.value)
		return result

	def get_basic_blocks_starting_at(self, addr):
		"""
		``get_basic_blocks_starting_at`` get a list of :py:Class:`BasicBlock` objects which start at the provided virtual address.

		:param int addr: virtual address of BasicBlock desired
		:return: a list of :py:Class:`BasicBlock` objects
		:rtype: list(BasicBlock)
		"""
		count = ctypes.c_ulonglong(0)
		blocks = core.BNGetBasicBlocksStartingAtAddress(self.handle, addr, count)
		result = []
		for i in range(0, count.value):
			result.append(basicblock.BasicBlock(core.BNNewBasicBlockReference(blocks[i]), self))
		core.BNFreeBasicBlockList(blocks, count.value)
		return result

	def get_recent_basic_block_at(self, addr):
		block = core.BNGetRecentBasicBlockForAddress(self.handle, addr)
		if block is None:
			return None
		return basicblock.BasicBlock(block, self)

	def get_code_refs(self, addr, length=None):
		"""
		``get_code_refs`` returns a list of ReferenceSource objects (xrefs or cross-references) that point to the provided virtual address.
		This function returns both autoanalysis ("auto") and user-specified ("user") xrefs.
		To add a user-specified reference, see :func:`~binaryninja.function.Function.add_user_code_ref`.

		:param int addr: virtual address to query for references
		:param int length: optional length of query
		:return: List of References for the given virtual address
		:rtype: list(ReferenceSource)
		:Example:

			>>> bv.get_code_refs(here)
			[<ref: x86@0x4165ff>]
			>>>

		"""
		count = ctypes.c_ulonglong(0)
		if length is None:
			refs = core.BNGetCodeReferences(self.handle, addr, count)
		else:
			refs = core.BNGetCodeReferencesInRange(self.handle, addr, length, count)
		result = []
		for i in range(0, count.value):
			if refs[i].func:
				func = binaryninja.function.Function(self, core.BNNewFunctionReference(refs[i].func))
			else:
				func = None
			if refs[i].arch:
				arch = binaryninja.architecture.CoreArchitecture._from_cache(refs[i].arch)
			else:
				arch = None
			addr = refs[i].addr
			result.append(binaryninja.architecture.ReferenceSource(func, arch, addr))
		core.BNFreeCodeReferences(refs, count.value)
		return result

	def get_code_refs_from(self, addr, func=None, arch=None, length=None):
		"""
		``get_code_refs_from`` returns a list of virtual addresses referenced by code in the function ``func``,
		of the architecture ``arch``, and at the address ``addr``. If no function is specified, references from
		all functions and containing the address will be returned. If no architecture is specified, the
		architecture of the function will be used.
		This function returns both autoanalysis ("auto") and user-specified ("user") xrefs.
		To add a user-specified reference, see :func:`~binaryninja.function.Function.add_user_code_ref`.

		:param int addr: virtual address to query for references
		:param int length: optional length of query
		:return: list of integers
		:rtype: list(integer)
		"""

		result = []
		funcs = self.get_functions_containing(addr) if func is None else [func]
		if not funcs:
			return []
		for src_func in funcs:
			src_arch = src_func.arch if arch is None else arch
			ref_src = core.BNReferenceSource(src_func.handle, src_arch.handle, addr)
			count = ctypes.c_ulonglong(0)
			if length is None:
				refs = core.BNGetCodeReferencesFrom(self.handle, ref_src, count)
			else:
				refs = core.BNGetCodeReferencesFromInRange(self.handle, ref_src, length, count)
			for i in range(0, count.value):
				result.append(refs[i])
			core.BNFreeAddressList(refs)
		return result

	def get_data_refs(self, addr, length=None):
		"""
		``get_data_refs`` returns a list of virtual addresses of data which references ``addr``. Optionally specifying
		a length. When ``length`` is set ``get_data_refs`` returns the data which references in the range ``addr``-``addr``+``length``.
		This function returns both autoanalysis ("auto") and user-specified ("user") xrefs. To add a user-specified
		reference, see :func:`add_user_data_ref`.

		:param int addr: virtual address to query for references
		:param int length: optional length of query
		:return: list of integers
		:rtype: list(integer)
		:Example:

			>>> bv.get_data_refs(here)
			[4203812]
			>>>
		"""
		count = ctypes.c_ulonglong(0)
		if length is None:
			refs = core.BNGetDataReferences(self.handle, addr, count)
		else:
			refs = core.BNGetDataReferencesInRange(self.handle, addr, length, count)

		result = []
		for i in range(0, count.value):
			result.append(refs[i])
		core.BNFreeDataReferences(refs, count.value)
		return result

	def get_data_refs_from(self, addr, length=None):
		"""
		``get_data_refs_from`` returns a list of virtual addresses referenced by the address ``addr``. Optionally specifying
		a length. When ``length`` is set ``get_data_refs_from`` returns the data referenced in the range ``addr``-``addr``+``length``.
		This function returns both autoanalysis ("auto") and user-specified ("user") xrefs. To add a user-specified
		reference, see :func:`add_user_data_ref`.

		:param int addr: virtual address to query for references
		:param int length: optional length of query
		:return: list of integers
		:rtype: list(integer)
		:Example:

			>>> bv.get_data_refs_from(here)
			[4200327]
			>>>
		"""
		count = ctypes.c_ulonglong(0)
		if length is None:
			refs = core.BNGetDataReferencesFrom(self.handle, addr, count)
		else:
			refs = core.BNGetDataReferencesFromInRange(self.handle, addr, length, count)

		result = []
		for i in range(0, count.value):
			result.append(refs[i])
		core.BNFreeDataReferences(refs, count.value)
		return result


	def add_user_data_ref(self, from_addr, to_addr):
		"""
		``add_user_data_ref`` adds a user-specified data cross-reference (xref) from the address ``from_addr`` to the address ``to_addr``.
		If the reference already exists, no action is performed. To remove the reference, use :func:`remove_user_data_ref`.

		:param int from_addr: the reference's source virtual address.
		:param int to_addr: the reference's destination virtual address.
		:rtype: None
		"""
		core.BNAddUserDataReference(self.handle, from_addr, to_addr)


	def remove_user_data_ref(self, from_addr, to_addr):
		"""
		``remove_user_data_ref`` removes a user-specified data cross-reference (xref) from the address ``from_addr`` to the address ``to_addr``.
		This function will only remove user-specified references, not ones generated during autoanalysis.
		If the reference does not exist, no action is performed.

		:param int from_addr: the reference's source virtual address.
		:param int to_addr: the reference's destination virtual address.
		:rtype: None
		"""
		core.BNRemoveUserDataReference(self.handle, from_addr, to_addr)


	def get_callers(self, addr):
		"""
		``get_callers`` returns a list of ReferenceSource objects (xrefs or cross-references) that call the provided virtual address.
		In this case, tail calls, jumps, and ordinary calls are considered.

		:param int addr: virtual address of callee to query for callers
		:return: List of References that call the given virtual address
		:rtype: list(ReferenceSource)
		:Example:

			>>> bv.get_callers(here)
			[<ref: x86@0x4165ff>]
			>>>

		"""
		count = ctypes.c_ulonglong(0)
		refs = core.BNGetCallers(self.handle, addr, count)
		result = []
		for i in range(0, count.value):
			if refs[i].func:
				func = binaryninja.function.Function(self, core.BNNewFunctionReference(refs[i].func))
			else:
				func = None
			if refs[i].arch:
				arch = binaryninja.architecture.CoreArchitecture._from_cache(refs[i].arch)
			else:
				arch = None
			addr = refs[i].addr
			result.append(binaryninja.architecture.ReferenceSource(func, arch, addr))
		core.BNFreeCodeReferences(refs, count.value)
		return result

	def get_callees(self, addr, func=None, arch=None):
		"""
		``get_callees`` returns a list of virtual addresses called by the call site in the function ``func``,
		of the architecture ``arch``, and at the address ``addr``. If no function is specified, call sites from
		all functions and containing the address will be considered. If no architecture is specified, the
		architecture of the function will be used.

		:param int addr: virtual address of the call site to query for callees
		:param Function func: (optional) the function that the call site belongs to
		:param Architecture func: (optional) the architecture of the call site
		:return: list of integers
		:rtype: list(integer)
		"""

		result = []
		funcs = self.get_functions_containing(addr) if func is None else [func]
		if not funcs:
			return []
		for src_func in funcs:
			src_arch = src_func.arch if arch is None else arch
			ref_src = core.BNReferenceSource(src_func.handle, src_arch.handle, addr)
			count = ctypes.c_ulonglong(0)
			refs = core.BNGetCallees(self.handle, ref_src, count)
			for i in range(0, count.value):
				result.append(refs[i])
			core.BNFreeAddressList(refs)
		return result


	def get_symbol_at(self, addr, namespace=None):
		"""
		``get_symbol_at`` returns the Symbol at the provided virtual address.

		:param int addr: virtual address to query for symbol
		:return: Symbol for the given virtual address
		:param NameSpace namespace: the namespace of the symbols to retrieve
		:rtype: Symbol
		:Example:

			>>> bv.get_symbol_at(bv.entry_point)
			<FunctionSymbol: "_start" @ 0x100001174>
			>>>
		"""
		if isinstance(namespace, str):
			namespace = types.NameSpace(namespace)
		if isinstance(namespace, types.NameSpace):
			namespace = namespace._get_core_struct()

		sym = core.BNGetSymbolByAddress(self.handle, addr, namespace)
		if sym is None:
			return None
		return types.Symbol(None, None, None, handle = sym)

	def get_symbol_by_raw_name(self, name, namespace=None):
		"""
		``get_symbol_by_raw_name`` retrieves a Symbol object for the given a raw (mangled) name.

		:param str name: raw (mangled) name of Symbol to be retrieved
		:return: Symbol object corresponding to the provided raw name
		:param NameSpace namespace: the namespace to search for the given symbol
		:rtype: Symbol
		:Example:

			>>> bv.get_symbol_by_raw_name('?testf@Foobar@@SA?AW4foo@1@W421@@Z')
			<FunctionSymbol: "public: static enum Foobar::foo __cdecl Foobar::testf(enum Foobar::foo)" @ 0x10001100>
			>>>
		"""
		if isinstance(namespace, str):
			namespace = types.NameSpace(namespace)
		if isinstance(namespace, types.NameSpace):
			namespace = namespace._get_core_struct()
		sym = core.BNGetSymbolByRawName(self.handle, name, namespace)
		if sym is None:
			return None
		return types.Symbol(None, None, None, handle = sym)

	def get_symbols_by_name(self, name, namespace=None):
		"""
		``get_symbols_by_name`` retrieves a list of Symbol objects for the given symbol name.

		:param str name: name of Symbol object to be retrieved
		:return: Symbol object corresponding to the provided name
		:param NameSpace namespace: the namespace of the symbol
		:rtype: Symbol
		:Example:

			>>> bv.get_symbols_by_name('?testf@Foobar@@SA?AW4foo@1@W421@@Z')
			[<FunctionSymbol: "public: static enum Foobar::foo __cdecl Foobar::testf(enum Foobar::foo)" @ 0x10001100>]
			>>>
		"""
		if isinstance(namespace, str):
			namespace = types.NameSpace(namespace)
		if isinstance(namespace, types.NameSpace):
			namespace = namespace._get_core_struct()
		count = ctypes.c_ulonglong(0)
		syms = core.BNGetSymbolsByName(self.handle, name, count, namespace)
		result = []
		for i in range(0, count.value):
			result.append(types.Symbol(None, None, None, handle = core.BNNewSymbolReference(syms[i])))
		core.BNFreeSymbolList(syms, count.value)
		return result

	def get_symbols(self, start=None, length=None, namespace=None):
		"""
		``get_symbols`` retrieves the list of all Symbol objects in the optionally provided range.

		:param int start: optional start virtual address
		:param int length: optional length
		:return: list of all Symbol objects, or those Symbol objects in the range of ``start``-``start+length``
		:rtype: list(Symbol)
		:Example:

			>>> bv.get_symbols(0x1000200c, 1)
			[<ImportAddressSymbol: "KERNEL32!IsProcessorFeaturePresent@IAT" @ 0x1000200c>]
			>>>
		"""
		count = ctypes.c_ulonglong(0)
		if isinstance(namespace, str):
			namespace = types.NameSpace(namespace)
		if isinstance(namespace, types.NameSpace):
			namespace = namespace._get_core_struct()
		if start is None:
			syms = core.BNGetSymbols(self.handle, count, namespace)
		else:
			syms = core.BNGetSymbolsInRange(self.handle, start, length, count, namespace)
		result = []
		for i in range(0, count.value):
			result.append(types.Symbol(None, None, None, handle = core.BNNewSymbolReference(syms[i])))
		core.BNFreeSymbolList(syms, count.value)
		return result

	def get_symbols_of_type(self, sym_type, start=None, length=None, namespace=None):
		"""
		``get_symbols_of_type`` retrieves a list of all Symbol objects of the provided symbol type in the optionally
		 provided range.

		:param SymbolType sym_type: A Symbol type: :py:Class:`Symbol`.
		:param int start: optional start virtual address
		:param int length: optional length
		:return: list of all Symbol objects of type sym_type, or those Symbol objects in the range of ``start``-``start+length``
		:rtype: list(Symbol)
		:Example:

			>>> bv.get_symbols_of_type(SymbolType.ImportAddressSymbol, 0x10002028, 1)
			[<ImportAddressSymbol: "KERNEL32!GetCurrentThreadId@IAT" @ 0x10002028>]
			>>>
		"""
		if isinstance(sym_type, str):
			sym_type = SymbolType[sym_type]
		if isinstance(namespace, str):
			namespace = types.NameSpace(namespace)
		if isinstance(namespace, types.NameSpace):
			namespace = namespace._get_core_struct()
		count = ctypes.c_ulonglong(0)
		if start is None:
			syms = core.BNGetSymbolsOfType(self.handle, sym_type, count, namespace)
		else:
			syms = core.BNGetSymbolsOfTypeInRange(self.handle, sym_type, start, length, count)
		result = []
		for i in range(0, count.value):
			result.append(types.Symbol(None, None, None, handle = core.BNNewSymbolReference(syms[i])))
		core.BNFreeSymbolList(syms, count.value)
		return result

	def define_auto_symbol(self, sym):
		"""
		``define_auto_symbol`` adds a symbol to the internal list of automatically discovered Symbol objects in a given
		namespace.

		.. warning:: If multiple symbols for the same address are defined, only the most recent symbol will ever be used.

		:param Symbol sym: the symbol to define
		:rtype: None
		"""
		core.BNDefineAutoSymbol(self.handle, sym.handle)

	def define_auto_symbol_and_var_or_function(self, sym, sym_type, plat=None):
		"""
		``define_auto_symbol_and_var_or_function``

		.. warning:: If multiple symbols for the same address are defined, only the most recent symbol will ever be used.

		:param Symbol sym: the symbol to define
		:param SymbolType sym_type: Type of symbol being defined (can be None)
		:param Platform plat: (optional) platform
		:rtype: None
		"""
		if plat is None:
			plat = self.platform
		elif not isinstance(plat, binaryninja.platform.Platform):
			raise AttributeError("Provided platform is not of type `binaryninja.platform.Platform`")

		if isinstance(sym_type, binaryninja.Type):
			sym_type = sym_type.handle
		elif sym_type is not None:
			raise AttributeError("Provided sym_type is not of type `binaryninja.SymbolType`")

		core.BNDefineAutoSymbolAndVariableOrFunction(self.handle, plat.handle, sym.handle, sym_type)

	def undefine_auto_symbol(self, sym):
		"""
		``undefine_auto_symbol`` removes a symbol from the internal list of automatically discovered Symbol objects.

		:param Symbol sym: the symbol to undefine
		:rtype: None
		"""
		core.BNUndefineAutoSymbol(self.handle, sym.handle)

	def define_user_symbol(self, sym):
		"""
		``define_user_symbol`` adds a symbol to the internal list of user added Symbol objects.

		.. warning:: If multiple symbols for the same address are defined, only the most recent symbol will ever be used.

		:param Symbol sym: the symbol to define
		:rtype: None
		"""
		core.BNDefineUserSymbol(self.handle, sym.handle)

	def undefine_user_symbol(self, sym):
		"""
		``undefine_user_symbol`` removes a symbol from the internal list of user added Symbol objects.

		:param Symbol sym: the symbol to undefine
		:rtype: None
		"""
		core.BNUndefineUserSymbol(self.handle, sym.handle)

	def define_imported_function(self, import_addr_sym, func, type=None):
		"""
		``define_imported_function`` defines an imported Function ``func`` with a ImportedFunctionSymbol type.

		:param Symbol import_addr_sym: A Symbol object with type ImportedFunctionSymbol
		:param Function func: A Function object to define as an imported function
		:rtype: None
		"""
		core.BNDefineImportedFunction(self.handle, import_addr_sym.handle, func.handle, None if type is None else type.handle)

	def create_tag_type(self, name, icon):
		"""
		``create_tag_type`` creates a new Tag Type and adds it to the view

		:param str name: The name for the tag
		:param str icon: The icon (recommended 1 emoji or 2 chars) for the tag
		:return: The created tag type
		:rtype: TagType
		:Example:

			>>> tt = bv.create_tag_type("Crabby Functions", "🦀")
			>>> bv.create_user_data_tag(here, tt, "Get Crabbed")
			>>>
		"""
		tag_type = TagType(core.BNCreateTagType(self.handle, name, icon))
		tag_type.name = name
		tag_type.icon = icon
		core.BNAddTagType(self.handle, tag_type.handle)
		return tag_type

	def remove_tag_type(self, tag_type):
		"""
		``remove_tag_type`` removes a new Tag Type and all tags that use it

		:param TagType tag_type: The Tag Type to remove
		:rtype: None
		"""
		core.BNRemoveTagType(self.handle, tag_type.handle)

	@property
	def tag_types(self):
		"""
		``tag_types`` gets a dictionary of all Tag Types present for the view,
		structured as {Tag Type Name => Tag Type}.

		:rtype: dict of (str, TagType)
		"""
		count = ctypes.c_ulonglong(0)
		types = core.BNGetTagTypes(self.handle, count)
		result = {}
		for i in range(0, count.value):
			tag = TagType(core.BNNewTagTypeReference(types[i]))
			if tag.name in result:
				if type(result[tag.name]) == list:
					result[tag.name].append(tag)
				else:
					result[tag.name] = [result[tag.name], tag]
			else:
				result[tag.name] = tag
		core.BNFreeTagTypeList(types, count.value)
		return result

	def create_user_tag(self, type, data):
		return self.create_tag(type, data, True)

	def create_auto_tag(self, type, data):
		return self.create_tag(type, data, False)

	def create_tag(self, type, data, user=True):
		"""
		``create_tag`` creates a new Tag object but does not add it anywhere.
		Use :py:meth:`create_user_data_tag` to create and add in one step.

		:param TagType type: The Tag Type for this Tag
		:param str data: Additional data for the Tag
		:param bool user
		:return: The created Tag
		:rtype: Tag
		:Example:

			>>> tt = bv.tag_types["Crashes"]
			>>> tag = bv.create_tag(tt, "Null pointer dereference", True)
			>>> bv.add_user_data_tag(here, tag)
			>>>
		"""
		tag = Tag(core.BNCreateTag(type.handle, data))
		core.BNAddTag(self.handle, tag.handle, user)
		return tag

	@property
	def data_tags(self):
		"""
		``data_tags`` gets a list of all data Tags in the view.
		Tags are returned as a list of (address, Tag) pairs.

		:type: list(int, Tag)
		"""
		count = ctypes.c_ulonglong()
		tags = core.BNGetDataTagReferences(self.handle, count)
		result = []
		for i in range(0, count.value):
			tag = Tag(core.BNNewTagReference(tags[i].tag))
			result.append((tags[i].addr, tag))
		core.BNFreeTagReferences(tags, count.value)
		return result

	def get_data_tags_at(self, addr):
		"""
		``get_data_tags_at`` gets a list of all Tags for a data address.

		:param int addr: Address to get tags at
		:return: A list of data Tags
		:rtype: list(Tag)
		"""
		count = ctypes.c_ulonglong()
		tags = core.BNGetDataTags(self.handle, addr, count)
		result = []
		for i in range(0, count.value):
			result.append(Tag(core.BNNewTagReference(tags[i])))
		core.BNFreeTagList(tags, count.value)
		return result

	def get_data_tags_in_range(self, address_range):
		"""
		``get_data_tags_in_range`` gets a list of all data Tags in a given range.
		Range is inclusive at the start, exclusive at the end.

		:param AddressRange address_range: Address range from which to get tags
		:return: A list of data Tags
		:rtype: list(Tag)
		"""
		count = ctypes.c_ulonglong()
		tags = core.BNGetDataTagsInRange(self.handle, address_range.start, address_range.end, count)
		result = []
		for i in range(0, count.value):
			result.append(Tag(core.BNNewTagReference(tags[i])))
		core.BNFreeTagList(tags, count.value)
		return result

	def add_user_data_tag(self, addr, tag):
		"""
		``add_user_data_tag`` adds an already-created Tag object at a data address.
		Since this adds a user tag, it will be added to the current undo buffer.

		:param int addr: Address at which to add the tag
		:param Tag tag: Tag object to be added
		:rtype: None
		"""
		core.BNAddUserDataTag(self.handle, addr, tag.handle)

	def create_user_data_tag(self, addr, type, data, unique=False):
		"""
		``create_user_data_tag`` creates and adds a Tag object at a data
		address. Since this adds a user tag, it will be added to the current
		undo buffer.

		This API is appropriate for generic data tags, for functions,
		consider using :meth:`create_user_function_tag <binaryninja.function.Function.create_user_function_tag>` or for
		specific addresses inside of functions: :meth:`create_user_address_tag <binaryninja.function.Function.create_user_address_tag>`.

		:param int addr: Address at which to add the tag
		:param TagType type: Tag Type for the Tag that is created
		:param str data: Additional data for the Tag
		:param bool unique: If a tag already exists at this location with this data, don't add another
		:return: The created Tag
		:rtype: Tag
		:Example:

			>>> tt = bv.tag_types["Crashes"]
			>>> bv.create_user_data_tag(here, tt, "String data to associate with this tag")
			>>>
		"""
		if unique:
			tags = self.get_data_tags_at(addr)
			for tag in tags:
				if tag.type == type and tag.data == data:
					return tag

		tag = self.create_tag(type, data, True)
		core.BNAddUserDataTag(self.handle, addr, tag.handle)
		return tag

	def remove_user_data_tag(self, addr, tag):
		"""
		``remove_user_data_tag`` removes a Tag object at a data address.
		Since this removes a user tag, it will be added to the current undo buffer.

		:param int addr: Address at which to add the tag
		:param Tag tag: Tag object to be added
		:rtype: None
		"""
		core.BNRemoveUserDataTag(self.handle, addr, tag.handle)

	def add_auto_data_tag(self, addr, tag):
		"""
		``add_auto_data_tag`` adds an already-created Tag object at a data address.

		:param int addr: Address at which to add the tag
		:param Tag tag: Tag object to be added
		:rtype: None
		"""
		core.BNAddAutoDataTag(self.handle, addr, tag.handle)

	def create_auto_data_tag(self, addr, type, data, unique=False):
		"""
		``create_auto_data_tag`` creates and adds a Tag object at a data address.

		:param int addr: Address at which to add the tag
		:param TagType type: Tag Type for the Tag that is created
		:param str data: Additional data for the Tag
		:param bool unique: If a tag already exists at this location with this data, don't add another
		:return: The created Tag
		:rtype: Tag
		"""
		if unique:
			tags = self.get_data_tags_at(addr)
			for tag in tags:
				if tag.type == type and tag.data == data:
					return tag

		tag = self.create_tag(type, data, False)
		core.BNAddAutoDataTag(self.handle, addr, tag.handle)
		return tag

	def remove_auto_data_tag(self, addr, tag):
		"""
		``remove_auto_data_tag`` removes a Tag object at a data address.
		Since this removes a user tag, it will be added to the current undo buffer.

		:param int addr: Address at which to add the tag
		:param Tag tag: Tag object to be added
		:rtype: None
		"""
		core.BNRemoveAutoDataTag(self.handle, addr, tag.handle)

	def can_assemble(self, arch=None):
		"""
		``can_assemble`` queries the architecture plugin to determine if the architecture can assemble instructions.

		:return: True if the architecture can assemble, False otherwise
		:rtype: bool
		:Example:

			>>> bv.can_assemble()
			True
			>>>
		"""
		if arch is None:
			arch = self.arch
		return core.BNCanAssemble(self.handle, arch.handle)

	def is_never_branch_patch_available(self, addr, arch=None):
		"""
		``is_never_branch_patch_available`` queries the architecture plugin to determine if the instruction at the
		instruction at ``addr`` can be made to **never branch**. The actual logic of which is implemented in the
		``perform_is_never_branch_patch_available`` in the corresponding architecture.

		:param int addr: the virtual address of the instruction to be patched
		:param Architecture arch: (optional) the architecture of the instructions if different from the default
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> bv.get_disassembly(0x100012ed)
			'test    eax, eax'
			>>> bv.is_never_branch_patch_available(0x100012ed)
			False
			>>> bv.get_disassembly(0x100012ef)
			'jg      0x100012f5'
			>>> bv.is_never_branch_patch_available(0x100012ef)
			True
			>>>
		"""
		if arch is None:
			arch = self.arch
		return core.BNIsNeverBranchPatchAvailable(self.handle, arch.handle, addr)

	def is_always_branch_patch_available(self, addr, arch=None):
		"""
		``is_always_branch_patch_available`` queries the architecture plugin to determine if the
		instruction at ``addr`` can be made to **always branch**. The actual logic of which is implemented in the
		``perform_is_always_branch_patch_available`` in the corresponding architecture.

		:param int addr: the virtual address of the instruction to be patched
		:param Architecture arch: (optional) the architecture for the current view
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> bv.get_disassembly(0x100012ed)
			'test    eax, eax'
			>>> bv.is_always_branch_patch_available(0x100012ed)
			False
			>>> bv.get_disassembly(0x100012ef)
			'jg      0x100012f5'
			>>> bv.is_always_branch_patch_available(0x100012ef)
			True
			>>>
		"""
		if arch is None:
			arch = self.arch
		return core.BNIsAlwaysBranchPatchAvailable(self.handle, arch.handle, addr)

	def is_invert_branch_patch_available(self, addr, arch=None):
		"""
		``is_invert_branch_patch_available`` queries the architecture plugin to determine if the instruction at ``addr``
		is a branch that can be inverted. The actual logic of which is implemented in the
		``perform_is_invert_branch_patch_available`` in the corresponding architecture.

		:param int addr: the virtual address of the instruction to be patched
		:param Architecture arch: (optional) the architecture of the instructions if different from the default
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> bv.get_disassembly(0x100012ed)
			'test    eax, eax'
			>>> bv.is_invert_branch_patch_available(0x100012ed)
			False
			>>> bv.get_disassembly(0x100012ef)
			'jg      0x100012f5'
			>>> bv.is_invert_branch_patch_available(0x100012ef)
			True
			>>>

		"""
		if arch is None:
			arch = self.arch
		return core.BNIsInvertBranchPatchAvailable(self.handle, arch.handle, addr)

	def is_skip_and_return_zero_patch_available(self, addr, arch=None):
		"""
		``is_skip_and_return_zero_patch_available`` queries the architecture plugin to determine if the
		instruction at ``addr`` is similar to an x86 "call"  instruction which can be made to return zero.  The actual
		logic of which is implemented in the ``perform_is_skip_and_return_zero_patch_available`` in the corresponding
		architecture.

		:param int addr: the virtual address of the instruction to be patched
		:param Architecture arch: (optional) the architecture of the instructions if different from the default
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> bv.get_disassembly(0x100012f6)
			'mov     dword [0x10003020], eax'
			>>> bv.is_skip_and_return_zero_patch_available(0x100012f6)
			False
			>>> bv.get_disassembly(0x100012fb)
			'call    0x10001629'
			>>> bv.is_skip_and_return_zero_patch_available(0x100012fb)
			True
			>>>
		"""
		if arch is None:
			arch = self.arch
		return core.BNIsSkipAndReturnZeroPatchAvailable(self.handle, arch.handle, addr)

	def is_skip_and_return_value_patch_available(self, addr, arch=None):
		"""
		``is_skip_and_return_value_patch_available`` queries the architecture plugin to determine if the
		instruction at ``addr`` is similar to an x86 "call" instruction which can be made to return a value. The actual
		logic of which is implemented in the ``perform_is_skip_and_return_value_patch_available`` in the corresponding
		architecture.

		:param int addr: the virtual address of the instruction to be patched
		:param Architecture arch: (optional) the architecture of the instructions if different from the default
		:return: True if the instruction can be patched, False otherwise
		:rtype: bool
		:Example:

			>>> bv.get_disassembly(0x100012f6)
			'mov     dword [0x10003020], eax'
			>>> bv.is_skip_and_return_value_patch_available(0x100012f6)
			False
			>>> bv.get_disassembly(0x100012fb)
			'call    0x10001629'
			>>> bv.is_skip_and_return_value_patch_available(0x100012fb)
			True
			>>>
		"""
		if arch is None:
			arch = self.arch
		return core.BNIsSkipAndReturnValuePatchAvailable(self.handle, arch.handle, addr)

	def convert_to_nop(self, addr, arch=None):
		"""
		``convert_to_nop`` converts the instruction at virtual address ``addr`` to a nop of the provided architecture.

		.. note:: This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary \
		file must be saved in order to preserve the changes made.

		:param int addr: virtual address of the instruction to convert to nops
		:param Architecture arch: (optional) the architecture of the instructions if different from the default
		:return: True on success, False on failure.
		:rtype: bool
		:Example:

			>>> bv.get_disassembly(0x100012fb)
			'call    0x10001629'
			>>> bv.convert_to_nop(0x100012fb)
			True
			>>> #The above 'call' instruction is 5 bytes, a nop in x86 is 1 byte,
			>>> # thus 5 nops are used:
			>>> bv.get_disassembly(0x100012fb)
			'nop'
			>>> bv.get_next_disassembly()
			'nop'
			>>> bv.get_next_disassembly()
			'nop'
			>>> bv.get_next_disassembly()
			'nop'
			>>> bv.get_next_disassembly()
			'nop'
			>>> bv.get_next_disassembly()
			'mov     byte [ebp-0x1c], al'
		"""
		if arch is None:
			arch = self.arch
		return core.BNConvertToNop(self.handle, arch.handle, addr)

	def always_branch(self, addr, arch=None):
		"""
		``always_branch`` convert the instruction of architecture ``arch`` at the virtual address ``addr`` to an
		unconditional branch.

		.. note:: This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary \
		file must be saved in order to preserve the changes made.

		:param int addr: virtual address of the instruction to be modified
		:param Architecture arch: (optional) the architecture of the instructions if different from the default
		:return: True on success, False on failure.
		:rtype: bool
		:Example:

			>>> bv.get_disassembly(0x100012ef)
			'jg      0x100012f5'
			>>> bv.always_branch(0x100012ef)
			True
			>>> bv.get_disassembly(0x100012ef)
			'jmp     0x100012f5'
			>>>
		"""
		if arch is None:
			arch = self.arch
		return core.BNAlwaysBranch(self.handle, arch.handle, addr)

	def never_branch(self, addr, arch=None):
		"""
		``never_branch`` convert the branch instruction of architecture ``arch`` at the virtual address ``addr`` to
		a fall through.

		.. note:: This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary\
		file must be saved in order to preserve the changes made.

		:param int addr: virtual address of the instruction to be modified
		:param Architecture arch: (optional) the architecture of the instructions if different from the default
		:return: True on success, False on failure.
		:rtype: bool
		:Example:

			>>> bv.get_disassembly(0x1000130e)
			'jne     0x10001317'
			>>> bv.never_branch(0x1000130e)
			True
			>>> bv.get_disassembly(0x1000130e)
			'nop'
			>>>
		"""
		if arch is None:
			arch = self.arch
		return core.BNConvertToNop(self.handle, arch.handle, addr)

	def invert_branch(self, addr, arch=None):
		"""
		``invert_branch`` convert the branch instruction of architecture ``arch`` at the virtual address ``addr`` to the
		inverse branch.

		.. note:: This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary \
		file must be saved in order to preserve the changes made.

		:param int addr: virtual address of the instruction to be modified
		:param Architecture arch: (optional) the architecture of the instructions if different from the default
		:return: True on success, False on failure.
		:rtype: bool
		:Example:

			>>> bv.get_disassembly(0x1000130e)
			'je      0x10001317'
			>>> bv.invert_branch(0x1000130e)
			True
			>>>
			>>> bv.get_disassembly(0x1000130e)
			'jne     0x10001317'
			>>>
		"""
		if arch is None:
			arch = self.arch
		return core.BNInvertBranch(self.handle, arch.handle, addr)

	def skip_and_return_value(self, addr, value, arch=None):
		"""
		``skip_and_return_value`` convert the ``call`` instruction of architecture ``arch`` at the virtual address
		``addr`` to the equivalent of returning a value.

		:param int addr: virtual address of the instruction to be modified
		:param int value: value to make the instruction *return*
		:param Architecture arch: (optional) the architecture of the instructions if different from the default
		:return: True on success, False on failure.
		:rtype: bool
		:Example:

			>>> bv.get_disassembly(0x1000132a)
			'call    0x1000134a'
			>>> bv.skip_and_return_value(0x1000132a, 42)
			True
			>>> #The return value from x86 functions is stored in eax thus:
			>>> bv.get_disassembly(0x1000132a)
			'mov     eax, 0x2a'
			>>>
		"""
		if arch is None:
			arch = self.arch
		return core.BNSkipAndReturnValue(self.handle, arch.handle, addr, value)

	def get_instruction_length(self, addr, arch=None):
		"""
		``get_instruction_length`` returns the number of bytes in the instruction of Architecture ``arch`` at the virtual
		address ``addr``

		:param int addr: virtual address of the instruction query
		:param Architecture arch: (optional) the architecture of the instructions if different from the default
		:return: Number of bytes in instruction
		:rtype: int
		:Example:

			>>> bv.get_disassembly(0x100012f1)
			'xor     eax, eax'
			>>> bv.get_instruction_length(0x100012f1)
			2L
			>>>
		"""
		if arch is None:
			arch = self.arch
		return core.BNGetInstructionLength(self.handle, arch.handle, addr)

	def notify_data_written(self, offset, length):
		core.BNNotifyDataWritten(self.handle, offset, length)

	def notify_data_inserted(self, offset, length):
		core.BNNotifyDataInserted(self.handle, offset, length)

	def notify_data_removed(self, offset, length):
		core.BNNotifyDataRemoved(self.handle, offset, length)

	def get_strings(self, start = None, length = None):
		"""
		``get_strings`` returns a list of strings defined in the binary in the optional virtual address range:
		``start-(start+length)``

		Note that this API will only return strings that have been identified by the string-analysis and thus governed by the minimum and maximum length settings and unrelated to the type system.

		:param int start: optional virtual address to start the string list from, defaults to start of the binary
		:param int length: optional length range to return strings from, defaults to length of the binary
		:return: a list of all strings or a list of strings defined between ``start`` and ``start+length``
		:rtype: list(StringReference)
		:Example:

			>>> bv.get_strings(0x1000004d, 1)
			[<AsciiString: 0x1000004d, len 0x2c>]
			>>>
		"""
		count = ctypes.c_ulonglong(0)
		if start is None:
			strings = core.BNGetStrings(self.handle, count)
		else:
			if length is None:
				length = self.end - start
			strings = core.BNGetStringsInRange(self.handle, start, length, count)
		result = []
		for i in range(0, count.value):
			result.append(StringReference(self, StringType(strings[i].type), strings[i].start, strings[i].length))
		core.BNFreeStringReferenceList(strings)
		return result

	def get_string_at(self, addr, partial=False):
		"""
		``get_string_at`` returns the string that falls on given virtual address.

		.. note:: This returns discovered strings and is therefore governed by `analysis.limits.minStringLength` and other settings. For an alternative API that simply returns any potential c-string at a given location, use :py:BinaryView:`binaryview.get_ascii_string_at`.

		:param int addr: virtual address to get the string from
		:param bool partial: whether to return a partial string reference or not
		:return: returns the StringReference at the given virtual address, otherwise None.
		:rtype: StringReference
		:Example:

			>>> bv.get_string_at(0x40302f)
			<StringType.AsciiString: 0x403028, len 0x12>

		"""
		str_ref = core.BNStringReference()
		if not core.BNGetStringAtAddress(self.handle, addr, str_ref):
			return None
		if str_ref.type != StringType.AsciiString:
			partial = False
			log.log_warn("Partial string not supported at {}".format(hex(addr)))
		start = addr if partial else str_ref.start
		length = str_ref.length - (addr - str_ref.start) if partial else str_ref.length
		return StringReference(self, StringType(str_ref.type), start, length)

	def get_ascii_string_at(self, addr, min_length=4, max_length=None, require_cstring=True):
		"""
		``get_ascii_string_at`` returns an ascii string found at ``addr``.

		.. note:: This returns an ascii string irrespective of whether the core analysis identified a string at that location. For an alternative API that uses existing identified strings, use :py:BinaryView:`binaryview.get_string_at`.

		:param int addr: virtual address to start the string
		:param int min_length: minimum length to define a string
		:param int max_length: max length string to return
		:param bool require_cstring: only return 0x0-terminated strings
		:return: the string found at ``addr`` or None if a string does not exist
		:rtype: StringReference or None
		:Example:

			>>> s1 = bv.get_ascii_string_at(0x70d0)
			>>> s1
			<AsciiString: 0x70d0, len 0xb>
			>>> s1.value
			'AWAVAUATUSH'
			>>> s2 = bv.get_ascii_string_at(0x70d1)
			>>> s2
			<AsciiString: 0x70d1, len 0xa>
			>>> s2.value
			'WAVAUATUSH'
		"""
		if not isinstance(addr, numbers.Integral):
			raise AttributeError("Input address (" + str(addr) + ") is not a number.")
		if addr < self.start or addr >= self.end:
			return None

		br = BinaryReader(self)
		br.seek(addr)
		length = 0
		c = br.read8()
		while c is not None and c > 0 and c <= 0x7f:
			if length == max_length:
				break
			length += 1
			c = br.read8()
		if length < min_length:
			return None
		if require_cstring and c != 0:
			return None
		return StringReference(self, StringType.AsciiString, addr, length)

	def add_analysis_completion_event(self, callback):
		"""
		``add_analysis_completion_event`` sets up a call back function to be called when analysis has been completed.
		This is helpful when using :func:`update_analysis` which does not wait for analysis completion before returning.

		The callee of this function is not responsible for maintaining the lifetime of the returned AnalysisCompletionEvent object.

		.. warning: The built-in python console automatically updates analysis after every command is run, which means this call back may not behave as expected if entered interactively.

		:param callback callback: A function to be called with no parameters when analysis has completed.
		:return: An initialized AnalysisCompletionEvent object.
		:rtype: AnalysisCompletionEvent
		:Example:

			>>> def completionEvent():
			...   print("done")
			...
			>>> bv.add_analysis_completion_event(completionEvent)
			<binaryninja.AnalysisCompletionEvent object at 0x10a2c9f10>
			>>> bv.update_analysis()
			done
			>>>
		"""
		return AnalysisCompletionEvent(self, callback)

	def get_next_function_start_after(self, addr):
		"""
		``get_next_function_start_after`` returns the virtual address of the Function that occurs after the virtual address
		``addr``

		:param int addr: the virtual address to start looking from.
		:return: the virtual address of the next Function
		:rtype: int
		:Example:

			>>> bv.get_next_function_start_after(bv.entry_point)
			268441061L
			>>> hex(bv.get_next_function_start_after(bv.entry_point))
			'0x100015e5L'
			>>> hex(bv.get_next_function_start_after(0x100015e5))
			'0x10001629L'
			>>> hex(bv.get_next_function_start_after(0x10001629))
			'0x1000165eL'
			>>>
		"""
		return core.BNGetNextFunctionStartAfterAddress(self.handle, addr)

	def get_next_basic_block_start_after(self, addr):
		"""
		``get_next_basic_block_start_after`` returns the virtual address of the BasicBlock that occurs after the virtual
		 address ``addr``

		:param int addr: the virtual address to start looking from.
		:return: the virtual address of the next BasicBlock
		:rtype: int
		:Example:

			>>> hex(bv.get_next_basic_block_start_after(bv.entry_point))
			'0x100014a8L'
			>>> hex(bv.get_next_basic_block_start_after(0x100014a8))
			'0x100014adL'
			>>>
		"""
		return core.BNGetNextBasicBlockStartAfterAddress(self.handle, addr)

	def get_next_data_after(self, addr):
		"""
		``get_next_data_after`` retrieves the virtual address of the next non-code byte.

		:param int addr: the virtual address to start looking from.
		:return: the virtual address of the next data byte which is data, not code
		:rtype: int
		:Example:

			>>> hex(bv.get_next_data_after(0x10000000))
			'0x10000001L'
		"""
		return core.BNGetNextDataAfterAddress(self.handle, addr)

	def get_next_data_var_after(self, addr):
		"""
		``get_next_data_var_after`` retrieves the next :py:Class:`DataVariable`, or None.

		:param int addr: the virtual address to start looking from.
		:return: the next :py:Class:`DataVariable`
		:rtype: DataVariable
		:Example:

			>>> bv.get_next_data_var_after(0x10000000)
			<var 0x1000003c: int32_t>
			>>>
		"""
		while True:
			next_data_var_start = core.BNGetNextDataVariableStartAfterAddress(self.handle, addr)
			if next_data_var_start == self.end:
				return None
			var = core.BNDataVariable()
			if not core.BNGetDataVariableAtAddress(self.handle, next_data_var_start, var):
				return None
			if var.address < next_data_var_start:
				addr = var.address + core.BNGetTypeWidth(var.type)
				continue
			break
		return DataVariable(var.address, types.Type(var.type, platform = self.platform, confidence = var.typeConfidence), var.autoDiscovered, self)

	def get_next_data_var_start_after(self, addr):
		"""
		``get_next_data_var_start_after`` retrieves the next virtual address of the next :py:Class:`DataVariable`

		:param int addr: the virtual address to start looking from.
		:return: the virtual address of the next :py:Class:`DataVariable`
		:rtype: int
		:Example:

			>>> hex(bv.get_next_data_var_start_after(0x10000000))
			'0x1000003cL'
			>>> bv.get_data_var_at(0x1000003c)
			<var 0x1000003c: int32_t>
			>>>
		"""
		return core.BNGetNextDataVariableStartAfterAddress(self.handle, addr)

	def get_previous_function_start_before(self, addr):
		"""
		``get_previous_function_start_before`` returns the virtual address of the Function that occurs prior to the
		virtual address provided

		:param int addr: the virtual address to start looking from.
		:return: the virtual address of the previous Function
		:rtype: int
		:Example:

			>>> hex(bv.entry_point)
			'0x1000149fL'
			>>> hex(bv.get_next_function_start_after(bv.entry_point))
			'0x100015e5L'
			>>> hex(bv.get_previous_function_start_before(0x100015e5))
			'0x1000149fL'
			>>>
		"""
		return core.BNGetPreviousFunctionStartBeforeAddress(self.handle, addr)

	def get_previous_basic_block_start_before(self, addr):
		"""
		``get_previous_basic_block_start_before`` returns the virtual address of the BasicBlock that occurs prior to the
		provided virtual address

		:param int addr: the virtual address to start looking from.
		:return: the virtual address of the previous BasicBlock
		:rtype: int
		:Example:

			>>> hex(bv.entry_point)
			'0x1000149fL'
			>>> hex(bv.get_next_basic_block_start_after(bv.entry_point))
			'0x100014a8L'
			>>> hex(bv.get_previous_basic_block_start_before(0x100014a8))
			'0x1000149fL'
			>>>
		"""
		return core.BNGetPreviousBasicBlockStartBeforeAddress(self.handle, addr)

	def get_previous_basic_block_end_before(self, addr):
		"""
		``get_previous_basic_block_end_before``

		:param int addr: the virtual address to start looking from.
		:return: the virtual address of the previous BasicBlock end
		:rtype: int
		:Example:
			>>> hex(bv.entry_point)
			'0x1000149fL'
			>>> hex(bv.get_next_basic_block_start_after(bv.entry_point))
			'0x100014a8L'
			>>> hex(bv.get_previous_basic_block_end_before(0x100014a8))
			'0x100014a8L'
		"""
		return core.BNGetPreviousBasicBlockEndBeforeAddress(self.handle, addr)

	def get_previous_data_before(self, addr):
		"""
		``get_previous_data_before``

		:param int addr: the virtual address to start looking from.
		:return: the virtual address of the previous data (non-code) byte
		:rtype: int
		:Example:

			>>> hex(bv.get_previous_data_before(0x1000001))
			'0x1000000L'
			>>>
		"""
		return core.BNGetPreviousDataBeforeAddress(self.handle, addr)

	def get_previous_data_var_before(self, addr):
		"""
		``get_previous_data_var_before`` retrieves the previous :py:Class:`DataVariable`, or None.

		:param int addr: the virtual address to start looking from.
		:return: the previous :py:Class:`DataVariable`
		:rtype: DataVariable
		:Example:

			>>> bv.get_previous_data_var_before(0x1000003c)
			<var 0x10000000: int16_t>
			>>>
		"""
		prev_data_var_start = core.BNGetPreviousDataVariableStartBeforeAddress(self.handle, addr)
		if prev_data_var_start == addr:
			return None
		var = core.BNDataVariable()
		if not core.BNGetDataVariableAtAddress(self.handle, prev_data_var_start, var):
			return None
		return DataVariable(var.address, types.Type(var.type, platform = self.platform, confidence = var.typeConfidence), var.autoDiscovered, self)

	def get_previous_data_var_start_before(self, addr):
		"""
		``get_previous_data_var_start_before``

		:param int addr: the virtual address to start looking from.
		:return: the virtual address of the previous :py:Class:`DataVariable`
		:rtype: int
		:Example:

			>>> hex(bv.get_previous_data_var_start_before(0x1000003c))
			'0x10000000L'
			>>> bv.get_data_var_at(0x10000000)
			<var 0x10000000: int16_t>
			>>>
		"""
		return core.BNGetPreviousDataVariableStartBeforeAddress(self.handle, addr)

	def get_linear_disassembly_position_at(self, addr, settings=None):
		"""
		``get_linear_disassembly_position_at`` instantiates a :py:class:`LinearViewCursor <binaryninja.lineardisassembly.LinearViewCursor>` object for use in
		:py:meth:`get_previous_linear_disassembly_lines` or :py:meth:`get_next_linear_disassembly_lines`.

		:param int addr: virtual address of linear disassembly position
		:param DisassemblySettings settings: an instantiated :py:class:`DisassemblySettings` object, defaults to None which will use default settings
		:return: An instantiated :py:class:`LinearViewCursor` object for the provided virtual address
		:rtype: LinearViewCursor
		:Example:

			>>> settings = DisassemblySettings()
			>>> pos = bv.get_linear_disassembly_position_at(0x1000149f, settings)
			>>> lines = bv.get_previous_linear_disassembly_lines(pos)
			>>> lines
			[<0x1000149a: pop     esi>, <0x1000149b: pop     ebp>,
			<0x1000149c: retn    0xc>, <0x1000149f: >]
		"""
		pos = lineardisassembly.LinearViewCursor(lineardisassembly.LinearViewObject.disassembly(self, settings))
		pos.seek_to_address(addr)
		return pos

	def get_previous_linear_disassembly_lines(self, pos):
		"""
		``get_previous_linear_disassembly_lines`` retrieves a list of :py:class:`LinearDisassemblyLine` objects for the
		previous disassembly lines, and updates the LinearViewCursor passed in. This function can be called
		repeatedly to get more lines of linear disassembly.

		:param LinearViewCursor pos: Position to start retrieving linear disassembly lines from
		:return: a list of :py:class:`LinearDisassemblyLine` objects for the previous lines.
		:Example:

			>>> settings = DisassemblySettings()
			>>> pos = bv.get_linear_disassembly_position_at(0x1000149a, settings)
			>>> bv.get_previous_linear_disassembly_lines(pos)
			[<0x10001488: push    dword [ebp+0x10 {arg_c}]>, ... , <0x1000149a: >]
			>>> bv.get_previous_linear_disassembly_lines(pos)
			[<0x10001483: xor     eax, eax  {0x0}>, ... , <0x10001488: >]
		"""
		result = []
		while len(result) == 0:
			if not pos.previous():
				return result
			result = pos.lines
		return result

	def get_next_linear_disassembly_lines(self, pos):
		"""
		``get_next_linear_disassembly_lines`` retrieves a list of :py:class:`LinearDisassemblyLine` objects for the
		next disassembly lines, and updates the LinearViewCursor passed in. This function can be called
		repeatedly to get more lines of linear disassembly.

		:param LinearViewCursor pos: Position to start retrieving linear disassembly lines from
		:return: a list of :py:class:`LinearDisassemblyLine` objects for the next lines.
		:Example:

			>>> settings = DisassemblySettings()
			>>> pos = bv.get_linear_disassembly_position_at(0x10001483, settings)
			>>> bv.get_next_linear_disassembly_lines(pos)
			[<0x10001483: xor     eax, eax  {0x0}>, <0x10001485: inc     eax  {0x1}>, ... , <0x10001488: >]
			>>> bv.get_next_linear_disassembly_lines(pos)
			[<0x10001488: push    dword [ebp+0x10 {arg_c}]>, ... , <0x1000149a: >]
			>>>
		"""
		result = []
		while len(result) == 0:
			result = pos.lines
			if not pos.next():
				return result
		return result

	def get_linear_disassembly(self, settings=None):
		"""
		``get_linear_disassembly`` gets an iterator for all lines in the linear disassembly of the view for the given
		disassembly settings.

		.. note:: linear_disassembly doesn't just return disassembly it will return a single line from the linear view,\
		 and thus will contain both data views, and disassembly.

		:param DisassemblySettings settings: instance specifying the desired output formatting. Defaults to None which will use default settings.
		:return: An iterator containing formatted disassembly lines.
		:rtype: LinearDisassemblyIterator
		:Example:

			>>> settings = DisassemblySettings()
			>>> lines = bv.get_linear_disassembly(settings)
			>>> for line in lines:
			...  print(line)
			...  break
			...
			cf fa ed fe 07 00 00 01  ........
		"""
		class LinearDisassemblyIterator(object):
			def __init__(self, view, settings):
				self._view = view
				self._settings = settings

			def __iter__(self):
				pos = lineardisassembly.LinearViewCursor(lineardisassembly.LinearViewObject.disassembly(
					self.view, self.settings))
				while True:
					lines = self._view.get_next_linear_disassembly_lines(pos)
					if len(lines) == 0:
						break
					for line in lines:
						yield line

			@property
			def view(self):
				""" """
				return self._view

			@view.setter
			def view(self, value):
				self._view = value

			@property
			def settings(self):
				""" """
				return self._settings

			@settings.setter
			def settings(self, value):
				self._settings = value


		return iter(LinearDisassemblyIterator(self, settings))

	def parse_type_string(self, text):
		"""
		``parse_type_string`` parses string containing C into a single type :py:Class:`Type`.
		In contrast to the :py:'platform

		:param str text: C source code string of type to create
		:return: A tuple of a :py:Class:`Type` and type name
		:rtype: tuple(Type, QualifiedName)
		:Example:

			>>> bv.parse_type_string("int foo")
			(<type: int32_t>, 'foo')
			>>>
		"""
		if not (isinstance(text, str) or isinstance(text, unicode)):
			raise AttributeError("Source must be a string")
		result = core.BNQualifiedNameAndType()
		errors = ctypes.c_char_p()
		type_list = core.BNQualifiedNameList()
		type_list.count = 0
		if not core.BNParseTypeString(self.handle, text, result, errors, type_list):
			error_str = errors.value.decode("utf-8")
			core.BNFreeString(ctypes.cast(errors, ctypes.POINTER(ctypes.c_byte)))
			raise SyntaxError(error_str)
		type_obj = types.Type(core.BNNewTypeReference(result.type), platform = self.platform)
		name = types.QualifiedName._from_core_struct(result.name)
		core.BNFreeQualifiedNameAndType(result)
		return type_obj, name

	def parse_types_from_string(self, text):
		"""
		``parse_types_from_string`` parses string containing C into a :py:Class:`TypeParserResult` objects. This API
		unlike the :py:Function:`platform.Platform.parse_types_from_source` allows the reference of types already defined
		in the BinaryView.

		:param str text: C source code string of types, variables, and function types, to create
		:return: :py:class:`TypeParserResult` (a SyntaxError is thrown on parse error)
		:rtype: TypeParserResult
		:Example:

			>>> bv.parse_types_from_string('int foo;\\nint bar(int x);\\nstruct bas{int x,y;};\\n')
			({types: {'bas': <type: struct bas>}, variables: {'foo': <type: int32_t>}, functions:{'bar':
			<type: int32_t(int32_t x)>}}, '')
			>>>
		"""
		if not (isinstance(text, str) or isinstance(text, unicode)):
			raise AttributeError("Source must be a string")

		parse = core.BNTypeParserResult()
		errors = ctypes.c_char_p()
		type_list = core.BNQualifiedNameList()
		type_list.count = 0
		if not core.BNParseTypesString(self.handle, text, parse, errors, type_list):
			error_str = errors.value.decode("utf-8")
			core.BNFreeString(ctypes.cast(errors, ctypes.POINTER(ctypes.c_byte)))
			raise SyntaxError(error_str)

		type_dict = {}
		variables = {}
		functions = {}
		for i in range(0, parse.typeCount):
			name = types.QualifiedName._from_core_struct(parse.types[i].name)
			type_dict[name] = types.Type(core.BNNewTypeReference(parse.types[i].type), platform = self.platform)
		for i in range(0, parse.variableCount):
			name = types.QualifiedName._from_core_struct(parse.variables[i].name)
			variables[name] = types.Type(core.BNNewTypeReference(parse.variables[i].type), platform = self.platform)
		for i in range(0, parse.functionCount):
			name = types.QualifiedName._from_core_struct(parse.functions[i].name)
			functions[name] = types.Type(core.BNNewTypeReference(parse.functions[i].type), platform = self.platform)
		core.BNFreeTypeParserResult(parse)
		return types.TypeParserResult(type_dict, variables, functions)

	def parse_possiblevalueset(self, value, state, here=0):
		"""
		Evaluates a string representation of a PossibleValueSet into an instance of the ``PossibleValueSet`` value.

		.. note:: Values are evaluated based on the rules as specified for :py:meth:`parse_expression` API. This implies that a ``ConstantValue [0x4000].d`` can be provided given that 4 bytes can be read at ``0x4000``. All constants are considered to be in hexadecimal form by default.

		The parser uses the following rules:
			- ConstantValue - ``<value>``
			- ConstantPointerValue - ``<value>``
			- StackFrameOffset - ``<value>``
			- SignedRangeValue - ``<value>:<value>:<value>{,<value>:<value>:<value>}*`` (Multiple ValueRanges can be provided by separating them by commas)
			- UnsignedRangeValue - ``<value>:<value>:<value>{,<value>:<value>:<value>}*`` (Multiple ValueRanges can be provided by separating them by commas)
			- InSetOfValues - ``<value>{,<value>}*``
			- NotInSetOfValues - ``<value>{,<value>}*``

		:param str value: PossibleValueSet value to be parsed
		:param RegisterValueType state: State for which the value is to be parsed
		:param int here: (optional) Base address for relative expressions, defaults to zero
		:rtype: PossibleValueSet
		:Example:

			>>> psv_c = bv.parse_possiblevalueset("400", RegisterValueType.ConstantValue)
			>>> psv_c
			<const 0x400>
			>>> psv_ur = bv.parse_possiblevalueset("1:10:1", RegisterValueType.UnsignedRangeValue)
			>>> psv_ur
			<unsigned ranges: [<range: 0x1 to 0x10>]>
			>>> psv_is = bv.parse_possiblevalueset("1,2,3", RegisterValueType.InSetOfValues)
			>>> psv_is
			<in set([0x1, 0x2, 0x3])>
			>>>
		"""
		result = core.BNPossibleValueSet()
		errors = ctypes.c_char_p()
		if value == None:
			value = ''
		if not core.BNParsePossibleValueSet(self.handle, value, state, result, here, errors):
			if errors:
				error_str = errors.value.decode("utf-8")
			else:
				error_str = "Error parsing specified PossibleValueSet"
			core.BNFreePossibleValueSet(result)
			core.BNFreeString(ctypes.cast(errors, ctypes.POINTER(ctypes.c_byte)))
			raise ValueError(error_str)
		return function.PossibleValueSet(self.arch, result)

	def get_type_by_name(self, name):
		"""
		``get_type_by_name`` returns the defined type whose name corresponds with the provided ``name``

		:param QualifiedName name: Type name to lookup
		:return: A :py:Class:`Type` or None if the type does not exist
		:rtype: Type or None
		:Example:

			>>> type, name = bv.parse_type_string("int foo")
			>>> bv.define_user_type(name, type)
			>>> bv.get_type_by_name(name)
			<type: int32_t>
			>>>
		"""
		name = types.QualifiedName(name)._get_core_struct()
		obj = core.BNGetAnalysisTypeByName(self.handle, name)
		if not obj:
			return None
		return types.Type(obj, platform = self.platform)

	def get_type_by_id(self, id):
		"""
		``get_type_by_id`` returns the defined type whose unique identifier corresponds with the provided ``id``

		:param str id: Unique identifier to lookup
		:return: A :py:Class:`Type` or None if the type does not exist
		:rtype: Type or None
		:Example:

			>>> type, name = bv.parse_type_string("int foo")
			>>> type_id = Type.generate_auto_type_id("source", name)
			>>> bv.define_type(type_id, name, type)
			>>> bv.get_type_by_id(type_id)
			<type: int32_t>
			>>>
		"""
		obj = core.BNGetAnalysisTypeById(self.handle, id)
		if not obj:
			return None
		return types.Type(obj, platform = self.platform)

	def get_type_name_by_id(self, id):
		"""
		``get_type_name_by_id`` returns the defined type name whose unique identifier corresponds with the provided ``id``

		:param str id: Unique identifier to lookup
		:return: A QualifiedName or None if the type does not exist
		:rtype: QualifiedName or None
		:Example:

			>>> type, name = bv.parse_type_string("int foo")
			>>> type_id = Type.generate_auto_type_id("source", name)
			>>> bv.define_type(type_id, name, type)
			'foo'
			>>> bv.get_type_name_by_id(type_id)
			'foo'
			>>>
		"""
		name = core.BNGetAnalysisTypeNameById(self.handle, id)
		result = types.QualifiedName._from_core_struct(name)
		core.BNFreeQualifiedName(name)
		if len(result) == 0:
			return None
		return result

	def get_type_id(self, name):
		"""
		``get_type_id`` returns the unique identifier of the defined type whose name corresponds with the
		provided ``name``

		:param QualifiedName name: Type name to lookup
		:return: The unique identifier of the type
		:rtype: str
		:Example:

			>>> type, name = bv.parse_type_string("int foo")
			>>> type_id = Type.generate_auto_type_id("source", name)
			>>> registered_name = bv.define_type(type_id, name, type)
			>>> bv.get_type_id(registered_name) == type_id
			True
			>>>
		"""
		name = types.QualifiedName(name)._get_core_struct()
		return core.BNGetAnalysisTypeId(self.handle, name)

	def add_type_library(self, lib):
		"""
		``add_type_library`` make the contents of a type library available for type/import resolution

		:param TypeLibrary lib: library to register with the view
		:rtype: None
		"""
		if not isinstance(lib, typelibrary.TypeLibrary):
			raise ValueError("must pass in a TypeLibrary object")
		core.BNAddBinaryViewTypeLibrary(self.handle, lib.handle)

	def get_type_library(self, name):
		"""
		``get_type_library`` returns the TypeLibrary

		:param str name: Library name to lookup
		:return: The Type Library object, if any
		:rtype: TypeLibrary or None
		:Example:

		"""
		handle = core.BNGetBinaryViewTypeLibrary(self.handle, name)
		if handle is None:
			return None
		return typelibrary.TypeLibrary(handle)

	def is_type_auto_defined(self, name):
		"""
		``is_type_auto_defined`` queries the user type list of name. If name is not in the *user* type list then the name
		is considered an *auto* type.

		:param QualifiedName name: Name of type to query
		:return: True if the type is not a *user* type. False if the type is a *user* type.
		:Example:
			>>> bv.is_type_auto_defined("foo")
			True
			>>> bv.define_user_type("foo", bv.parse_type_string("struct {int x,y;}")[0])
			>>> bv.is_type_auto_defined("foo")
			False
			>>>
		"""
		name = types.QualifiedName(name)._get_core_struct()
		return core.BNIsAnalysisTypeAutoDefined(self.handle, name)

	def define_type(self, type_id, default_name, type_obj):
		"""
		``define_type`` registers a :py:Class:`Type` ``type_obj`` of the given ``name`` in the global list of types for
		the current :py:Class:`BinaryView`. This method should only be used for automatically generated types.

		:param str type_id: Unique identifier for the automatically generated type
		:param QualifiedName default_name: Name of the type to be registered
		:param Type type_obj: Type object to be registered
		:return: Registered name of the type. May not be the same as the requested name if the user has renamed types.
		:rtype: QualifiedName
		:Example:

			>>> type, name = bv.parse_type_string("int foo")
			>>> registered_name = bv.define_type(Type.generate_auto_type_id("source", name), name, type)
			>>> bv.get_type_by_name(registered_name)
			<type: int32_t>
		"""
		name = types.QualifiedName(default_name)._get_core_struct()
		reg_name = core.BNDefineAnalysisType(self.handle, type_id, name, type_obj.handle)
		result = types.QualifiedName._from_core_struct(reg_name)
		core.BNFreeQualifiedName(reg_name)
		return result

	def define_user_type(self, name, type_obj):
		"""
		``define_user_type`` registers a :py:Class:`Type` ``type_obj`` of the given ``name`` in the global list of user
		types for the current :py:Class:`BinaryView`.

		:param QualifiedName name: Name of the user type to be registered
		:param Type type_obj: Type object to be registered
		:rtype: None
		:Example:

			>>> type, name = bv.parse_type_string("int foo")
			>>> bv.define_user_type(name, type)
			>>> bv.get_type_by_name(name)
			<type: int32_t>
		"""
		name = types.QualifiedName(name)._get_core_struct()
		core.BNDefineUserAnalysisType(self.handle, name, type_obj.handle)

	def undefine_type(self, type_id):
		"""
		``undefine_type`` removes a :py:Class:`Type` from the global list of types for the current :py:Class:`BinaryView`

		:param str type_id: Unique identifier of type to be undefined
		:rtype: None
		:Example:

			>>> type, name = bv.parse_type_string("int foo")
			>>> type_id = Type.generate_auto_type_id("source", name)
			>>> bv.define_type(type_id, name, type)
			>>> bv.get_type_by_name(name)
			<type: int32_t>
			>>> bv.undefine_type(type_id)
			>>> bv.get_type_by_name(name)
			>>>
		"""
		core.BNUndefineAnalysisType(self.handle, type_id)

	def undefine_user_type(self, name):
		"""
		``undefine_user_type`` removes a :py:Class:`Type` from the global list of user types for the current
		:py:Class:`BinaryView`

		:param QualifiedName name: Name of user type to be undefined
		:rtype: None
		:Example:

			>>> type, name = bv.parse_type_string("int foo")
			>>> bv.define_user_type(name, type)
			>>> bv.get_type_by_name(name)
			<type: int32_t>
			>>> bv.undefine_user_type(name)
			>>> bv.get_type_by_name(name)
			>>>
		"""
		name = types.QualifiedName(name)._get_core_struct()
		core.BNUndefineUserAnalysisType(self.handle, name)

	def rename_type(self, old_name, new_name):
		"""
		``rename_type`` renames a type in the global list of types for the current :py:Class:`BinaryView`

		:param QualifiedName old_name: Existing name of type to be renamed
		:param QualifiedName new_name: New name of type to be renamed
		:rtype: None
		:Example:

			>>> type, name = bv.parse_type_string("int foo")
			>>> bv.define_user_type(name, type)
			>>> bv.get_type_by_name("foo")
			<type: int32_t>
			>>> bv.rename_type("foo", "bar")
			>>> bv.get_type_by_name("bar")
			<type: int32_t>
			>>>
		"""
		old_name = types.QualifiedName(old_name)._get_core_struct()
		new_name = types.QualifiedName(new_name)._get_core_struct()
		core.BNRenameAnalysisType(self.handle, old_name, new_name)

	def import_library_type(self, name, lib = None):
		"""
		``import_library_type`` recursively imports a type from the specified type library, or, if
		no library was explicitly provided, the first type library associated with the current :py:Class:`BinaryView`
		that provides the name requested.

		This may have the impact of loading other type libraries as dependencies on other type libraries are lazily resolved
		when references to types provided by them are first encountered.

		Note that the name actually inserted into the view may not match the name as it exists in the type library in
		the event of a name conflict. To aid in this, the :py:Class:`Type` object returned is a `NamedTypeReference` to
		the deconflicted name used.

		:param QualifiedName name:
		:param TypeLibrary lib:
		:return: a `NamedTypeReference` to the type, taking into account any renaming performed
		:rtype: Type
		"""
		if not isinstance(name, types.QualifiedName):
			name = types.QualifiedName(name)
		handle = core.BNBinaryViewImportTypeLibraryType(self.handle, None if lib is None else lib.handle, name._get_core_struct())
		if handle is None:
			return None
		return types.Type(handle, platform = self.platform)

	def import_library_object(self, name, lib = None):
		"""
		``import_library_object`` recursively imports an object from the specified type library, or, if
		no library was explicitly provided, the first type library associated with the current :py:Class:`BinaryView`
		that provides the name requested.

		This may have the impact of loading other type libraries as dependencies on other type libraries are lazily resolved
		when references to types provided by them are first encountered.

		:param QualifiedName name:
		:param TypeLibrary lib:
		:return: the object type, with any interior `NamedTypeReferences` renamed as necessary to be appropriate for the current view
		:rtype: Type
		"""
		if not isinstance(name, types.QualifiedName):
			name = types.QualifiedName(name)
		handle = core.BNBinaryViewImportTypeLibraryObject(self.handle, None if lib is None else lib.handle, name._get_core_struct())
		if handle is None:
			return None
		return types.Type(handle, platform = self.platform)

	def export_type_to_library(self, lib, name, type_obj):
		"""
		``export_type_to_library`` recursively exports ``type_obj`` into ``lib`` as a type with name ``name``

		As other referenced types are encountered, they are either copied into the destination type library or
		else the type library that provided the referenced type is added as a dependency for the destination library.

		:param TypeLibrary lib:
		:param QualifiedName name:
		:param Type type_obj:
		:rtype: None
		"""
		if not isinstance(name, types.QualifiedName):
			name = types.QualifiedName(name)
		if not isinstance(lib, typelibrary.TypeLibrary):
			raise ValueError("lib must be a TypeLibrary object")
		if not isinstance(type_obj, types.Type):
			raise ValueError("type_obj must be a Type object")
		core.BNBinaryViewExportTypeToTypeLibrary(self.handle, lib.handle, name._get_core_struct(), type_obj.handle)

	def export_object_to_library(self, lib, name, type_obj):
		"""
		``export_object_to_library`` recursively exports ``type_obj`` into ``lib`` as an object with name ``name``

		As other referenced types are encountered, they are either copied into the destination type library or
		else the type library that provided the referenced type is added as a dependency for the destination library.

		:param TypeLibrary lib:
		:param QualifiedName name:
		:param Type type_obj:
		:rtype: None
		"""
		if not isinstance(name, types.QualifiedName):
			name = types.QualifiedName(name)
		if not isinstance(lib, typelibrary.TypeLibrary):
			raise ValueError("lib must be a TypeLibrary object")
		if not isinstance(type_obj, types.Type):
			raise ValueError("type_obj must be a Type object")
		core.BNBinaryViewExportObjectToTypeLibrary(self.handle, lib.handle, name._get_core_struct(), type_obj.handle)

	def register_platform_types(self, platform):
		"""
		``register_platform_types`` ensures that the platform-specific types for a :py:Class:`Platform` are available
		for the current :py:Class:`BinaryView`. This is automatically performed when adding a new function or setting
		the default platform.

		:param Platform platform: Platform containing types to be registered
		:rtype: None
		:Example:

			>>> platform = Platform["linux-x86"]
			>>> bv.register_platform_types(platform)
			>>>
		"""
		core.BNRegisterPlatformTypes(self.handle, platform.handle)

	def find_next_data(self, start, data, flags=FindFlag.FindCaseSensitive):
		"""
		``find_next_data`` searches for the bytes ``data`` starting at the virtual address ``start`` until the end of the BinaryView.

		:param int start: virtual address to start searching from.
		:param Union[bytes, bytearray, str] data: data to search for
		:param FindFlag flags: (optional) defaults to case-insensitive data search

			==================== ============================
			FindFlag             Description
			==================== ============================
			FindCaseSensitive    Case-sensitive search
			FindCaseInsensitive  Case-insensitive search
			==================== ============================
		"""
		if not (isinstance(data, bytes) or isinstance(data, bytearray) or isinstance(data, str)):
			raise TypeError("Must be bytes, bytearray, or str")
		else:
			buf = databuffer.DataBuffer(data)
		result = ctypes.c_ulonglong()
		if not core.BNFindNextData(self.handle, start, buf.handle, result, flags):
			return None
		return result.value


	def find_next_text(self, start, text, settings=None, flags=FindFlag.FindCaseSensitive):
		"""
		``find_next_text`` searches for string ``text`` occurring in the linear view output starting at the virtual
		address ``start`` until the end of the BinaryView.

		:param int start: virtual address to start searching from.
		:param str text: text to search for
		:param FindFlag flags: (optional) defaults to case-insensitive data search

			==================== ============================
			FindFlag             Description
			==================== ============================
			FindCaseSensitive    Case-sensitive search
			FindCaseInsensitive  Case-insensitive search
			==================== ============================
		"""
		if not isinstance(text, str):
			raise TypeError("text parameter is not str type")
		if settings is None:
			settings = function.DisassemblySettings()
		if not isinstance(settings, function.DisassemblySettings):
			raise TypeError("settings parameter is not DisassemblySettings type")

		result = ctypes.c_ulonglong()
		if not core.BNFindNextText(self.handle, start, text, result, settings.handle, flags):
			return None
		return result.value

	def find_next_constant(self, start, constant, settings=None):
		"""
		``find_next_constant`` searches for integer constant ``constant`` occurring in the linear view output starting at the virtual
		address ``start`` until the end of the BinaryView.

		:param int start: virtual address to start searching from.
		:param int constant: constant to search for
		:param DisassemblySettings settings: disassembly settings
		"""
		if not isinstance(constant, numbers.Integral):
			raise TypeError("constant parameter is not integral type")
		if settings is None:
			settings = function.DisassemblySettings()
		if not isinstance(settings, function.DisassemblySettings):
			raise TypeError("settings parameter is not DisassemblySettings type")

		result = ctypes.c_ulonglong()
		if not core.BNFindNextConstant(self.handle, start, constant, result, settings.handle):
			return None
		return result.value

	def reanalyze(self):
		"""
		``reanalyze`` causes all functions to be reanalyzed. This function does not wait for the analysis to finish.

		:rtype: None
		"""
		core.BNReanalyzeAllFunctions(self.handle)

	def rebase(self, address, force = False, progress_func = None):
		"""
		``rebase`` rebase the existing :py:class:`BinaryView` into a new :py:class:`BinaryView` at the specified virtual address

		.. note:: This method does not update cooresponding UI components. If the `BinaryView` is associated with
		UI components then initiate the rebase operation within the UI, e.g. using the command palette. If working with views that
		are not associated with UI components while the UI is active, then set ``force`` to ``True`` to enable rebasing.

		:param int address: virtual address of the start of the :py:class:`BinaryView`
		:param bool force: enable rebasing while the UI is active
		:return: the new :py:class:`BinaryView` object or ``None`` on failure
		:rtype: :py:class:`BinaryView` or ``None``
		"""
		result = False
		if core.BNIsUIEnabled() and not force:
			log.log_warn("The BinaryView rebase API does not update cooresponding UI components. If the BinaryView is not associated with the UI rerun with 'force = True'.")
			return None
		if progress_func is None:
			result = core.BNRebase(self.handle, address)
		else:
			result = core.BNRebaseWithProgress(self.handle, address, None, ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong)(
				lambda ctxt, cur, total: progress_func(cur, total)))
		if result:
			return self.get_view_of_type(self.view_type)
		else:
			return None

	def show_plain_text_report(self, title, contents):
		core.BNShowPlainTextReport(self.handle, title, contents)

	def show_markdown_report(self, title, contents, plaintext = ""):
		"""
		``show_markdown_report`` displays the markdown contents in UI applications and plaintext in command-line
		applications. Markdown reports support hyperlinking into the BinaryView. Hyperlinks can be specified as follows:
		``binaryninja://?expr=_start`` Where ``expr=`` specifies an expression parsable by the :py:meth:`parse_expression` API.

		Note: This API functions differently on the command-line vs the UI. In the UI a pop-up is used. On the command-line \
			a simple text prompt is used.

		:param str contents: markdown contents to display
		:param str plaintext: Plain text version to display (used on the command-line)
		:rtype: None
		:Example:
			>>> bv.show_markdown_report("title", "##Contents", "Plain text contents")
			Plain text contents
		"""
		core.BNShowMarkdownReport(self.handle, title, contents, plaintext)

	def show_html_report(self, title, contents, plaintext = ""):
		"""
		``show_html_report`` displays the HTML contents in UI applications and plaintext in command-line
		applications. HTML reports support hyperlinking into the BinaryView. Hyperlinks can be specified as follows:
		``binaryninja://?expr=_start`` Where ``expr=`` specifies an expression parsable by the :py:meth:`parse_expression` API.

		Note: This API function differently on the command-line vs the UI. In the UI a pop-up is used. On the command-line \
			a simple text prompt is used.

		:param str contents: HTML contents to display
		:param str plaintext: Plain text version to display (used on the command-line)
		:rtype: None
		:Example:
			>>> bv.show_html_report("title", "<h1>Contents</h1>", "Plain text contents")
			Plain text contents
		"""
		core.BNShowHTMLReport(self.handle, title, contents, plaintext)

	def show_graph_report(self, title, graph):
		"""
		``show_graph_report`` displays a :py:Class:`FlowGraph` object `graph` in a new tab with ``title``.

		:param title: Title of the graph
		:type title: Plain text string title
		:param graph: The graph you wish to display
		:type graph: :py:Class:`FlowGraph` object
		"""
		core.BNShowGraphReport(self.handle, title, graph.handle)

	def get_address_input(self, prompt, title, current_address = None):
		if current_address is None:
			current_address = self._file.offset
		value = ctypes.c_ulonglong()
		if not core.BNGetAddressInput(value, prompt, title, self.handle, current_address):
			return None
		return value.value

	def add_auto_segment(self, start, length, data_offset, data_length, flags):
		core.BNAddAutoSegment(self.handle, start, length, data_offset, data_length, flags)

	def remove_auto_segment(self, start, length):
		core.BNRemoveAutoSegment(self.handle, start, length)

	def add_user_segment(self, start, length, data_offset, data_length, flags):
		"""
		``add_user_segment`` creates a user-defined segment that specifies how data from the raw file is mapped into a virtual address space.

		:param int start: virtual address of the start of the segment
		:param int length: length of the segment (may be larger than the source data)
		:param int data_offset: offset from the parent view
		:param int data_length: length of the data from the parent view
		:param enums.SegmentFlag flags: SegmentFlags
		:rtype: None
		"""
		core.BNAddUserSegment(self.handle, start, length, data_offset, data_length, flags)

	def remove_user_segment(self, start, length):
		core.BNRemoveUserSegment(self.handle, start, length)

	def get_segment_at(self, addr):
		seg = core.BNGetSegmentAt(self.handle, addr)
		if not seg:
			return None
		return Segment(core.BNNewSegmentReference(seg))

	def get_address_for_data_offset(self, offset):
		"""
		``get_address_for_data_offset`` returns the virtual address that maps to the specific file offset

		:param int offset: file offset
		:return: the virtual address of the first segment that contains that file location
		:rtype: Int
		"""
		address = ctypes.c_ulonglong()
		if not core.BNGetAddressForDataOffset(self.handle, offset, address):
			return None
		return address.value

	def add_auto_section(self, name, start, length, semantics = SectionSemantics.DefaultSectionSemantics,
		type = "", align = 1, entry_size = 1, linked_section = "", info_section = "", info_data = 0):
		core.BNAddAutoSection(self.handle, name, start, length, semantics, type, align, entry_size, linked_section,
			info_section, info_data)

	def remove_auto_section(self, name):
		core.BNRemoveAutoSection(self.handle, name)

	def add_user_section(self, name, start, length, semantics = SectionSemantics.DefaultSectionSemantics,
		type = "", align = 1, entry_size = 1, linked_section = "", info_section = "", info_data = 0):
		"""
		``add_user_section`` creates a user-defined section that can help inform analysis by clarifying what types of
		data exist in what ranges. Note that all data specified must already be mapped by an existing segment.

		:param str name: name of the section
		:param int start: virtual address of the start of the section
		:param int length: length of the section
		:param enums.SectionSemantics semantics: SectionSemantics of the section
		:param str type: optional type
		:param int align: optional byte alignment
		:param int entry_size: optional entry size
		:param str linked_section: optional name of a linked section
		:param str info_section: optional name of an associated informational section
		:param int info_data: optional info data
		:rtype: None
		"""
		core.BNAddUserSection(self.handle, name, start, length, semantics, type, align, entry_size, linked_section,
			info_section, info_data)

	def remove_user_section(self, name):
		core.BNRemoveUserSection(self.handle, name)

	def get_sections_at(self, addr):
		count = ctypes.c_ulonglong(0)
		section_list = core.BNGetSectionsAt(self.handle, addr, count)
		result = []
		for i in range(0, count.value):
			result.append(Section(core.BNNewSectionReference(section_list[i])))
		core.BNFreeSectionList(section_list, count.value)
		return result

	def get_section_by_name(self, name):
		section = core.BNGetSectionByName(self.handle, name)
		if not section:
			return None
		result = Section(core.BNNewSectionReference(section))
		return result

	def get_unique_section_names(self, name_list):
		incoming_names = (ctypes.c_char_p * len(name_list))()
		for i in range(0, len(name_list)):
			incoming_names[i] = binaryninja.cstr(name_list[i])
		outgoing_names = core.BNGetUniqueSectionNames(self.handle, incoming_names, len(name_list))
		result = []
		for i in range(0, len(name_list)):
			result.append(str(outgoing_names[i]))
		core.BNFreeStringList(outgoing_names, len(name_list))
		return result

	@property
	def address_comments(self):
		"""
		Returns a read-only dict of the address comments attached to this BinaryView

		Note that these are different from function-level comments which are specific to each function.
		For annotating code, it is recommended to use comments attached to functions rather than address
		comments attached to the BinaryView. On the other hand, BinaryView comments can be attached to data
		whereas function comments cannot.
		To create a function-level comment, use :func:`~binaryninja.function.Function.add_user_code_ref`.
		"""
		count = ctypes.c_ulonglong()
		addrs = core.BNGetGlobalCommentedAddresses(self.handle, count)
		result = {}
		for i in range(0, count.value):
			result[addrs[i]] = self.get_comment_at(addrs[i])
		core.BNFreeAddressList(addrs)
		return result

	def get_comment_at(self, addr):
		"""
		``get_comment_at`` returns the address-based comment attached to the given address in this BinaryView
		Note that address-based comments are different from function-level comments which are specific to each function.
		For more information, see :func:`address_comments`.
		:param int addr: virtual address within the current BinaryView to apply the comment to
		:rtype: str

		"""
		return core.BNGetGlobalCommentForAddress(self.handle, addr)

	def set_comment_at(self, addr, comment):
		"""
		``set_comment_at`` sets a comment for the BinaryView at the address specified

		Note that these are different from function-level comments which are specific to each function. \
		For more information, see :func:`address_comments`.

		:param int addr: virtual address within the current BinaryView to apply the comment to
		:param str comment: string comment to apply
		:rtype: None
		:Example:

			>>> bv.set_comment_at(here, "hi")

		"""
		core.BNSetGlobalCommentForAddress(self.handle, addr, comment)

	def query_metadata(self, key):
		"""
		`query_metadata` retrieves a metadata associated with the given key stored in the current BinaryView.

		:param str key: key to query
		:rtype: metadata associated with the key
		:Example:

			>>> bv.store_metadata("integer", 1337)
			>>> bv.query_metadata("integer")
			1337L
			>>> bv.store_metadata("list", [1,2,3])
			>>> bv.query_metadata("list")
			[1L, 2L, 3L]
			>>> bv.store_metadata("string", "my_data")
			>>> bv.query_metadata("string")
			'my_data'
		"""
		md_handle = core.BNBinaryViewQueryMetadata(self.handle, key)
		if md_handle is None:
			raise KeyError(key)
		return metadata.Metadata(handle=md_handle).value

	def store_metadata(self, key, md):
		"""
		`store_metadata` stores an object for the given key in the current BinaryView. Objects stored using
		`store_metadata` can be retrieved when the database is reopened. Objects stored are not arbitrary python
		objects! The values stored must be able to be held in a Metadata object. See :py:class:`Metadata`
		for more information. Python objects could obviously be serialized using pickle but this intentionally
		a task left to the user since there is the potential security issues.

		:param str key: key value to associate the Metadata object with
		:param Varies md: object to store.
		:rtype: None
		:Example:

			>>> bv.store_metadata("integer", 1337)
			>>> bv.query_metadata("integer")
			1337L
			>>> bv.store_metadata("list", [1,2,3])
			>>> bv.query_metadata("list")
			[1L, 2L, 3L]
			>>> bv.store_metadata("string", "my_data")
			>>> bv.query_metadata("string")
			'my_data'
		"""
		if not isinstance(md, metadata.Metadata):
			md = metadata.Metadata(md)
		core.BNBinaryViewStoreMetadata(self.handle, key, md.handle)

	def remove_metadata(self, key):
		"""
		`remove_metadata` removes the metadata associated with key from the current BinaryView.

		:param str key: key associated with metadata to remove from the BinaryView
		:rtype: None
		:Example:

			>>> bv.store_metadata("integer", 1337)
			>>> bv.remove_metadata("integer")
		"""
		core.BNBinaryViewRemoveMetadata(self.handle, key)

	def get_load_settings_type_names(self):
		"""
		``get_load_settings_type_names`` retrieve a list :py:class:`BinaryViewType` names for which load settings exist in \
		this :py:class:`BinaryView` context

		:return: list of :py:class:`BinaryViewType` names
		:rtype: list(str)
		"""
		result = []
		count = ctypes.c_ulonglong(0)
		names = core.BNBinaryViewGetLoadSettingsTypeNames(self.handle, count)
		for i in range(count.value):
			result.append(names[i])
		core.BNFreeStringList(names, count)
		return result

	def get_load_settings(self, type_name):
		"""
		``get_load_settings`` retrieve a :py:class:`Settings` object which defines the load settings for the given :py:class:`BinaryViewType` ``type_name``

		:param str type_name: the :py:class:`BinaryViewType` name
		:return: the load settings
		:rtype: :py:class:`Settings`, or ``None``
		"""
		settings_handle = core.BNBinaryViewGetLoadSettings(self.handle, type_name)
		if settings_handle is None:
			return None
		return settings.Settings(handle=settings_handle)

	def set_load_settings(self, type_name, settings):
		"""
		``set_load_settings`` set a :py:class:`Settings` object which defines the load settings for the given :py:class:`BinaryViewType` ``type_name``

		:param str type_name: the :py:class:`BinaryViewType` name
		:param Settings settings: the load settings
		:rtype: None
		"""
		if settings is not None:
			settings = settings.handle
		core.BNBinaryViewSetLoadSettings(self.handle, type_name, settings)

	def __setattr__(self, name, value):
		try:
			object.__setattr__(self, name, value)
		except AttributeError:
			raise AttributeError("attribute '%s' is read only" % name)

	def parse_expression(self, expression, here=0):
		r"""
		Evaluates a string expression to an integer value.

		The parser uses the following rules:

			- Symbols are defined by the lexer as ``[A-Za-z0-9_:<>][A-Za-z0-9_:$\-<>]+`` or anything enclosed in either single or double quotes
			- Symbols are everything in ``bv.symbols``, unnamed DataVariables (i.e. ``data_00005000``), unnamed functions (i.e. ``sub_00005000``), or section names (i.e. ``.text``)
			- Numbers are defaulted to hexadecimal thus `_printf + 10` is equivalent to `printf + 0x10` If decimal numbers required use the decimal prefix.
			- Since numbers and symbols can be ambiguous its recommended that you prefix your numbers with the following:

				- ``0x`` - Hexadecimal
				- ``0n`` - Decimal
				- ``0`` - Octal

			- In the case of an ambiguous number/symbol (one with no prefix) for instance ``12345`` we will first attempt
			  to look up the string as a symbol, if a symbol is found its address is used, otherwise we attempt to convert
			  it to a hexadecimal number.
			- The following operations are valid: ``+, -, \*, /, %, (), &, \|, ^, ~``
			- In addition to the above operators there are dereference operators similar to BNIL style IL:

				- ``[<expression>]`` - read the `current address size` at ``<expression>``
				- ``[<expression>].b`` - read the byte at ``<expression>``
				- ``[<expression>].w`` - read the word (2 bytes) at ``<expression>``
				- ``[<expression>].d`` - read the dword (4 bytes) at ``<expression>``
				- ``[<expression>].q`` - read the quadword (8 bytes) at ``<expression>``

			- The ``$here`` keyword can be used in calculations and is defined as the ``here`` parameter
			- The ``$start``/``$end`` keyword represents the address of the first/last bytes in the file respectively

		:param str expression: Arithmetic expression to be evaluated
		:param int here: (optional) Base address for relative expressions, defaults to zero
		:rtype: int
		"""
		offset = ctypes.c_ulonglong()
		errors = ctypes.c_char_p()
		if not core.BNParseExpression(self.handle, expression, offset, here, errors):
			error_str = errors.value.decode("utf-8")
			core.BNFreeString(ctypes.cast(errors, ctypes.POINTER(ctypes.c_byte)))
			raise ValueError(error_str)
		return offset.value

	def eval(self, expression, here=0):
		"""
		Evaluates an string expression to an integer value. This is a more concise alias for the :py:meth:`parse_expression` API
		"""
		return self.parse_expression(expression, here)


class BinaryReader(object):
	"""
	``class BinaryReader`` is a convenience class for reading binary data.

	BinaryReader can be instantiated as follows and the rest of the document will start from this context ::

		>>> from binaryninja import *
		>>> bv = BinaryViewType.get_view_of_file("/bin/ls")
		>>> br = BinaryReader(bv)
		>>> hex(br.read32())
		'0xfeedfacfL'
		>>>

	Or using the optional endian parameter ::

		>>> from binaryninja import *
		>>> br = BinaryReader(bv, Endianness.BigEndian)
		>>> hex(br.read32())
		'0xcffaedfeL'
		>>>
	"""
	def __init__(self, view, endian = None):
		self.handle = core.BNCreateBinaryReader(view.handle)
		if endian is None:
			core.BNSetBinaryReaderEndianness(self.handle, view.endianness)
		else:
			core.BNSetBinaryReaderEndianness(self.handle, endian)

	def __del__(self):
		core.BNFreeBinaryReader(self.handle)

	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))

	@property
	def endianness(self):
		"""
		The Endianness to read data. (read/write)

		:getter: returns the endianness of the reader
		:setter: sets the endianness of the reader (BigEndian or LittleEndian)
		:type: Endianness
		"""
		return core.BNGetBinaryReaderEndianness(self.handle)

	@endianness.setter
	def endianness(self, value):
		core.BNSetBinaryReaderEndianness(self.handle, value)

	@property
	def offset(self):
		"""
		The current read offset (read/write).

		:getter: returns the current internal offset
		:setter: sets the internal offset
		:type: int
		"""
		return core.BNGetReaderPosition(self.handle)

	@offset.setter
	def offset(self, value):
		core.BNSeekBinaryReader(self.handle, value)

	@property
	def eof(self):
		"""
		Is end of file (read-only)

		:getter: returns boolean, true if end of file, false otherwise
		:type: bool
		"""
		return core.BNIsEndOfFile(self.handle)

	def read(self, length):
		"""
		``read`` returns ``length`` bytes read from the current offset, adding ``length`` to offset.

		:param int length: number of bytes to read.
		:return: ``length`` bytes from current offset
		:rtype: str, or None on failure
		:Example:

			>>> br.read(8)
			'\\xcf\\xfa\\xed\\xfe\\x07\\x00\\x00\\x01'
			>>>
		"""
		dest = ctypes.create_string_buffer(length)
		if not core.BNReadData(self.handle, dest, length):
			return None
		return dest.raw

	def read8(self):
		"""
		``read8`` returns a one byte integer from offset incrementing the offset.

		:return: byte at offset.
		:rtype: int, or None on failure
		:Example:

			>>> br.seek(0x100000000)
			>>> br.read8()
			207
			>>>
		"""
		result = ctypes.c_ubyte()
		if not core.BNRead8(self.handle, result):
			return None
		return result.value

	def read16(self):
		"""
		``read16`` returns a two byte integer from offset incrementing the offset by two, using specified endianness.

		:return: a two byte integer at offset.
		:rtype: int, or None on failure
		:Example:

			>>> br.seek(0x100000000)
			>>> hex(br.read16())
			'0xfacf'
			>>>
		"""
		result = ctypes.c_ushort()
		if not core.BNRead16(self.handle, result):
			return None
		return result.value

	def read32(self):
		"""
		``read32`` returns a four byte integer from offset incrementing the offset by four, using specified endianness.

		:return: a four byte integer at offset.
		:rtype: int, or None on failure
		:Example:

			>>> br.seek(0x100000000)
			>>> hex(br.read32())
			'0xfeedfacfL'
			>>>
		"""
		result = ctypes.c_uint()
		if not core.BNRead32(self.handle, result):
			return None
		return result.value

	def read64(self):
		"""
		``read64`` returns an eight byte integer from offset incrementing the offset by eight, using specified endianness.

		:return: an eight byte integer at offset.
		:rtype: int, or None on failure
		:Example:

			>>> br.seek(0x100000000)
			>>> hex(br.read64())
			'0x1000007feedfacfL'
			>>>
		"""
		result = ctypes.c_ulonglong()
		if not core.BNRead64(self.handle, result):
			return None
		return result.value

	def read16le(self):
		"""
		``read16le`` returns a two byte little endian integer from offset incrementing the offset by two.

		:return: a two byte integer at offset.
		:rtype: int, or None on failure
		:Example:

			>>> br.seek(0x100000000)
			>>> hex(br.read16le())
			'0xfacf'
			>>>
		"""
		result = self.read(2)
		if (result is None) or (len(result) != 2):
			return None
		return struct.unpack("<H", result)[0]

	def read32le(self):
		"""
		``read32le`` returns a four byte little endian integer from offset incrementing the offset by four.

		:return: a four byte integer at offset.
		:rtype: int, or None on failure
		:Example:

			>>> br.seek(0x100000000)
			>>> hex(br.read32le())
			'0xfeedfacf'
			>>>
		"""
		result = self.read(4)
		if (result is None) or (len(result) != 4):
			return None
		return struct.unpack("<I", result)[0]

	def read64le(self):
		"""
		``read64le`` returns an eight byte little endian integer from offset incrementing the offset by eight.

		:return: a eight byte integer at offset.
		:rtype: int, or None on failure
		:Example:

			>>> br.seek(0x100000000)
			>>> hex(br.read64le())
			'0x1000007feedfacf'
			>>>
		"""
		result = self.read(8)
		if (result is None) or (len(result) != 8):
			return None
		return struct.unpack("<Q", result)[0]

	def read16be(self):
		"""
		``read16be`` returns a two byte big endian integer from offset incrementing the offset by two.

		:return: a two byte integer at offset.
		:rtype: int, or None on failure
		:Example:

			>>> br.seek(0x100000000)
			>>> hex(br.read16be())
			'0xcffa'
			>>>
		"""
		result = self.read(2)
		if (result is None) or (len(result) != 2):
			return None
		return struct.unpack(">H", result)[0]

	def read32be(self):
		"""
		``read32be`` returns a four byte big endian integer from offset incrementing the offset by four.

		:return: a four byte integer at offset.
		:rtype: int, or None on failure
		:Example:

			>>> br.seek(0x100000000)
			>>> hex(br.read32be())
			'0xcffaedfe'
			>>>
		"""
		result = self.read(4)
		if (result is None) or (len(result) != 4):
			return None
		return struct.unpack(">I", result)[0]

	def read64be(self):
		"""
		``read64be`` returns an eight byte big endian integer from offset incrementing the offset by eight.

		:return: a eight byte integer at offset.
		:rtype: int, or None on failure
		:Example:

			>>> br.seek(0x100000000)
			>>> hex(br.read64be())
			'0xcffaedfe07000001L'
		"""
		result = self.read(8)
		if (result is None) or (len(result) != 8):
			return None
		return struct.unpack(">Q", result)[0]

	def seek(self, offset):
		"""
		``seek`` update internal offset to ``offset``.

		:param int offset: offset to set the internal offset to
		:rtype: None
		:Example:

			>>> hex(br.offset)
			'0x100000008L'
			>>> br.seek(0x100000000)
			>>> hex(br.offset)
			'0x100000000L'
			>>>
		"""
		core.BNSeekBinaryReader(self.handle, offset)

	def seek_relative(self, offset):
		"""
		``seek_relative`` updates the internal offset by ``offset``.

		:param int offset: offset to add to the internal offset
		:rtype: None
		:Example:

			>>> hex(br.offset)
			'0x100000008L'
			>>> br.seek_relative(-8)
			>>> hex(br.offset)
			'0x100000000L'
			>>>
		"""
		core.BNSeekBinaryReaderRelative(self.handle, offset)

	def __setattr__(self, name, value):
		try:
			object.__setattr__(self, name, value)
		except AttributeError:
			raise AttributeError("attribute '%s' is read only" % name)


class BinaryWriter(object):
	"""
	``class BinaryWriter`` is a convenience class for writing binary data.

	BinaryWriter can be instantiated as follows and the rest of the document will start from this context ::

		>>> from binaryninja import *
		>>> bv = BinaryViewType.get_view_of_file("/bin/ls")
		>>> br = BinaryReader(bv)
		>>> br.offset
		4294967296
		>>> bw = BinaryWriter(bv)
		>>>

	Or using the optional endian parameter ::

		>>> from binaryninja import *
		>>> bv = BinaryViewType.get_view_of_file("/bin/ls")
		>>> br = BinaryReader(bv, Endianness.BigEndian)
		>>> bw = BinaryWriter(bv, Endianness.BigEndian)
		>>>
	"""
	def __init__(self, view, endian = None):
		self.handle = core.BNCreateBinaryWriter(view.handle)
		if endian is None:
			core.BNSetBinaryWriterEndianness(self.handle, view.endianness)
		else:
			core.BNSetBinaryWriterEndianness(self.handle, endian)

	def __del__(self):
		core.BNFreeBinaryWriter(self.handle)

	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))

	@property
	def endianness(self):
		"""
		The Endianness to written data. (read/write)

		:getter: returns the endianness of the reader
		:setter: sets the endianness of the reader (BigEndian or LittleEndian)
		:type: Endianness
		"""
		return core.BNGetBinaryWriterEndianness(self.handle)

	@endianness.setter
	def endianness(self, value):
		core.BNSetBinaryWriterEndianness(self.handle, value)

	@property
	def offset(self):
		"""
		The current write offset (read/write).

		:getter: returns the current internal offset
		:setter: sets the internal offset
		:type: int
		"""
		return core.BNGetWriterPosition(self.handle)

	@offset.setter
	def offset(self, value):
		core.BNSeekBinaryWriter(self.handle, value)

	def write(self, value):
		"""
		``write`` writes ``len(value)`` bytes to the internal offset, without regard to endianness.

		:param str value: bytes to be written at current offset
		:return: boolean True on success, False on failure.
		:rtype: bool
		:Example:

			>>> bw.write("AAAA")
			True
			>>> br.read(4)
			'AAAA'
			>>>
		"""

		value = cstr(value)
		buf = ctypes.create_string_buffer(len(value))
		ctypes.memmove(buf, value, len(value))
		return core.BNWriteData(self.handle, buf, len(value))

	def write8(self, value):
		"""
		``write8`` lowest order byte from the integer ``value`` to the current offset.

		:param str value: bytes to be written at current offset
		:return: boolean
		:rtype: bool
		:Example:

			>>> bw.write8(0x42)
			True
			>>> br.read(1)
			'B'
			>>>
		"""
		return core.BNWrite8(self.handle, value)

	def write16(self, value):
		"""
		``write16`` writes the lowest order two bytes from the integer ``value`` to the current offset, using internal endianness.

		:param int value: integer value to write.
		:return: boolean True on success, False on failure.
		:rtype: bool
		"""
		return core.BNWrite16(self.handle, value)

	def write32(self, value):
		"""
		``write32`` writes the lowest order four bytes from the integer ``value`` to the current offset, using internal endianness.

		:param int value: integer value to write.
		:return: boolean True on success, False on failure.
		:rtype: bool
		"""
		return core.BNWrite32(self.handle, value)

	def write64(self, value):
		"""
		``write64`` writes the lowest order eight bytes from the integer ``value`` to the current offset, using internal endianness.

		:param int value: integer value to write.
		:return: boolean True on success, False on failure.
		:rtype: bool
		"""
		return core.BNWrite64(self.handle, value)

	def write16le(self, value):
		"""
		``write16le`` writes the lowest order two bytes from the little endian integer ``value`` to the current offset.

		:param int value: integer value to write.
		:return: boolean True on success, False on failure.
		:rtype: bool
		"""
		value = struct.pack("<H", value)
		return self.write(value)

	def write32le(self, value):
		"""
		``write32le`` writes the lowest order four bytes from the little endian integer ``value`` to the current offset.

		:param int value: integer value to write.
		:return: boolean True on success, False on failure.
		:rtype: bool
		"""
		value = struct.pack("<I", value)
		return self.write(value)

	def write64le(self, value):
		"""
		``write64le`` writes the lowest order eight bytes from the little endian integer ``value`` to the current offset.

		:param int value: integer value to write.
		:return: boolean True on success, False on failure.
		:rtype: bool
		"""
		value = struct.pack("<Q", value)
		return self.write(value)

	def write16be(self, value):
		"""
		``write16be`` writes the lowest order two bytes from the big endian integer ``value`` to the current offset.

		:param int value: integer value to write.
		:return: boolean True on success, False on failure.
		:rtype: bool
		"""
		value = struct.pack(">H", value)
		return self.write(value)

	def write32be(self, value):
		"""
		``write32be`` writes the lowest order four bytes from the big endian integer ``value`` to the current offset.

		:param int value: integer value to write.
		:return: boolean True on success, False on failure.
		:rtype: bool
		"""
		value = struct.pack(">I", value)
		return self.write(value)

	def write64be(self, value):
		"""
		``write64be`` writes the lowest order eight bytes from the big endian integer ``value`` to the current offset.

		:param int value: integer value to write.
		:return: boolean True on success, False on failure.
		:rtype: bool
		"""
		value = struct.pack(">Q", value)
		return self.write(value)

	def seek(self, offset):
		"""
		``seek`` update internal offset to ``offset``.

		:param int offset: offset to set the internal offset to
		:rtype: None
		:Example:

			>>> hex(bw.offset)
			'0x100000008L'
			>>> bw.seek(0x100000000)
			>>> hex(bw.offset)
			'0x100000000L'
			>>>
		"""
		core.BNSeekBinaryWriter(self.handle, offset)

	def seek_relative(self, offset):
		"""
		``seek_relative`` updates the internal offset by ``offset``.

		:param int offset: offset to add to the internal offset
		:rtype: None
		:Example:

			>>> hex(bw.offset)
			'0x100000008L'
			>>> bw.seek_relative(-8)
			>>> hex(bw.offset)
			'0x100000000L'
			>>>
		"""
		core.BNSeekBinaryWriterRelative(self.handle, offset)

class StructuredDataValue(object):
	def __init__(self, type, address, value, endian):
		self._type = type
		self._address = address
		self._value = value
		self._endian = endian

	def __str__(self):
		decode_str = "{}B".format(self._type.width)
		return ' '.join(["{:02x}".format(x) for x in struct.unpack(decode_str, self._value)])

	def __repr__(self):
		return "<StructuredDataValue type:{} value:{}>".format(str(self._type), str(self))

	def __int__(self):
		if self._type.width == 1:
			if self._endian == Endianness.LittleEndian:
				code = "<B"
			else:
				code = ">B"
		elif self._type.width == 2:
			if self._endian == Endianness.LittleEndian:
				code = "<H"
			else:
				code = ">H"
		elif self._type.width == 4:
			if self._endian == Endianness.LittleEndian:
				code = "<I"
			else:
				code = ">I"
		elif self._type.width == 8:
			if self._endian == Endianness.LittleEndian:
				code = "<Q"
			else:
				code = ">Q"
		else:
			raise Exception("Could not convert to integer with width {}".format(self._type.width))

		return struct.unpack(code, self._value)[0]

	@property
	def type(self):
		return self._type

	@property
	def width(self):
		return self._type.width

	@property
	def address(self):
		return self._address

	@property
	def value(self):
		return self._value

	@property
	def int(self):
		return int(self)

	@property
	def str(self):
		return str(self)


class StructuredDataView(object):
	"""
		``class StructuredDataView`` is a convenience class for reading structured binary data.

		StructuredDataView can be instantiated as follows:

			>>> from binaryninja import *
			>>> bv = BinaryViewType.get_view_of_file("/bin/ls")
			>>> structure = "Elf64_Header"
			>>> address = bv.start
			>>> elf = StructuredDataView(bv, structure, address)
			>>>

		Once instantiated, members can be accessed:

			>>> print("{:x}".format(elf.machine))
			003e
			>>>

		"""
	_structure = None
	_structure_name = None
	_address = 0
	_bv = None

	def __init__(self, bv, structure_name, address):
		self._bv = bv
		self._structure_name = structure_name
		self._address = address
		self._members = OrderedDict()
		self._endian = bv.arch.endianness

		self._lookup_structure()
		self._define_members()

	def __repr__(self):
		return "<StructuredDataView type:{} size:{:#x} address:{:#x}>".format(self._structure_name,
																			  self._structure.width, self._address)

	def __len__(self):
		return self._structure.width

	def __getattr__(self, key):
		m = self._members.get(key, None)
		if m is None:
			return self.__getattribute__(key)

		return self[key]

	def __getitem__(self, key):
		m = self._members.get(key, None)
		if m is None:
			return m

		ty = m.type
		offset = m.offset
		width = ty.width

		value = self._bv.read(self._address + offset, width)
		return StructuredDataValue(ty, self._address + offset, value, self._endian)

	def __str__(self):
		rv = "struct {name} 0x{addr:x} {{\n".format(name=self._structure_name, addr=self._address)
		for k in self._members:
			m = self._members[k]

			ty = m.type
			offset = m.offset

			formatted_offset = "{:=+x}".format(offset)
			formatted_type = "{:s} {:s}".format(str(ty), k)

			value = self[k]
			if value.width in (1, 2, 4, 8):
				formatted_value = str.zfill("{:x}".format(value.int), value.width * 2)
			else:
				formatted_value = str(value)

			rv += "\t{:>6s} {:40s} = {:30s}\n".format(formatted_offset, formatted_type, formatted_value)

		rv += "}\n"

		return rv

	def _lookup_structure(self):
		s = self._bv.get_type_by_name(self._structure_name)
		if s is None:
			raise Exception("Could not find structure with name: {}".format(self._structure_name))

		if s.type_class != TypeClass.StructureTypeClass:
			raise Exception("{} is not a StructureTypeClass, got: {}".format(self._structure_name, s._type_class))

		self._structure = s.structure

	def _define_members(self):
		for m in self._structure.members:
			self._members[m.name] = m