sleigh-sys 0.1.0

Rust bindings for Ghidra's Sleigh decompiler
Documentation
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
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "ifacedecomp.hh"
extern "C" {
#include <time.h>
}
#include "pcodeparse.hh"
#include "blockaction.hh"

// Constructing this registers the capability
IfaceDecompCapability IfaceDecompCapability::ifaceDecompCapability;

IfaceDecompCapability::IfaceDecompCapability(void)

{
  name = "decomp";
}

void IfaceDecompCapability::registerCommands(IfaceStatus *status)

{
  status->registerCom(new IfcComment(),"//"); //Note: A space must follow this when used.
  status->registerCom(new IfcComment(),"#"); //Note: A space must follow this when used.
  status->registerCom(new IfcComment(),"%"); //Note: A space must follow this when used.
  status->registerCom(new IfcQuit(),"quit");
  status->registerCom(new IfcHistory(),"history");
  status->registerCom(new IfcOpenfile(),"openfile");
  status->registerCom(new IfcOpenfile(),"openfile", "write");
  status->registerCom(new IfcOpenfileAppend(),"openfile","append");
  status->registerCom(new IfcClosefile(),"closefile");
  status->registerCom(new IfcEcho(),"echo");

  status->registerCom(new IfcSource(),"source");
  status->registerCom(new IfcOption(),"option");
  status->registerCom(new IfcParseFile(),"parse","file");
  status->registerCom(new IfcParseLine(),"parse","line");
  status->registerCom(new IfcAdjustVma(),"adjust","vma");
  status->registerCom(new IfcFuncload(),"load","function");
  status->registerCom(new IfcAddrrangeLoad(),"load","addr");
  status->registerCom(new IfcReadSymbols(),"read","symbols");
  status->registerCom(new IfcCleararch(),"clear","architecture");
  status->registerCom(new IfcMapaddress(),"map","address");
  status->registerCom(new IfcMaphash(),"map","hash");
  status->registerCom(new IfcMapfunction(),"map","function");
  status->registerCom(new IfcMapexternalref(),"map","externalref");
  status->registerCom(new IfcMaplabel(),"map","label");
  status->registerCom(new IfcMapconvert(),"map","convert");
  status->registerCom(new IfcPrintdisasm(),"disassemble");
  status->registerCom(new IfcDecompile(),"decompile");
  status->registerCom(new IfcDump(),"dump");
  status->registerCom(new IfcDumpbinary(),"binary");
  status->registerCom(new IfcForcegoto(),"force","goto");
  status->registerCom(new IfcForceHex(),"force","hex");
  status->registerCom(new IfcForceDec(),"force","dec");
  status->registerCom(new IfcProtooverride(),"override","prototype");
  status->registerCom(new IfcJumpOverride(),"override","jumptable");
  status->registerCom(new IfcFlowOverride(),"override","flow");
  status->registerCom(new IfcDeadcodedelay(),"deadcode","delay");
  status->registerCom(new IfcGlobalAdd(),"global","add");
  status->registerCom(new IfcGlobalRemove(),"global","remove");
  status->registerCom(new IfcGlobalify(),"global","spaces");
  status->registerCom(new IfcGlobalRegisters(),"global","registers");
  status->registerCom(new IfcGraphDataflow(),"graph","dataflow");
  status->registerCom(new IfcGraphControlflow(),"graph","controlflow");
  status->registerCom(new IfcGraphDom(),"graph","dom");
  status->registerCom(new IfcPrintLanguage(),"print","language");
  status->registerCom(new IfcPrintCStruct(),"print","C");
  status->registerCom(new IfcPrintCFlat(),"print","C","flat");
  status->registerCom(new IfcPrintCGlobals(),"print","C","globals");
  status->registerCom(new IfcPrintCTypes(),"print","C","types");
  status->registerCom(new IfcPrintCXml(),"print","C","xml");
  status->registerCom(new IfcPrintParamMeasures(),"print","parammeasures");
  status->registerCom(new IfcProduceC(),"produce","C");
  status->registerCom(new IfcProducePrototypes(),"produce","prototypes");
  status->registerCom(new IfcPrintRaw(),"print","raw");
  status->registerCom(new IfcPrintInputs(),"print","inputs");
  status->registerCom(new IfcPrintInputsAll(),"print","inputs","all");
  status->registerCom(new IfcListaction(),"list","action");
  status->registerCom(new IfcListOverride(),"list","override");
  status->registerCom(new IfcListprototypes(),"list","prototypes");
  status->registerCom(new IfcSetcontextrange(),"set","context");
  status->registerCom(new IfcSettrackedrange(),"set","track");
  status->registerCom(new IfcBreakstart(),"break","start");
  status->registerCom(new IfcBreakaction(),"break","action");
  status->registerCom(new IfcPrintSpaces(),"print","spaces");
  status->registerCom(new IfcPrintHigh(),"print","high");
  status->registerCom(new IfcPrintTree(),"print","tree","varnode");
  status->registerCom(new IfcPrintBlocktree(),"print","tree","block");
  status->registerCom(new IfcPrintLocalrange(),"print","localrange");
  status->registerCom(new IfcPrintMap(),"print","map");
  status->registerCom(new IfcPrintVarnode(),"print","varnode");
  status->registerCom(new IfcPrintCover(),"print","cover","high");
  status->registerCom(new IfcVarnodeCover(),"print","cover","varnode");
  status->registerCom(new IfcVarnodehighCover(),"print","cover","varnodehigh");
  status->registerCom(new IfcPrintExtrapop(),"print","extrapop");
  status->registerCom(new IfcPrintActionstats(),"print","actionstats");
  status->registerCom(new IfcResetActionstats(),"reset","actionstats");
  status->registerCom(new IfcCountPcode(),"count","pcode");
  status->registerCom(new IfcTypeVarnode(),"type","varnode");
  status->registerCom(new IfcNameVarnode(),"name","varnode");
  status->registerCom(new IfcRename(),"rename");
  status->registerCom(new IfcRetype(),"retype");
  status->registerCom(new IfcRemove(),"remove");
  status->registerCom(new IfcLockPrototype(),"prototype","lock");
  status->registerCom(new IfcUnlockPrototype(),"prototype","unlock");
  status->registerCom(new IfcCommentInstr(),"comment","instruction");
  status->registerCom(new IfcDuplicateHash(),"duplicate","hash");
  status->registerCom(new IfcCallGraphBuild(),"callgraph","build");
  status->registerCom(new IfcCallGraphBuildQuick(),"callgraph","build","quick");
  status->registerCom(new IfcCallGraphDump(),"callgraph","dump");
  status->registerCom(new IfcCallGraphLoad(),"callgraph","load");
  status->registerCom(new IfcCallGraphList(),"callgraph","list");
  status->registerCom(new IfcCallFixup(),"fixup","call");
  status->registerCom(new IfcCallOtherFixup(),"fixup","callother");
  status->registerCom(new IfcVolatile(),"volatile");
  status->registerCom(new IfcReadonly(),"readonly");
  status->registerCom(new IfcPointerSetting(),"pointer","setting");
  status->registerCom(new IfcPreferSplit(),"prefersplit");
  status->registerCom(new IfcStructureBlocks(),"structure","blocks");
  status->registerCom(new IfcAnalyzeRange(), "analyze","range");
  status->registerCom(new IfcLoadTestFile(), "load","test","file");
  status->registerCom(new IfcListTestCommands(), "list","test","commands");
  status->registerCom(new IfcExecuteTestCommand(), "execute","test","command");
#ifdef CPUI_RULECOMPILE
  status->registerCom(new IfcParseRule(),"parse","rule");
  status->registerCom(new IfcExperimentalRules(),"experimental","rules");
#endif
  status->registerCom(new IfcContinue(),"continue");
#ifdef OPACTION_DEBUG
  status->registerCom(new IfcDebugAction(),"debug","action");
  status->registerCom(new IfcTraceBreak(),"trace","break");
  status->registerCom(new IfcTraceAddress(),"trace","address");
  status->registerCom(new IfcTraceEnable(),"trace","enable");
  status->registerCom(new IfcTraceDisable(),"trace","disable");
  status->registerCom(new IfcTraceClear(),"trace","clear");
  status->registerCom(new IfcTraceList(),"trace","list");
  status->registerCom(new IfcBreakjump(),"break","jumptable");
#endif
}

/// Runs over every function in the scope, or any sub-scope , calling
/// iterationCallback()
/// \param scope is the given scope
void IfaceDecompCommand::iterateScopesRecursive(Scope *scope)

{
  if (!scope->isGlobal()) return;
  iterateFunctionsAddrOrder(scope);
  ScopeMap::const_iterator iter,enditer;
  iter = scope->childrenBegin();
  enditer = scope->childrenEnd();
  for(;iter!=enditer;++iter) {
    iterateScopesRecursive((*iter).second);
  }
}

/// Runs over every function in the scope calling iterationCallback().
/// \param scope is the given scope
void IfaceDecompCommand::iterateFunctionsAddrOrder(Scope *scope)

{
  MapIterator miter,menditer;
  miter = scope->begin();
  menditer = scope->end();
  while(miter != menditer) {
    Symbol *sym = (*miter)->getSymbol();
    FunctionSymbol *fsym = dynamic_cast<FunctionSymbol *>(sym);
    ++miter;
    if (fsym != (FunctionSymbol *)0)
	iterationCallback(fsym->getFunction());
  }
}

/// Scopes are traversed depth-first, then within a scope, functions are
/// traversed in address order.
void IfaceDecompCommand::iterateFunctionsAddrOrder(void)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No architecture loaded");
  iterateScopesRecursive(dcp->conf->symboltab->getGlobalScope());
}

/// Traversal is based on the current CallGraph for the program.
/// Child functions are traversed before their parents.
void IfaceDecompCommand::iterateFunctionsLeafOrder(void)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No architecture loaded");

  if (dcp->cgraph == (CallGraph *)0)
    throw IfaceExecutionError("No callgraph present");

  CallGraphNode *node;
  node = dcp->cgraph->initLeafWalk();
  while(node != (CallGraphNode *)0) {
    if (node->getName().size()==0) continue; // Skip if has no name
    Funcdata *fd = node->getFuncdata();
    if (fd != (Funcdata *)0)
      iterationCallback(fd);
    node = dcp->cgraph->nextLeaf(node);
  }
}

IfaceDecompData::IfaceDecompData(void)

{
  conf = (Architecture *)0;
  fd = (Funcdata *)0;
  cgraph = (CallGraph *)0;
  testCollection = (FunctionTestCollection *)0;
#ifdef OPACTION_DEBUG
  jumptabledebug = false;
#endif
}

IfaceDecompData::~IfaceDecompData(void)

{
  if (cgraph != (CallGraph *)0)
    delete cgraph;
  if (conf != (Architecture *)0)
    delete conf;
  if (testCollection != (FunctionTestCollection *)0)
    delete testCollection;
// fd will get deleted with Database
}

void IfaceDecompData::allocateCallGraph(void)

{
  if (cgraph != (CallGraph *)0)
    delete cgraph;
  cgraph = new CallGraph(conf);
}

/// This is called if a command throws a low-level error.
/// It clears any analysis on the function, sets the current function
/// to null, and issues a warning.
/// \param s is the stream to write the warning to
void IfaceDecompData::abortFunction(ostream &s)

{
  if (fd == (Funcdata *)0) return;
  s << "Unable to proceed with function: " << fd->getName() << endl;
  conf->clearAnalysis(fd);
  fd = (Funcdata *)0;
}

void IfaceDecompData::clearArchitecture(void)

{
  if (conf != (Architecture *)0)
    delete conf;
  conf = (Architecture *)0;
  fd = (Funcdata *)0;
}

/// \class IfcComment
/// \brief A comment within a command script: `% A comment in a script`
///
/// This commands does nothing but attaches to comment tokens like:
///   - \#
///   - %
///   - //
///
/// allowing comment lines in a script file
void IfcComment::execute(istream &s)
{
  //Do nothing
}

/// \class IfcOption
/// \brief Adjust a decompiler option: `option <optionname> [<param1>] [<param2>] [<param3>]`
///
/// Passes command-line parameters to an ArchOption object registered with
/// the current architecture's OptionDatabase.  Options are looked up by name
/// and can be configure with up to 3 parameters.  Options generally report success
/// or failure back to the console.
void IfcOption::execute(istream &s)

{
  string optname;
  string p1,p2,p3;
  
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");
  s >> ws >> optname >> ws;
  if (optname.size()==0)
    throw IfaceParseError("Missing option name");
  if (!s.eof()) {
    s >> p1 >> ws;
    if (!s.eof()) {
      s >> p2 >> ws;
      if (!s.eof()) {
	s >> p3 >> ws;
	if (!s.eof())
	  throw IfaceParseError("Too many option parameters");
      }
    }
  }
  
  try {
    string res = dcp->conf->options->set(optname,p1,p2,p3);
    *status->optr << res << endl;
  }
  catch(ParseError &err) {
    *status->optr << err.explain << endl;
    throw IfaceParseError("Bad option");
  }
  catch(RecovError &err) {
    *status->optr << err.explain << endl;
    throw IfaceExecutionError("Bad option");
  }
}

/// \class IfcParseFile
/// \brief Parse a file with C declarations: `parse file <filename>`
///
/// The file must contain C syntax data-type and function declarations.
/// Data-types become part of the program, and function declarations,
/// if the symbol already exists, associate the prototype with the symbol.
void IfcParseFile::execute(istream &s)

{  
  if (dcp->conf == (Architecture *)0) 
    throw IfaceExecutionError("No load image present");

  string filename;
  ifstream fs;

  s >> ws >> filename;
  if (filename.empty())
    throw IfaceParseError("Missing filename");

  fs.open( filename.c_str() );
  if (!fs)
    throw IfaceExecutionError("Unable to open file: "+filename);

  try {				// Try to parse the file
    parse_C(dcp->conf,fs);
  }
  catch(ParseError &err) {
    *status->optr << "Error in C syntax: " << err.explain << endl;
    throw IfaceExecutionError("Bad C syntax");
  }
  fs.close();
}

/// \class IfcParseLine
/// \brief Parse a line of C syntax: `parse line ...`
///
/// The line can contain a declaration either a data-type or a function prototype:
///    - `parse line typedef int4 *specialint;`
///    - `parse line struct mystruct { int4 a; int4 b; }`
///    - `parse line extern void myfunc(int4 a,int4 b);`
///
/// Data-types go straight into the program.  For a prototype, the function symbol
/// must already exist.
void IfcParseLine::execute(istream &s)

{  
  if (dcp->conf == (Architecture *)0) 
    throw IfaceExecutionError("No load image present");

  s >> ws;
  if (s.eof())
    throw IfaceParseError("No input");

  try {				// Try to parse the line
    parse_C(dcp->conf,s);
  }
  catch(ParseError &err) {
    *status->optr << "Error in C syntax: " << err.explain << endl;
    throw IfaceExecutionError("Bad C syntax");
  }
}

/// \class IfcAdjustVma
/// \brief Change the base address of the load image: `adjust vma 0xabcd0123`
///
/// The provided parameter is added to the current base address of the image.
/// This only affects the address of bytes in the image and so should be done
/// before functions and other symbols are layed down.
void IfcAdjustVma::execute(istream &s)

{
  unsigned long adjust;

  adjust = 0uL;
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");
  s.unsetf(ios::dec | ios::hex | ios::oct); // Let user specify base
  s >> ws >> adjust;
  if (adjust == 0uL)
    throw IfaceParseError("No adjustment parameter");
  dcp->conf->loader->adjustVma(adjust);
}

#ifdef OPACTION_DEBUG
static void jump_callback(Funcdata &orig,Funcdata &fd);
#endif

/// \brief Generate raw p-code for the current function
///
/// Follow flow from the entry point of the function and generate the
/// raw p-code ops for all instructions, up to \e return instructions.
/// If a \e size in bytes is provided, it bounds the memory region where flow
/// can be followed.  Otherwise, a zero \e size allows unbounded flow tracing.
/// \param s is a output stream for reporting function details or errors
/// \param size (if non-zero) is the maximum number of bytes to disassemble
void IfaceDecompData::followFlow(ostream &s,int4 size)

{
#ifdef OPACTION_DEBUG
  if (jumptabledebug)
    fd->enableJTCallback(jump_callback);
#endif
  try {
    if (size==0) {
      Address baddr(fd->getAddress().getSpace(),0);
      Address eaddr(fd->getAddress().getSpace(),fd->getAddress().getSpace()->getHighest());
      fd->followFlow(baddr,eaddr);
    }
    else
      fd->followFlow(fd->getAddress(),fd->getAddress()+size);
    s << "Function " << fd->getName() << ": ";
    fd->getAddress().printRaw(s);
    s << endl;
  } catch(RecovError &err) {
    s << "Function " << fd->getName() << ": " << err.explain << endl;
  }
}

/// \class IfcFuncload
/// \brief Make a specific function current: `load function <functionname>`
///
/// The name must be a fully qualified symbol with "::" separating namespaces.
/// If the symbol represents a function, that function becomes \e current for
/// the console. If there are bytes for the function, raw p-code and control-flow
/// are calculated.
void IfcFuncload::execute(istream &s)

{
  string funcname;
  Address offset;

  s >> funcname;

  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No image loaded");

  string basename;
  Scope *funcscope = dcp->conf->symboltab->resolveScopeFromSymbolName(funcname,"::",basename,(Scope *)0);
  if (funcscope == (Scope *)0)
    throw IfaceExecutionError("Bad namespace: "+funcname);
  dcp->fd = funcscope->queryFunction( basename ); // Is function already in database
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("Unknown function name: "+funcname);

  if (!dcp->fd->hasNoCode())
    dcp->followFlow(*status->optr,0);
}

/// \class IfcAddrrangeLoad
/// \brief Create a new function at an address: `load addr <address> [<funcname>]`
///
/// A new function is created at the provided address.  If a name is provided, this
/// becomes the function symbol, otherwise a default name is generated.
/// The function becomes \e current for the interface, and if bytes are present,
/// raw p-code and control-flow are generated.
void IfcAddrrangeLoad::execute(istream &s)

{
  int4 size;
  string name;
  Address offset=parse_machaddr(s,size,*dcp->conf->types); // Read required address

  s >> ws;
  if (size <= offset.getAddrSize()) // Was a real size specified
    size = 0;
  if (dcp->conf->loader == (LoadImage *)0)
    throw IfaceExecutionError("No binary loaded");

  s >> name;			// Read optional name
  if (name.empty())
    dcp->conf->nameFunction(offset,name); // Pick default name if necessary
  dcp->fd = dcp->conf->symboltab->getGlobalScope()->addFunction( offset,name)->getFunction();
  dcp->followFlow(*status->optr,size);
}

/// \class IfcCleararch
/// \brief Clear the current architecture/program: `clear architecture`
void IfcCleararch::execute(istream &s)

{
  dcp->clearArchitecture();
}

/// \class IfcReadSymbols
/// \brief Read in symbols from the load image: `read symbols`
///
/// If the load image format encodes symbol information.  These are
/// read in and attached to the appropriate address.
void IfcReadSymbols::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0) 
    throw IfaceExecutionError("No load image present");
  if (dcp->conf->loader == (LoadImage *)0)
    throw IfaceExecutionError("No binary loaded");

  dcp->conf->readLoaderSymbols("::");
}

/// \class IfcMapaddress
/// \brief Map a new symbol into the program: `map address <address> <typedeclaration>`
///
/// Create a new variable in the current scope
/// \code
///    map address r0x1000 int4 globalvar
/// \endcode
/// The symbol specified in the type declaration can qualify the namespace using the "::"
/// specifier.  If there is a current function, the variable is local to the function.
/// Otherwise the symbol is created relative to the global scope.
void IfcMapaddress::execute(istream &s)

{
  Datatype *ct;
  string name;
  int4 size;
  Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read required address;

  s >> ws;
  ct = parse_type(s,name,dcp->conf); // Parse the required type
  if (dcp->fd != (Funcdata *)0) {
    Symbol *sym;
    sym = dcp->fd->getScopeLocal()->addSymbol(name,ct,addr,Address())->getSymbol();
    sym->getScope()->setAttribute(sym,Varnode::namelock|Varnode::typelock);
  }
  else {
    Symbol *sym;
    uint4 flags = Varnode::namelock|Varnode::typelock;
    flags |= dcp->conf->symboltab->getProperty(addr); // Inherit existing properties
    string basename;
    Scope *scope = dcp->conf->symboltab->findCreateScopeFromSymbolName(name, "::", basename, (Scope *)0);
    sym = scope->addSymbol(basename,ct,addr,Address())->getSymbol();
    sym->getScope()->setAttribute(sym,flags);
    if (scope->getParent() != (Scope *)0) {		// If this is a global namespace scope
      SymbolEntry *e = sym->getFirstWholeMap();		// Adjust range
      dcp->conf->symboltab->addRange(scope,e->getAddr().getSpace(),e->getFirst(),e->getLast());
    }
  }

}

/// \class IfcMaphash
/// \brief Add a dynamic symbol to the current function: `map hash <address> <hash> <typedeclaration>`
///
/// The command only creates local variables for the current function.
/// The name and data-type are taken from a C syntax type declaration.  The symbol is
/// not associated with a particular storage address but with a specific Varnode in the data-flow,
/// specified by a code address and hash of the local data-flow structure.
void IfcMaphash::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function loaded");
  Datatype *ct;
  string name;
  uint8 hash;
  int4 size;
  Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read pc address of hash

  s >> hex >> hash;		// Parse the hash value
  s >> ws;
  ct = parse_type(s,name,dcp->conf); // Parse the required type and name

  Symbol *sym = dcp->fd->getScopeLocal()->addDynamicSymbol(name,ct,addr,hash);
  sym->getScope()->setAttribute(sym,Varnode::namelock|Varnode::typelock);
}

/// \class IfcMapfunction
/// \brief Create a new function: `map function <address> [<functionname>] [nocode]`
///
/// Create a new function symbol at the provided address.
/// A symbol name can be provided, otherwise a default name is selected.
/// The new function becomes \e current for the console.
/// The provided address gives the entry point for the function.  Unless the final keyword
/// "nocode" is provided, the underlying bytes in the load image are used for any
/// future disassembly or decompilation.
void IfcMapfunction::execute(istream &s)

{
  string name;
  int4 size;
  if ((dcp->conf == (Architecture *)0)||(dcp->conf->loader == (LoadImage *)0))
    throw IfaceExecutionError("No binary loaded");

  Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read required address;

  s >> name;			// Read optional name
  if (name.empty())
    dcp->conf->nameFunction(addr,name); // Pick default name if necessary
  string basename;
  Scope *scope = dcp->conf->symboltab->findCreateScopeFromSymbolName(name, "::", basename, (Scope *)0);
  dcp->fd = scope->addFunction(addr,name)->getFunction();

  string nocode;
  s >> ws >> nocode;
  if (nocode == "nocode")
    dcp->fd->setNoCode(true);
}

/// \class IfcMapexternalref
/// \brief Create an external ref symbol `map externalref <address> <refaddress> [<name>]`
///
/// Creates a symbol for a function pointer and associates a specific address as
/// a value for that symbol.  The first address specified is the address of the symbol,
/// The second address is the address referred to by the pointer.  Indirect calls
/// through the function pointer will be converted to direct calls to the referred address.
/// A symbol name can be provided, otherwise a default one is generated.
void IfcMapexternalref::execute(istream &s)

{
  int4 size1,size2;
  Address addr1 = parse_machaddr(s,size1,*dcp->conf->types); // Read externalref address
  Address addr2 = parse_machaddr(s,size2,*dcp->conf->types); // Read referred to address
  string name;

  s >> name;			// Read optional name

  dcp->conf->symboltab->getGlobalScope()->addExternalRef(addr1,addr2,name);
}

/// \class IfcMaplabel
/// \brief Create a code label: `map label <name> <address>`
///
/// Label a specific code address.  This creates a LabSymbol which is usually
/// an internal control-flow target.  The symbol is local to the \e current function
/// if it exists, otherwise the symbol is added to the global scope.
void IfcMaplabel::execute(istream &s)

{
  string name;
  s >> name;
  if (name.size()==0)
    throw IfaceParseError("Need label name and address");
  int4 size;
  Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read address

  Scope *scope;
  if (dcp->fd != (Funcdata *)0)
    scope = dcp->fd->getScopeLocal();
  else
    scope = dcp->conf->symboltab->getGlobalScope();

  Symbol *sym = scope->addCodeLabel(addr,name);
  scope->setAttribute(sym,Varnode::namelock|Varnode::typelock);
}

/// \class IfcMapconvert
/// \brief Create an convert directive: `map convert <format> <value> <address> <hash>`
///
/// Creates a \e convert directive that causes a targeted constant value to be displayed
/// with the specified integer format.  The constant is specified by \e value, and the
/// \e address of the p-code op using the constant plus a dynamic \e hash is also given.
void IfcMapconvert::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function loaded");
  string name;
  uintb value;
  uint8 hash;
  int4 size;
  uint4 format = 0;

  s >> name;		// Parse the format token
  if (name == "hex")
    format = Symbol::force_hex;
  else if (name == "dec")
    format = Symbol::force_dec;
  else if (name == "bin")
    format = Symbol::force_bin;
  else if (name == "oct")
    format = Symbol::force_oct;
  else if (name == "char")
    format = Symbol::force_char;
  else
    throw IfaceParseError("Bad convert format");

  s >> ws >> hex >> value;
  Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read pc address of hash

  s >> hex >> hash;		// Parse the hash value

  dcp->fd->getScopeLocal()->addConvertSymbol(format, value, addr, hash);
}

/// \class IfcPrintdisasm
/// \brief Print disassembly of a memory range: `disassemble [<address1> <address2>]`
///
/// If no addresses are provided, disassembly for the current function is displayed.
/// Otherwise disassembly is between the two provided addresses.
void IfcPrintdisasm::execute(istream &s)

{
  Architecture *glb;
  Address addr;
  int4 size;
  // TODO add partial listings

  s >> ws;
  if (s.eof()) {
    if (dcp->fd == (Funcdata *)0)
      throw IfaceExecutionError("No function selected");
    *status->fileoptr << "Assembly listing for " << dcp->fd->getName() << endl;
    addr = dcp->fd->getAddress();
    size = dcp->fd->getSize();
    glb = dcp->fd->getArch();
  }
  else {
    addr = parse_machaddr(s,size,*dcp->conf->types); // Read beginning address
    s >> ws;
    Address offset2=parse_machaddr(s,size,*dcp->conf->types);
    size = offset2.getOffset() - addr.getOffset();
    glb = dcp->conf;
  }
  IfaceAssemblyEmit assem(status->fileoptr,10);
  while(size > 0) {
    int4 sz;
    sz = glb->translate->printAssembly(assem,addr);
    addr = addr + sz;
    size -= sz;
  }
}

/// \class IfcDump
/// \brief Display bytes in the load image: `dump <address+size>`
///
/// The command does a hex listing of the specific memory region.
void IfcDump::execute(istream &s)

{
  int4 size;
  uint1 *buffer;
  Address offset = parse_machaddr(s,size,*dcp->conf->types);

  buffer = dcp->conf->loader->load(size,offset);
  print_data(*status->fileoptr,buffer,size,offset);
  delete [] buffer;
}

/// \class IfcDumpbinary
/// \brief Dump a memory to file: `binary <address+size> <filename>`
///
/// Raw bytes from the specified memory region in the load image are written
/// to a file.
void IfcDumpbinary::execute(istream &s)

{
  int4 size;
  uint1 *buffer;
  Address offset = parse_machaddr(s,size,*dcp->conf->types);
  string filename;

  s >> ws;
  if (s.eof())
    throw IfaceParseError("Missing file name for binary dump");
  s >> filename;
  ofstream os;
  os.open(filename.c_str());
  if (!os)
    throw IfaceExecutionError("Unable to open file "+filename);

  buffer = dcp->conf->loader->load(size,offset);
  os.write((const char *)buffer,size);
  delete [] buffer;
  os.close();
}

/// \class IfcDecompile
/// \brief Decompile the current function: `decompile`
///
/// Decompilation is started for the current function. Any previous decompilation
/// analysis on the function is cleared first.  The process respects
/// any active break points or traces, so decompilation may not complete.
void IfcDecompile::execute(istream &s)

{
  int4 res;

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  if (dcp->fd->hasNoCode()) {
    *status->optr << "No code for " << dcp->fd->getName() << endl;
    return;
  }
  if (dcp->fd->isProcStarted()) { // Free up old decompile
    *status->optr << "Clearing old decompilation" << endl;
    dcp->conf->clearAnalysis(dcp->fd);
  }
    
  *status->optr << "Decompiling " << dcp->fd->getName() << endl;
  dcp->conf->allacts.getCurrent()->reset(*dcp->fd);
  res = dcp->conf->allacts.getCurrent()->perform( *dcp->fd );
  if (res<0) {
    *status->optr << "Break at ";
    dcp->conf->allacts.getCurrent()->printState(*status->optr);
  }
  else {
    *status->optr << "Decompilation complete";
    if (res==0)
      *status->optr << " (no change)";
  }
  *status->optr << endl;
}

/// \class IfcPrintCFlat
/// \brief Print current function without control-flow: `print C flat`
void IfcPrintCFlat::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  dcp->conf->print->setOutputStream(status->fileoptr);
  dcp->conf->print->setFlat(true);
  dcp->conf->print->docFunction(dcp->fd);
  dcp->conf->print->setFlat(false);
}

/// \class IfcPrintCGlobals
/// \brief Print declarations for any known global variables: `print C globals`
void IfcPrintCGlobals::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0) 
    throw IfaceExecutionError("No load image present");

  dcp->conf->print->setOutputStream(status->fileoptr);
  dcp->conf->print->docAllGlobals();
}

/// \class IfcPrintCTypes
/// \brief Print any known type definitions: `print C types`
void IfcPrintCTypes::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0) 
    throw IfaceExecutionError("No load image present");

  if (dcp->conf->types != (TypeFactory *)0) {
    dcp->conf->print->setOutputStream(status->fileoptr);
    dcp->conf->print->docTypeDefinitions(dcp->conf->types);
  }
}

/// \class IfcPrintCXml
/// \brief Print the current function with C syntax and XML markup:`print C xml`
void IfcPrintCXml::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  dcp->conf->print->setOutputStream(status->fileoptr);
  dcp->conf->print->setXML(true);
  dcp->conf->print->docFunction(dcp->fd);
  dcp->conf->print->setXML(false);
}

/// \class IfcPrintCStruct
/// \brief Print the current function using C syntax:`print C`
void IfcPrintCStruct::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  dcp->conf->print->setOutputStream(status->fileoptr);
  dcp->conf->print->docFunction(dcp->fd);
}

/// \class IfcPrintLanguage
/// \brief Print current output using a specific language: `print language <langname>`
///
/// The current function must already be decompiled.
void IfcPrintLanguage::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  s >> ws;
  if (s.eof())
    throw IfaceParseError("No print language specified");
  string langroot;
  s >> langroot;
  langroot = langroot + "-language";

  string curlangname = dcp->conf->print->getName();
  dcp->conf->setPrintLanguage(langroot);
  dcp->conf->print->setOutputStream(status->fileoptr);
  dcp->conf->print->docFunction(dcp->fd);
  dcp->conf->setPrintLanguage(curlangname); // Reset to original language
}

/// \class IfcPrintRaw
/// \brief Print the raw p-code for the \e current function: `print raw`
///
/// Each p-code op, in its present state, is printed to the console, labeled
/// with the address of its original instruction and any output and input varnodes.
void IfcPrintRaw::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  dcp->fd->printRaw(*status->fileoptr);
}

/// \class IfcListaction
/// \brief List all current actions and rules for the decompiler: `list action`
void IfcListaction::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("Decompile action not loaded");
  dcp->conf->allacts.getCurrent()->print(*status->fileoptr,0,0);
}

/// \class IfcListOverride
/// \brief Display any overrides for the current function: `list override`
///
/// Overrides include:
///   - Forced gotos
///   - Dead code delays
///   - Indirect call overrides
///   - Indirect prototype overrides
void IfcListOverride::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  *status->optr << "Function: " << dcp->fd->getName() << endl;
  dcp->fd->getOverride().printRaw(*status->optr,dcp->conf);
}

/// \class IfcListprototypes
/// \brief List known prototype models: `list prototypes`
///
/// All prototype models are listed with markup indicating the
/// \e default, the evaluation model for the active function, and
/// the evaluation model for called functions.
void IfcListprototypes::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");
  
  map<string,ProtoModel *>::const_iterator iter;
  for(iter=dcp->conf->protoModels.begin();iter!=dcp->conf->protoModels.end();++iter) {
    ProtoModel *model = (*iter).second;
    *status->optr << model->getName();
    if (model == dcp->conf->defaultfp)
      *status->optr << " default";
    else if (model == dcp->conf->evalfp_called)
      *status->optr << " eval called";
    else if (model == dcp->conf->evalfp_current)
      *status->optr << " eval current";
    *status->optr << endl;
  }
}

/// \class IfcSetcontextrange
/// \brief Set a context variable: `set context <name> <value> [<startaddress> <endaddress>]`
///
/// The named context variable is set to the provided value.
/// If a start and end address is provided, the context variable is set over this range,
/// otherwise the value is set as a default.
void IfcSetcontextrange::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");

  string name;
  s >> name >> ws;

  if (name.size()==0)
    throw IfaceParseError("Missing context variable name");

  s.unsetf(ios::dec | ios::hex | ios::oct); // Let user specify base
  uintm value = 0xbadbeef;
  s >> value;
  if (value == 0xbadbeef)
    throw IfaceParseError("Missing context value");

  s >> ws;

  if (s.eof()) {		// No range indicates default value
    dcp->conf->context->setVariableDefault(name,value);
    return;
  }

  // Otherwise parse the range
  int4 size1,size2;
  Address addr1 = parse_machaddr(s,size1,*dcp->conf->types); // Read begin address
  Address addr2 = parse_machaddr(s,size2,*dcp->conf->types); // Read end address

  if (addr1.isInvalid() || addr2.isInvalid())
    throw IfaceParseError("Invalid address range");
  if (addr2 <= addr1)
    throw IfaceParseError("Bad address range");

  dcp->conf->context->setVariableRegion(name,addr1,addr2,value);
}

/// \class IfcSettrackedrange
/// \brief Set the value of a register: `set track <name> <value> [<startaddress> <endaddress>]`
///
/// The value for the register is picked up by the decompiler for functions in the tracked range.
/// The register is specified by name.  A specific range can be provided, otherwise the value is
/// treated as a default.
void IfcSettrackedrange::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");

  string name;
  s >> name >> ws;
  if (name.size() ==0)
    throw IfaceParseError("Missing tracked register name");

  s.unsetf(ios::dec | ios::hex | ios::oct); // Let user specify base
  uintb value = 0xbadbeef;
  s >> value;
  if (value == 0xbadbeef)
    throw IfaceParseError("Missing context value");

  s >> ws;
  if (s.eof()) {		// No range indicates default value
    TrackedSet &track(dcp->conf->context->getTrackedDefault());
    track.push_back( TrackedContext() );
    track.back().loc = dcp->conf->translate->getRegister(name);
    track.back().val = value;
    return;
  }

  int4 size1,size2;
  Address addr1 = parse_machaddr(s,size1,*dcp->conf->types);
  Address addr2 = parse_machaddr(s,size2,*dcp->conf->types);
  
  if (addr1.isInvalid() || addr2.isInvalid())
    throw IfaceParseError("Invalid address range");
  if (addr2 <= addr1)
    throw IfaceParseError("Bad address range");

  TrackedSet &track(dcp->conf->context->createSet(addr1,addr2));
  TrackedSet &def(dcp->conf->context->getTrackedDefault());
  track = def;			// Start with default as base
  track.push_back( TrackedContext() );
  track.back().loc = dcp->conf->translate->getRegister(name);
  track.back().val = value;
}

/// \class IfcBreakaction
/// \brief Set a breakpoint when a Rule or Action executes: `break action <actionname>`
///
/// The break point can be on either an Action or Rule.  The name can specify
/// partial path information to distinguish the Action/Rule.  The breakpoint causes
/// the decompilation process to stop and return control to the console immediately
/// \e after the Action or Rule has executed, but only if there was an active transformation
/// to the function.
void IfcBreakaction::execute(istream &s)

{
  bool res;
  string specify;

  s >> specify >> ws;		// Which action or rule to put breakpoint on

  if (specify.empty())
    throw IfaceExecutionError("No action/rule specified");

  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("Decompile action not loaded");

  res = dcp->conf->allacts.getCurrent()->setBreakPoint(Action::break_action, specify);
  if (!res)
    throw IfaceExecutionError("Bad action/rule specifier: "+specify);
}

/// \class IfcBreakstart
/// \brief Set a break point at the start of an Action: `break start <actionname>`
///
/// The break point can be on either an Action or a Rule.  The name can specify
/// partial path information to distinguish the Action/Rule.  The breakpoint causes
/// the decompilation process to stop and return control to the console just before
/// the Action/Rule would have executed.
void IfcBreakstart::execute(istream &s)

{
  bool res;
  string specify;

  s >> specify >> ws;		// Which action or rule to put breakpoint on

  if (specify.empty())
    throw IfaceExecutionError("No action/rule specified");

  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("Decompile action not loaded");

  res = dcp->conf->allacts.getCurrent()->setBreakPoint(Action::break_start, specify);
  if (!res)
    throw IfaceExecutionError("Bad action/rule specifier: "+specify);
}

/// \class IfcPrintTree
/// \brief Print all Varnodes in the \e current function: `print tree varnode`
///
/// Information about every Varnode in the data-flow graph for the function is displayed.
void IfcPrintTree::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  dcp->fd->printVarnodeTree(*status->fileoptr);
}

/// \class IfcPrintBlocktree
/// \brief Print a description of the \e current functions control-flow: `print tree block`
///
/// The recovered control-flow structure is displayed as a hierarchical list of blocks,
/// showing the nesting and code ranges covered by the blocks.
void IfcPrintBlocktree::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  dcp->fd->printBlockTree(*status->fileoptr);
}

/// \class IfcPrintSpaces
/// \brief Print all address spaces: `print spaces`
///
/// Information about every address space in the architecture/program is written
/// to the console.
void IfcPrintSpaces::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");

  const AddrSpaceManager *manage = dcp->conf;
  int4 num = manage->numSpaces();
  for(int4 i=0;i<num;++i) {
    AddrSpace *spc = manage->getSpace(i);
    if (spc == (AddrSpace *)0) continue;
    *status->fileoptr << dec << spc->getIndex() << " : '" << spc->getShortcut() << "' " << spc->getName();
    if (spc->getType() == IPTR_CONSTANT)
      *status->fileoptr << " constant ";
    else if (spc->getType() == IPTR_PROCESSOR)
      *status->fileoptr << " processor";
    else if (spc->getType() == IPTR_SPACEBASE)
      *status->fileoptr << " spacebase";
    else if (spc->getType() == IPTR_INTERNAL)
      *status->fileoptr << " internal ";
    else
      *status->fileoptr << " special  ";
    if (spc->isBigEndian())
      *status->fileoptr << " big  ";
    else
      *status->fileoptr << " small";
    *status->fileoptr << " addrsize=" << spc->getAddrSize() << " wordsize=" << spc->getWordSize();
    *status->fileoptr << " delay=" << spc->getDelay();
    *status->fileoptr << endl;
  }
}

/// \class IfcPrintHigh
/// \brief Display all Varnodes in a HighVariable: `print high <name>`
///
/// A HighVariable associated with the current function is specified by name.
/// Information about every Varnode merged into the variable is displayed.
void IfcPrintHigh::execute(istream &s)

{
  string varname;
  HighVariable *high;

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  s >> varname >> ws;

  high = dcp->fd->findHigh(varname);
  if (high == (HighVariable *)0)	// Didn't find this name
    throw IfaceExecutionError("Unknown variable name: "+varname);

  high->printInfo(*status->optr);
}

/// \class IfcPrintParamMeasures
/// \brief Perform parameter-id analysis on the \e current function: `print parammeasures`
void IfcPrintParamMeasures::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  ParamIDAnalysis pidanalysis( dcp->fd, false );
  pidanalysis.savePretty( *status->fileoptr, true );
  *status->fileoptr << "\n";
}

/// \class IfcRename
/// \brief Rename a variable: `rename <oldname> <newname>`
///
/// Change the name of a symbol.  The provided name is searched for starting
/// in the scope of the current function.
void IfcRename::execute(istream &s)

{
  string oldname,newname;
  
  s >> ws >> oldname >> ws >> newname >> ws;
  if (oldname.size()==0)
    throw IfaceParseError("Missing old symbol name");
  if (newname.size()==0)
    throw IfaceParseError("Missing new name");
    
  Symbol *sym;
  vector<Symbol *> symList;
  if (dcp->fd != (Funcdata *)0)
    dcp->fd->getScopeLocal()->queryByName(oldname,symList);
  else
    dcp->conf->symboltab->getGlobalScope()->queryByName(oldname,symList);
  
  if (symList.empty())
    throw IfaceExecutionError("No symbol named: "+oldname);
  if (symList.size() == 1)
    sym = symList[0];
  else
    throw IfaceExecutionError("More than one symbol named: "+oldname);

  if (sym->getCategory() == 0)
    dcp->fd->getFuncProto().setInputLock(true);
  sym->getScope()->renameSymbol(sym,newname);
  sym->getScope()->setAttribute(sym,Varnode::namelock|Varnode::typelock);
}

/// \class IfcRemove
/// \brief Remove a symbol by name: `remove <varname>`
///
/// The symbol is searched for starting in the current function's scope.
/// The resulting symbol is removed completely from the symbol table.
void IfcRemove::execute(istream &s)

{
  string name;
  
  s >> ws >> name;
  if (name.size()==0)
    throw IfaceParseError("Missing symbol name");

  vector<Symbol *> symList;
  if (dcp->fd != (Funcdata *)0)
    dcp->fd->getScopeLocal()->queryByName(name,symList);
  else
    dcp->conf->symboltab->getGlobalScope()->queryByName(name,symList);
  
  if (symList.empty())
    throw IfaceExecutionError("No symbol named: "+name);
  if (symList.size() > 1)
    throw IfaceExecutionError("More than one symbol named: "+name);
  symList[0]->getScope()->removeSymbol(symList[0]);
}

/// \class IfcRetype
/// \brief Change the data-type of a symbol: `retype <varname> <typedeclaration>`
///
/// The symbol is searched for by name starting in the current function's scope.
/// If the type declaration includes a new name for the variable, the
/// variable is renamed as well.
void IfcRetype::execute(istream &s)

{
  Datatype *ct;
  string name,newname;

  s >> ws >> name;
  if (name.size()==0)
    throw IfaceParseError("Must specify name of symbol");
  ct = parse_type(s,newname,dcp->conf);

  Symbol *sym;
  vector<Symbol *> symList;
  if (dcp->fd != (Funcdata *)0)
    dcp->fd->getScopeLocal()->queryByName(name,symList);
  else
    dcp->conf->symboltab->getGlobalScope()->queryByName(name,symList);
  
  if (symList.empty())
    throw IfaceExecutionError("No symbol named: "+name);
  if (symList.size() > 1)
    throw IfaceExecutionError("More than one symbol named : "+name);
  else
    sym = symList[0];

  if (sym->getCategory()==0)
    dcp->fd->getFuncProto().setInputLock(true);
  sym->getScope()->retypeSymbol(sym,ct);
  sym->getScope()->setAttribute(sym,Varnode::typelock);
  if ((newname.size()!=0)&&(newname != name)) {
    sym->getScope()->renameSymbol(sym,newname);
    sym->getScope()->setAttribute(sym,Varnode::namelock);
  }
}

/// The Varnode is selected from the \e current function.  It is specified as a
/// storage location with info about its defining p-code in parantheses.
///   - `%EAX(r0x10000:0x65)`
///   - `%ECX(i)`
///   - `r0x10001000:4(:0x96)`
///   - `u0x00001100:1(:0x102)`
///   - `#0x1(0x10205:0x27)`
///
/// The storage address space is given as the \e short-cut character followed by the
/// address offset.  For register spaces, the name of the register can be given instead of the
/// offset.  After the offset, a size can be specified with a ':' followed by the size in bytes.
/// If size is not provided and there is no register name, a default word size is assigned based
/// on the address space.
///
/// The defining p-code op is specified either as:
///   - An address and sequence number: `%EAX(r0x10000:0x65)`
///   - Just a sequence number: `%EAX(:0x65)`  or
///   - An "i" token for inputs: `%EAX(i)`
///
/// For a constant Varnode, the storage offset is the actual value of the constant, and
/// the p-code address and sequence number must both be present and specify the p-code op
/// that \e reads the constant.
/// \param s is the given input stream
/// \return the Varnode object
Varnode *IfaceDecompData::readVarnode(istream &s)

{
  uintm uq;
  int4 defsize;
  Varnode *vn = (Varnode *)0;

  if (fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  Address pc;
  Address loc(parse_varnode(s,defsize,pc,uq,*conf->types));
  if (loc.getSpace()->getType() == IPTR_CONSTANT) {
    if (pc.isInvalid() || (uq == ~((uintm)0)))
      throw IfaceParseError("Missing p-code sequence number");
    SeqNum seq(pc,uq);
    PcodeOp *op = fd->findOp(seq);
    if (op != (PcodeOp *)0) {
      for(int4 i=0;i<op->numInput();++i) {
	Varnode *tmpvn = op->getIn(i);
	if (tmpvn->getAddr() == loc) {
	  vn = tmpvn;
	  break;
	}
      }
    }
  }
  else if (pc.isInvalid()&&(uq==~((uintm)0)))
    vn = fd->findVarnodeInput(defsize,loc);
  else if ((!pc.isInvalid())&&(uq!=~((uintm)0)))
    vn = fd->findVarnodeWritten(defsize,loc,pc,uq);
  else {
    VarnodeLocSet::const_iterator iter,enditer;
    iter = fd->beginLoc(defsize,loc);
    enditer = fd->endLoc(defsize,loc);
    while(iter != enditer) {
      vn = *iter++;
      if (vn->isFree()) continue;
      if (vn->isWritten()) {
	if ((!pc.isInvalid()) && (vn->getDef()->getAddr()==pc)) break;
	if ((uq!=~((uintm)0))&&(vn->getDef()->getTime()==uq)) break;
      }
    }
  }

  if (vn == (Varnode *)0)
    throw IfaceExecutionError("Requested varnode does not exist");
  return vn;
}

/// \class IfcPrintVarnode
/// \brief Print information about a Varnode: `print varnode <varnode>`
///
/// Attributes of the indicated Varnode from the \e current function are printed
/// to the console.  If the Varnode belongs to a HighVariable, information about
/// it and all its Varnodes are printed as well.
void IfcPrintVarnode::execute(istream &s)

{
  Varnode *vn;

  vn = dcp->readVarnode(s);
  if (vn->isAnnotation()||(!dcp->fd->isHighOn()))
    vn->printInfo(*status->optr);
  else
    vn->getHigh()->printInfo(*status->optr);
}

/// \class IfcPrintCover
/// \brief Print cover info about a HighVariable: `print cover high <name>`
///
/// A HighVariable is specified by its symbol name in the current function's scope.
/// Information about the code ranges where the HighVariable is in scope is printed.
void IfcPrintCover::execute(istream &s)

{
  HighVariable *high;
  string name;

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  s >> ws >> name;
  if (name.size()==0)
    throw IfaceParseError("Missing variable name");
  high = dcp->fd->findHigh(name);
  if (high == (HighVariable *)0)
    throw IfaceExecutionError("Unable to find variable: "+name);
  
  high->printCover(*status->optr);
}

/// \class IfcVarnodehighCover
/// \brief Print cover info about a HighVariable: `print cover varnodehigh <varnode>`
///
/// The HighVariable is selected by specifying one of its Varnodes.
/// Information about the code ranges where the HighVariable is in scope is printed.
void IfcVarnodehighCover::execute(istream &s)

{
  Varnode *vn;

  vn = dcp->readVarnode(s);
  if (vn == (Varnode *)0)
    throw IfaceParseError("Unknown varnode");
  if (vn->getHigh() != (HighVariable *)0)
    vn->getHigh()->printCover(*status->optr);
  else
    *status->optr << "Unmerged" << endl;
}

/// \class IfcPrintExtrapop
/// \brief Print change to stack pointer for called function: `print extrapop [<functionname>]`
///
/// For the selected function, the extra amount each called function changes the stack pointer
/// (over popping the return value) is printed to console.  The function is selected by
/// name, or if no name is given, the \e current function is selected.
void IfcPrintExtrapop::execute(istream &s)

{
  string name;

  s >> ws >> name;
  if (name.size() == 0) {
    if (dcp->fd != (Funcdata *)0) {
      int4 num = dcp->fd->numCalls();
      for(int4 i=0;i<num;++i) {
	FuncCallSpecs *fc = dcp->fd->getCallSpecs(i);
	*status->optr << "ExtraPop for " << fc->getName() << '(';
	*status->optr << fc->getOp()->getAddr() << ')';
	int4 expop = fc->getEffectiveExtraPop();
	*status->optr << " ";
	if (expop == ProtoModel::extrapop_unknown)
	  *status->optr << "unknown";
	else
	  *status->optr << dec << expop;
	*status->optr << '(';
	expop = fc->getExtraPop();
	if (expop == ProtoModel::extrapop_unknown)
	  *status->optr << "unknown";
	else
	  *status->optr << dec << expop;
	*status->optr << ')' << endl;
      }
    }
    else {
      int4 expop = dcp->conf->defaultfp->getExtraPop();
      *status->optr << "Default extra pop = ";
      if (expop == ProtoModel::extrapop_unknown)
	*status->optr << "unknown" << endl;
      else
	*status->optr << dec << expop << endl;
    }
  }
  else {
    Funcdata *fd;
    fd = dcp->conf->symboltab->getGlobalScope()->queryFunction( name );
    if (fd == (Funcdata *)0)
      throw IfaceExecutionError("Unknown function: "+name);
    int4 expop = fd->getFuncProto().getExtraPop();
    *status->optr << "ExtraPop for function " << name << " is ";
    if (expop == ProtoModel::extrapop_unknown)
      *status->optr << "unknown" << endl;
    else
      *status->optr << dec << expop << endl;
    if (dcp->fd != (Funcdata *)0) {
      int4 num = dcp->fd->numCalls();
      for(int4 i=0;i<num;++i) {
	FuncCallSpecs *fc = dcp->fd->getCallSpecs(i);
	if (fc->getName() == fd->getName()) {
	  expop = fc->getEffectiveExtraPop();
	  *status->optr << "For this function, extrapop = ";
	  if (expop == ProtoModel::extrapop_unknown)
	    *status->optr << "unknown";
	  else
	    *status->optr << dec << expop;
	  *status->optr << '(';
	  expop = fc->getExtraPop();
	  if (expop == ProtoModel::extrapop_unknown)
	    *status->optr << "unknown";
	  else
	    *status->optr << dec << expop;
	  *status->optr << ')' << endl;
	}
      }
    }
  }
}

/// \class IfcVarnodeCover
/// \brief Print cover information about a Varnode: `print cover varnode <varnode>`
///
/// Information about code ranges where the single Varnode is in scope are printed.
void IfcVarnodeCover::execute(istream &s)

{
  Varnode *vn;

  vn = dcp->readVarnode(s);
  if (vn == (Varnode *)0)
    throw IfaceParseError("Unknown varnode");
  vn->printCover(*status->optr);
}

/// \class IfcNameVarnode
/// \brief Attach a named symbol to a specific Varnode: `name varnode <varnode> <name>`
///
/// A new local symbol is created for the \e current function, and
/// is attached to the specified Varnode. The \e current function must be decompiled
/// again to see the effects.  The new symbol is \e name-locked with the specified
/// name, but the data-type of the symbol is allowed to float.
void IfcNameVarnode::execute(istream &s)

{
  string token;
  int4 size;
  uintm uq;

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  Address pc;
  Address loc(parse_varnode(s,size,pc,uq,*dcp->conf->types)); // Get specified varnode

  s >> ws >> token;		// Get the new name of the varnode
  if (token.size()==0)
    throw IfaceParseError("Must specify name");

  Datatype *ct = dcp->conf->types->getBase(size,TYPE_UNKNOWN);

  dcp->conf->clearAnalysis(dcp->fd); // Make sure varnodes are cleared

  Scope *scope = dcp->fd->getScopeLocal()->discoverScope(loc,size,pc);
  if (scope == (Scope *)0)	// Variable does not have natural scope
    scope = dcp->fd->getScopeLocal();	// force it to be in function scope
  Symbol *sym = scope->addSymbol(token,ct,loc,pc)->getSymbol();
  scope->setAttribute(sym,Varnode::namelock);

  *status->fileoptr << "Successfully added " << token;
  *status->fileoptr << " to scope " << scope->getFullName() << endl;
}

/// \class IfcTypeVarnode
/// \brief Attach a typed symbol to a specific Varnode: `type varnode <varnode> <typedeclaration>`
///
/// A new local symbol is created for the \e current function, and
/// is attached to the specified Varnode. The \e current function must be decompiled
/// again to see the effects.  The new symbol is \e type-locked with the data-type specified
/// in the type declaration.  If a name is specified in the declaration, the symbol
/// is \e name-locked as well.
void IfcTypeVarnode::execute(istream &s)

{
  int4 size;
  uintm uq;
  Datatype *ct;
  string name;

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  Address pc;
  Address loc(parse_varnode(s,size,pc,uq,*dcp->conf->types)); // Get specified varnode
  ct = parse_type(s,name,dcp->conf);

  dcp->conf->clearAnalysis(dcp->fd); // Make sure varnodes are cleared
    
  Scope *scope = dcp->fd->getScopeLocal()->discoverScope(loc,size,pc);
  if (scope == (Scope *)0)	// Variable does not have natural scope
    scope = dcp->fd->getScopeLocal();	// force it to be in function scope
  Symbol *sym = scope->addSymbol(name,ct,loc,pc)->getSymbol();
  scope->setAttribute(sym,Varnode::typelock);
  sym->setIsolated(true);
  if (name.size() > 0)
    scope->setAttribute(sym,Varnode::namelock);
  
  *status->fileoptr << "Successfully added " << sym->getName();
  *status->fileoptr << " to scope " << scope->getFullName() << endl;
}

/// \class IfcForceHex
/// \brief Mark a constant to be printed in hex format: `force hex <varnode>`
///
/// A selected constant Varnode in the \e current function is marked so
/// that it will be printed in hexadecimal format in decompiler output.
void IfcForceHex::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  Varnode *vn = dcp->readVarnode(s);
  if (!vn->isConstant())
    throw IfaceExecutionError("Can only force hex on a constant");
  type_metatype mt = vn->getType()->getMetatype();
  if ((mt!=TYPE_INT)&&(mt!=TYPE_UINT)&&(mt!=TYPE_UNKNOWN))
    throw IfaceExecutionError("Can only force hex on integer type constant");
  dcp->fd->buildDynamicSymbol(vn);
  Symbol *sym = vn->getHigh()->getSymbol();
  if (sym == (Symbol *)0)
    throw IfaceExecutionError("Unable to create symbol");
  sym->getScope()->setDisplayFormat(sym,Symbol::force_hex);
  sym->getScope()->setAttribute(sym,Varnode::typelock);
  *status->optr << "Successfully forced hex display" << endl;
}

/// \class IfcForceDec
/// \brief Mark a constant to be printed in decimal format: `force dec <varnode>`
///
/// A selected constant Varnode in the \e current function is marked so
/// that it will be printed in decimal format in decompiler output.
void IfcForceDec::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  Varnode *vn = dcp->readVarnode(s);
  if (!vn->isConstant())
    throw IfaceExecutionError("Can only force hex on a constant");
  type_metatype mt = vn->getType()->getMetatype();
  if ((mt!=TYPE_INT)&&(mt!=TYPE_UINT)&&(mt!=TYPE_UNKNOWN))
    throw IfaceExecutionError("Can only force dec on integer type constant");
  dcp->fd->buildDynamicSymbol(vn);
  Symbol *sym = vn->getHigh()->getSymbol();
  if (sym == (Symbol *)0)
    throw IfaceExecutionError("Unable to create symbol");
  sym->getScope()->setDisplayFormat(sym,Symbol::force_dec);
  sym->getScope()->setAttribute(sym,Varnode::typelock);
  *status->optr << "Successfully forced dec display" << endl;
}

/// \class IfcForcegoto
/// \brief Force a branch to be an unstructured \b goto: `force goto <branchaddr> <targetaddr>`
///
/// Create an override that forces the decompiler to treat the specified branch
/// as unstructured. The branch will be modeled as a \b goto statement.
/// The branch is specified by first providing the address of the branching instruction,
/// then the destination address.
void IfcForcegoto::execute(istream &s)

{
  int4 discard;
  
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  s >> ws;
  Address target(parse_machaddr(s,discard,*dcp->conf->types));
  s >> ws;
  Address dest(parse_machaddr(s,discard,*dcp->conf->types));
  dcp->fd->getOverride().insertForceGoto(target,dest);
}

/// \class IfcProtooverride
/// \brief Override the prototype of a called function: `override prototype <address> <declaration>`
///
/// Force a specified prototype declaration on a called function when decompiling
/// the current function. The current function must be decompiled again to see the effect.
/// The called function is indicated by the address of its calling instruction.
/// The prototype only affects decompilation for the \e current function.
void IfcProtooverride::execute(istream &s)

{
  int4 discard;
  
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  s >> ws;
  Address callpoint(parse_machaddr(s,discard,*dcp->conf->types));
  int4 i;
  for(i=0;dcp->fd->numCalls();++i)
    if (dcp->fd->getCallSpecs(i)->getOp()->getAddr() == callpoint) break;
  if (i == dcp->fd->numCalls())
    throw IfaceExecutionError("No call is made at this address");

  PrototypePieces pieces;
  parse_protopieces(pieces,s,dcp->conf); // Parse the prototype from stream

  FuncProto *newproto = new FuncProto();

  // Make proto whose storage is internal, not backed by a real scope
  newproto->setInternal(pieces.model,dcp->conf->types->getTypeVoid());
  newproto->setPieces(pieces);
  dcp->fd->getOverride().insertProtoOverride(callpoint,newproto);
  dcp->fd->clear();		// Clear any analysis (this leaves overrides intact)
}

/// \class IfcJumpOverride
/// \brief Provide an overriding jump-table for an indirect branch: `override jumptable ...`
///
/// The command expects the address of an indirect branch in the \e current function,
/// followed by the keyword \b table then a list of possible target addresses of the branch.
/// \code
///    override jumptable r0x1000 table r0x1020 r0x1030 r0x1043 ...
/// \endcode
/// The command can optionally take the keyword \b startval followed by an
/// integer indicating the value taken by the \e normalized switch variable that
/// produces the first address in the table.
/// \code
///    override jumptable startval 10 table r0x1020 r0x1030 ...
/// \endcode
void IfcJumpOverride::execute(istream &s)

{
  int4 discard;

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  s >> ws;
  Address jmpaddr( parse_machaddr(s,discard,*dcp->conf->types));
  JumpTable *jt = dcp->fd->installJumpTable(jmpaddr);
  vector<Address> adtable;
  Address naddr;
  uintb h=0;
  uintb sv = 0;
  string token;
  s >> token;
//   if (token == "norm") {
//     naddr = parse_machaddr(s,discard,*dcp->conf->types);
//     s >> ws;
//     s >> h;
//     s >> token;
//   }
  if (token == "startval") {
    s.unsetf(ios::dec | ios::hex | ios::oct); // Let user specify base
    s >> sv;
    s >> token;
  }
  if (token == "table") {
    s >> ws;
    while(!s.eof()) {
      Address addr( parse_machaddr(s,discard,*dcp->conf->types));
      adtable.push_back(addr);
    }
  }
  if (adtable.empty())
    throw IfaceExecutionError("Missing jumptable address entries");
  jt->setOverride(adtable,naddr,h,sv);
  *status->optr << "Successfully installed jumptable override" << endl;
}

/// \class IfcFlowOverride
/// \brief Create a control-flow override: `override flow <address> branch|call|callreturn|return`
///
/// Change the nature of the control-flow at the specified address, as indicated by the
/// final token on the command-line:
///   - branch     -  Change the CALL or RETURN to a BRANCH
///   - call       -  Change a BRANCH or RETURN to a CALL
///   - callreturn -  Change a BRANCH or RETURN to a CALL followed by a RETURN
///   - return     -  Change a CALLIND or BRANCHIND to a RETURN
void IfcFlowOverride::execute(istream &s)

{
  int4 discard;
  uint4 type;
  string token;

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  s >> ws;
  Address addr( parse_machaddr(s,discard,*dcp->conf->types));
  s >> token;
  if (token.size() == 0)
    throw IfaceParseError("Missing override type");
  type = Override::stringToType(token);
  if (type == Override::NONE)
    throw IfaceParseError("Bad override type");

  dcp->fd->getOverride().insertFlowOverride(addr,type);
  *status->optr << "Successfully added override" << endl;
}

/// \class IfcDeadcodedelay
/// \brief Change when dead code elimination starts: `deadcode delay <name> <delay>`
///
/// An address space is selected by name, along with a pass number.
/// Dead code elimination for Varnodes in that address space is changed to start
/// during that pass.  If there is a \e current function, the delay is altered only for
/// that function, otherwise the delay is set globally for all functions.
void IfcDeadcodedelay::execute(istream &s)

{
  string name;
  int4 delay = -1;
  AddrSpace *spc;
  
  s >> name;
  s >> ws;
  s >> delay;

  spc = dcp->conf->getSpaceByName(name);
  if (spc == (AddrSpace *)0)
    throw IfaceParseError("Bad space: "+name);
  if (delay == -1)
    throw IfaceParseError("Need delay integer");
  if (dcp->fd != (Funcdata *)0) {
    dcp->fd->getOverride().insertDeadcodeDelay(spc,delay);
    *status->optr << "Successfully overrided deadcode delay for single function" << endl;
  }
  else {
    dcp->conf->setDeadcodeDelay(spc,delay);
    *status->optr << "Successfully overrided deadcode delay for all functions" << endl;
  }
}

/// \class IfcGlobalAdd
/// \brief Add a memory range as discoverable global variables: `global add <address+size>`
///
/// The decompiler will treat Varnodes stored in the new memory range as persistent
/// global variables.
void IfcGlobalAdd::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No image loaded");
  
  int4 size;
  Address addr = parse_machaddr(s,size,*dcp->conf->types);
  uintb first = addr.getOffset();
  uintb last = first + (size-1);

  Scope *scope = dcp->conf->symboltab->getGlobalScope();
  dcp->conf->symboltab->addRange(scope,addr.getSpace(),first,last);
}

/// \class IfcGlobalRemove
/// \brief Remove a memory range from discoverable global variables: `global remove <address+size>`
///
/// The will no longer treat Varnodes stored in the memory range as persistent global
/// variables.  The will be treated as local or temporary storage.
void IfcGlobalRemove::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No image loaded");
  
  int4 size;
  Address addr = parse_machaddr(s,size,*dcp->conf->types);
  uintb first = addr.getOffset();
  uintb last = first + (size-1);

  Scope *scope = dcp->conf->symboltab->getGlobalScope();
  dcp->conf->symboltab->removeRange(scope,addr.getSpace(),first,last);
}

/// \class IfcGlobalify
/// \brief Treat all normal memory as discoverable global variables: `global spaces`
///
/// This has the drastic effect that the decompiler will treat all registers and stack
/// locations as global variables.
void IfcGlobalify::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");
  dcp->conf->globalify();
  *status->optr << "Successfully made all registers/memory locations global" << endl;
}

/// \class IfcGlobalRegisters
/// \brief Name global registers: `global registers`
///
/// Name any global symbol stored in a register with the name of the register.
void IfcGlobalRegisters::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");
  map<VarnodeData,string> reglist;
  dcp->conf->translate->getAllRegisters(reglist);
  map<VarnodeData,string>::const_iterator iter;
  AddrSpace *spc = (AddrSpace *)0;
  uintb lastoff=0;
  Scope *globalscope = dcp->conf->symboltab->getGlobalScope();
  int4 count = 0;
  for(iter=reglist.begin();iter!=reglist.end();++iter) {
    const VarnodeData &dat( (*iter).first );
    if (dat.space == spc) {
      if (dat.offset<=lastoff) continue; // Nested register def
    }
    spc = dat.space;
    lastoff = dat.offset+dat.size-1;
    Address addr(spc,dat.offset);
    uint4 flags=0;
    // Check if the register location is global
    globalscope->queryProperties(addr,dat.size,Address(),flags);
    if ((flags & Varnode::persist)!=0) {
      Datatype *ct = dcp->conf->types->getBase(dat.size,TYPE_UINT);
      globalscope->addSymbol((*iter).second,ct,addr,Address());
      count += 1;
    }
  }
  if (count == 0)
    *status->optr << "No global registers" << endl;
  else
    *status->optr << "Successfully made a global symbol for " << count << " registers" << endl;
}

/// The use is non-trivial if it can be traced to any p-code operation except
/// a COPY, CAST, INDIRECT, or MULTIEQUAL.
/// \param vn is the given Varnode
/// \return \b true if there is a non-trivial use
bool IfcPrintInputs::nonTrivialUse(Varnode *vn)

{
  vector<Varnode *> vnlist;
  bool res = false;
  vnlist.push_back(vn);
  uint4 proc = 0;
  while(proc < vnlist.size()) {
    Varnode *tmpvn = vnlist[proc];
    proc += 1;
    list<PcodeOp *>::const_iterator iter;
    for(iter=tmpvn->beginDescend();iter!=tmpvn->endDescend();++iter) {
      PcodeOp *op = *iter;
      if ((op->code() == CPUI_COPY)||
	  (op->code() == CPUI_CAST)||
	  (op->code() == CPUI_INDIRECT) ||
	  (op->code() == CPUI_MULTIEQUAL)) {
	Varnode *outvn = op->getOut();
	if (!outvn->isMark()) {
	  outvn->setMark();
	  vnlist.push_back(outvn);
	}
      }
      else {
	res = true;
	break;
      }
    }
  }
  for(int4 i=0;i<vnlist.size();++i)
    vnlist[i]->clearMark();
  return res;
}

/// Look for any value flowing into the Varnode coming from anything
/// other than an input Varnode with the same storage.  The value can flow through
/// a COPY, CAST, INDIRECT, or MULTIEQUAL
/// \param vn is the given Varnode
/// \return 0 if Varnode is restored, 1 otherwise
int4 IfcPrintInputs::checkRestore(Varnode *vn)

{
  vector<Varnode *> vnlist;
  int4 res = 0;
  vnlist.push_back(vn);
  uint4 proc = 0;
  while(proc < vnlist.size()) {
    Varnode *tmpvn = vnlist[proc];
    proc += 1;
    if (tmpvn->isInput()) {
      if ((tmpvn->getSize() != vn->getSize()) ||
	  (tmpvn->getAddr() != vn->getAddr())) {
	res = 1;
	break;
      }
    }
    else if (!tmpvn->isWritten()) {
      res = 1;
      break;
    }
    else {
      PcodeOp *op = tmpvn->getDef();
      if ((op->code() == CPUI_COPY)||(op->code()==CPUI_CAST)) {
	tmpvn = op->getIn(0);
	if (!tmpvn->isMark()) {
	  tmpvn->setMark();
	  vnlist.push_back(tmpvn);
	}
      }
      else if (op->code() == CPUI_INDIRECT) {
	tmpvn = op->getIn(0);
	if (!tmpvn->isMark()) {
	  tmpvn->setMark();
	  vnlist.push_back(tmpvn);
	}
      }
      else if (op->code() == CPUI_MULTIEQUAL) {
	for(int4 i=0;i<op->numInput();++i) {
	  tmpvn = op->getIn(i);
	  if (!tmpvn->isMark()) {
	    tmpvn->setMark();
	    vnlist.push_back(tmpvn);
	  }
	}
      }
      else {
	res = 1;
	break;
      }
    }
  }
  for(int4 i=0;i<vnlist.size();++i)
    vnlist[i]->clearMark();
  return res;
}

/// For the given storage location, check that it is \e restored
/// from its original input value.
/// \param vn is the given storage location
/// \param fd is the function being analyzed
bool IfcPrintInputs::findRestore(Varnode *vn,Funcdata *fd)

{
  VarnodeLocSet::const_iterator iter,enditer;

  iter = fd->beginLoc(vn->getAddr());
  enditer = fd->endLoc(vn->getAddr());
  int4 count = 0;
  while(iter != enditer) {
    Varnode *vn = *iter;
    ++iter;
    if (!vn->hasNoDescend()) continue;
    if (!vn->isWritten()) continue;
    PcodeOp *op = vn->getDef();
    if (op->code() == CPUI_INDIRECT) continue; // Not a global return address force
    int4 res = checkRestore(vn);
    if (res != 0) return false;
    count += 1;
  }
  return (count>0);
}

/// For each input Varnode, print information about the Varnode,
/// any explicit symbol it represents, and info about how the value is used.
/// \param fd is the function
/// \param s is the output stream to write to
void IfcPrintInputs::print(Funcdata *fd,ostream &s)

{
  VarnodeDefSet::const_iterator iter,enditer;

  s << "Function: " << fd->getName() << endl;
  iter = fd->beginDef(Varnode::input);
  enditer = fd->endDef(Varnode::input);
  while(iter != enditer) {
    Varnode *vn = *iter;
    ++iter;
    vn->printRaw(s);
    if (fd->isHighOn()) {
      Symbol *sym = vn->getHigh()->getSymbol();
      if (sym != (Symbol *)0)
	s << "    " << sym->getName();
    }
    bool findres = findRestore(vn,fd);
    bool nontriv = nonTrivialUse(vn);
    if (findres && !nontriv)
      s << "     restored";
    else if (nontriv)
      s << "     nontriv";
    s << endl;
  }
}

/// \class IfcPrintInputs
/// \brief Print info about the current function's input Varnodes: `print inputs`
void IfcPrintInputs::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  print(dcp->fd,*status->fileoptr);
}

/// \class IfcPrintInputsAll
/// \brief Print info about input Varnodes for all functions: `print inputs all`
///
/// Each function is decompiled, and info about its input Varnodes are printed.
void IfcPrintInputsAll::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");

  iterateFunctionsAddrOrder();
}

void IfcPrintInputsAll::iterationCallback(Funcdata *fd)

{
  if (fd->hasNoCode()) {
    *status->optr << "No code for " << fd->getName() << endl;
    return;
  }
  try {
    dcp->conf->clearAnalysis(fd); // Clear any old analysis
    dcp->conf->allacts.getCurrent()->reset(*fd);
    dcp->conf->allacts.getCurrent()->perform( *fd );
    IfcPrintInputs::print(fd,*status->fileoptr);
  }
  catch(LowlevelError &err) {
    *status->optr << "Skipping " << fd->getName() << ": " << err.explain << endl;
  }
  dcp->conf->clearAnalysis(fd);
}

/// \class IfcLockPrototype
/// \brief Lock in the \e current function's prototype: `prototype lock`
///
/// Lock in the existing formal parameter names and data-types for any future
/// decompilation.  Both input parameters and the return value are locked.
void IfcLockPrototype::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  dcp->fd->getFuncProto().setInputLock(true);
  dcp->fd->getFuncProto().setOutputLock(true);
}

/// \class IfcUnlockPrototype
/// \brief Unlock the \e current function's prototype: `prototype unlock`
///
/// Unlock all input parameters and the return value, so future decompilation
/// is not constrained with their data-type or name.
void IfcUnlockPrototype::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  dcp->fd->getFuncProto().setInputLock(false);
  dcp->fd->getFuncProto().setOutputLock(false);
}

/// \class IfcPrintLocalrange
/// \brief Print range of locals on the stack: `print localrange`
///
/// Print the memory range(s) on the stack is or could be used for
///
void IfcPrintLocalrange::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  dcp->fd->printLocalRange( *status->optr );
}

/// \class IfcPrintMap
/// \brief Print info about a scope/namespace: `print map <name>`
///
/// Prints information about the discoverable memory ranges for the scope,
/// and prints a description of every symbol in the scope.
void IfcPrintMap::execute(istream &s)

{
  string name;
  Scope *scope;

  s >> name;
  
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image");
  if (name.size() != 0 || dcp->fd==(Funcdata *)0) {
    string fullname = name + "::a";		// Add fake variable name
    scope = dcp->conf->symboltab->resolveScopeFromSymbolName(fullname, "::", fullname, (Scope *)0);
  }
  else
    scope = dcp->fd->getScopeLocal();
    
  if (scope == (Scope *)0)
    throw IfaceExecutionError("No map named: "+name);

  *status->fileoptr << scope->getFullName() << endl;
  scope->printBounds(*status->fileoptr);
  scope->printEntries(*status->fileoptr);
}

/// \class IfcProduceC
/// \brief Write decompilation for all functions to a file: `produce C <filename>`
///
/// Iterate over all functions in the program.  For each function, decompilation is
/// performed and output is appended to the file.
void IfcProduceC::execute(istream &s)

{
  string name;
  
  s >> ws >> name;
  if (name.size()==0)
    throw IfaceParseError("Need file name to write to");
  
  ofstream os;
  os.open(name.c_str());
  dcp->conf->print->setOutputStream(&os);

  iterateFunctionsAddrOrder();

  os.close();
}

void IfcProduceC::iterationCallback(Funcdata *fd)

{
  clock_t start_time,end_time;
  float duration;

  if (fd->hasNoCode()) {
    *status->optr << "No code for " << fd->getName() << endl;
    return;
  }
  try {
    dcp->conf->clearAnalysis(fd); // Clear any old analysis
    dcp->conf->allacts.getCurrent()->reset(*fd);
    start_time = clock();
    dcp->conf->allacts.getCurrent()->perform( *fd );
    end_time = clock();
    *status->optr << "Decompiled " << fd->getName();
    //	  *status->optr << ": " << hex << fd->getAddress().getOffset();
    *status->optr << '(' << dec << fd->getSize() << ')';
    duration = ((float)(end_time-start_time))/CLOCKS_PER_SEC;
    duration *= 1000.0;
    *status->optr << " time=" << fixed << setprecision(0) << duration << " ms" << endl;
    dcp->conf->print->docFunction(fd);
  }
  catch(LowlevelError &err) {
    *status->optr << "Skipping " << fd->getName() << ": " << err.explain << endl;
  }
  dcp->conf->clearAnalysis(fd);
}

/// \class IfcProducePrototypes
/// \brief Determine the prototype model for all functions: `produce prototypes`
///
/// Functions are walked in leaf order.
void IfcProducePrototypes::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image");
  if (dcp->cgraph == (CallGraph *)0)
    throw IfaceExecutionError("Callgraph has not been built");
  if (dcp->conf->evalfp_current == (ProtoModel *)0) {
    *status->optr << "Always using default prototype" << endl;
    return;
  }

  if (!dcp->conf->evalfp_current->isMerged()) {
    *status->optr << "Always using prototype " << dcp->conf->evalfp_current->getName() << endl;
    return;
  }
  ProtoModelMerged *model = (ProtoModelMerged *)dcp->conf->evalfp_current;
  *status->optr << "Trying to distinguish between prototypes:" << endl;
  for(int4 i=0;i<model->numModels();++i)
    *status->optr << "  " << model->getModel(i)->getName() << endl;

  iterateFunctionsLeafOrder();
}

void IfcProducePrototypes::iterationCallback(Funcdata *fd)

{
  clock_t start_time,end_time;
  float duration;

  *status->optr << fd->getName() << ' ';
  if (fd->hasNoCode()) {
    *status->optr << "has no code" << endl;
    return;
  }
  if (fd->getFuncProto().isInputLocked()) {
    *status->optr << "has locked prototype" << endl;
    return;
  }
  try {
    dcp->conf->clearAnalysis(fd); // Clear any old analysis
    dcp->conf->allacts.getCurrent()->reset(*fd);
    start_time = clock();
    dcp->conf->allacts.getCurrent()->perform( *fd );
    end_time = clock();
    //    *status->optr << "Decompiled " << fd->getName();
    //    *status->optr << '(' << dec << fd->getSize() << ')';
    *status->optr << "proto=" << fd->getFuncProto().getModelName();
    fd->getFuncProto().setModelLock(true);
    duration = ((float)(end_time-start_time))/CLOCKS_PER_SEC;
    duration *= 1000.0;
    *status->optr << " time=" << fixed << setprecision(0) << duration << " ms" << endl;
  }
  catch(LowlevelError &err) {
    *status->optr << "Skipping " << fd->getName() << ": " << err.explain << endl;
  }
  dcp->conf->clearAnalysis(fd);
}

/// \class IfcContinue
/// \brief Continue decompilation after a break point: `continue`
///
/// This command assumes decompilation has been started and has hit a break point.
void IfcContinue::execute(istream &s)

{
  int4 res;

  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("Decompile action not loaded");

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  if (dcp->conf->allacts.getCurrent()->getStatus() == Action::status_start)
    throw IfaceExecutionError("Decompilation has not been started");
  if (dcp->conf->allacts.getCurrent()->getStatus() == Action::status_end)
    throw IfaceExecutionError("Decompilation is already complete");

  res = dcp->conf->allacts.getCurrent()->perform( *dcp->fd ); // Try to continue decompilation
  if (res<0) {
    *status->optr << "Break at ";
    dcp->conf->allacts.getCurrent()->printState(*status->optr);
  }
  else {
    *status->optr << "Decompilation complete";
    if (res==0)
      *status->optr << " (no change)";
  }
  *status->optr << endl;
}

/// \class IfcGraphDataflow
/// \brief Write a graph representation of data-flow to a file: `graph dataflow <filename>`
///
/// The data-flow graph for the \e current function, in its current state of transform,
/// is written to the indicated file.
void IfcGraphDataflow::execute(istream &s)

{
  string filename;

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  s >> filename;
  if (filename.size()==0)
    throw IfaceParseError("Missing output file");
  if (!dcp->fd->isProcStarted())
    throw IfaceExecutionError("Syntax tree not calculated");
  ofstream thefile( filename.c_str());
  if (!thefile)
    throw IfaceExecutionError("Unable to open output file: "+filename);

  dump_dataflow_graph(*dcp->fd,thefile);
  thefile.close();
}

/// \class IfcGraphControlflow
/// \brief Write a graph representation of control-flow to a file: `graph controlflow <filename>`
///
/// The control-flow graph for the \e current function, in its current state of transform,
/// is written to the indicated file.
void IfcGraphControlflow::execute(istream &s)

{
  string filename;

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  s >> filename;
  if (filename.size()==0)
    throw IfaceParseError("Missing output file");
  if (dcp->fd->getBasicBlocks().getSize()==0)
    throw IfaceExecutionError("Basic block structure not calculated");
  ofstream thefile( filename.c_str());
  if (!thefile)
    throw IfaceExecutionError("Unable to open output file: "+filename);

  dump_controlflow_graph(dcp->fd->getName(),dcp->fd->getBasicBlocks(),thefile);
  thefile.close();
}

/// \class IfcGraphDom
/// \brief Write the forward dominance graph to a file: `graph dom <filename>`
///
/// The dominance tree, associated with the control-flow graph of the \e current function
/// in its current state of transform, is written to the indicated file.
void IfcGraphDom::execute(istream &s)

{
  string filename;

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  s >> filename;
  if (filename.size()==0)
    throw IfaceParseError("Missing output file");
  if (!dcp->fd->isProcStarted())
    throw IfaceExecutionError("Basic block structure not calculated");
  ofstream thefile( filename.c_str());
  if (!thefile)
    throw IfaceExecutionError("Unable to open output file: "+filename);

  dump_dom_graph(dcp->fd->getName(),dcp->fd->getBasicBlocks(),thefile);
  thefile.close();
}

/// \class IfcCommentInstr
/// \brief Attach a comment to an address: `comment <address> comment text...`
///
/// Add a comment to the database, suitable for integration into decompiler output
/// for the \e current function.  The command-line takes the address of the
/// machine instruction which the comment will be attached to and is followed by
/// the text of the comment.
void IfcCommentInstr::execute(istream &s)

{ // Comment on a particular address within current function
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("Decompile action not loaded");

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  int4 size;
  Address addr = parse_machaddr(s,size,*dcp->conf->types);
  s >> ws;
  string comment;
  char tok;
  s.get(tok);
  while(!s.eof()) {
    comment += tok;
    s.get(tok);
  }
  uint4 type = dcp->conf->print->getInstructionComment();
  dcp->conf->commentdb->addComment(type,
				  dcp->fd->getAddress(),addr,comment);
}

/// For each duplicate discovered, a message is written to the provided stream.
/// \param fd is the given function to search
/// \param s is the stream to write messages to
void IfcDuplicateHash::check(Funcdata *fd,ostream &s)

{
  DynamicHash dhash;

  VarnodeLocSet::const_iterator iter,enditer;
  pair<set<uint8>::iterator,bool> res;
  iter = fd->beginLoc();
  enditer = fd->endLoc();
  while(iter != enditer) {
    Varnode *vn = *iter;
    ++iter;
    if (vn->isAnnotation()) continue;
    if (vn->isConstant()) {
      PcodeOp *op = vn->loneDescend();
      int4 slot = op->getSlot(vn);
      if (slot == 0) {
	if (op->code() == CPUI_LOAD) continue;
	if (op->code() == CPUI_STORE) continue;
	if (op->code() == CPUI_RETURN) continue;
      }
    }
    else if (vn->getSpace()->getType() != IPTR_INTERNAL)
      continue;
    else if (vn->isImplied())
      continue;
    dhash.uniqueHash(vn,fd);
    if (dhash.getHash() == 0) {
      // We have a duplicate
      const PcodeOp *op;
      if (vn->beginDescend() != vn->endDescend())
	op = *vn->beginDescend();
      else
	op = vn->getDef();
      s << "Could not get unique hash for : ";
      vn->printRaw(s);
      s << " : ";
      op->printRaw(s);
      s << endl;
      return;
    }
    uint4 total = DynamicHash::getTotalFromHash(dhash.getHash());
    if (total != 1) {
      const PcodeOp *op;
      if (vn->beginDescend() != vn->endDescend())
	op = *vn->beginDescend();
      else
	op = vn->getDef();
      s << "Duplicate : ";
      s << dec << DynamicHash::getPositionFromHash(dhash.getHash()) << " out of " << total << " : ";
      vn->printRaw(s);
      s << " : ";
      op->printRaw(s);
      s << endl;
    }
  }
}

/// \class IfcDuplicateHash
/// \brief Check for duplicate hashes in functions: `duplicate hash`
///
/// All functions in the architecture/program are decompiled, and for each
/// a check is made for Varnode pairs with identical hash values.
void IfcDuplicateHash::execute(istream &s)

{
  iterateFunctionsAddrOrder();
}

void IfcDuplicateHash::iterationCallback(Funcdata *fd)

{
  clock_t start_time,end_time;
  float duration;

  if (fd->hasNoCode()) {
    *status->optr << "No code for " << fd->getName() << endl;
    return;
  }
  try {
    dcp->conf->clearAnalysis(fd); // Clear any old analysis
    dcp->conf->allacts.getCurrent()->reset(*fd);
    start_time = clock();
    dcp->conf->allacts.getCurrent()->perform( *fd );
    end_time = clock();
    *status->optr << "Decompiled " << fd->getName();
    //	  *status->optr << ": " << hex << fd->getAddress().getOffset();
    *status->optr << '(' << dec << fd->getSize() << ')';
    duration = ((float)(end_time-start_time))/CLOCKS_PER_SEC;
    duration *= 1000.0;
    *status->optr << " time=" << fixed << setprecision(0) << duration << " ms" << endl;
    check(fd,*status->optr);
  }
  catch(LowlevelError &err) {
    *status->optr << "Skipping " << fd->getName() << ": " << err.explain << endl;
  }
  dcp->conf->clearAnalysis(fd);
}

/// \class IfcCallGraphBuild
/// \brief Build the call-graph for the architecture/program: `callgraph build`
///
/// Build, or rebuild, the call-graph with nodes for all existing functions.
/// Functions are to decompiled to recover destinations of indirect calls.
/// Going forward, the graph is held in memory and is accessible by other commands.
void IfcCallGraphBuild::execute(istream &s)

{
  dcp->allocateCallGraph();

  dcp->cgraph->buildAllNodes();		// Build a node in the graph for existing symbols
  quick = false;
  iterateFunctionsAddrOrder();
  *status->optr << "Successfully built callgraph" << endl;
}

void IfcCallGraphBuild::iterationCallback(Funcdata *fd)

{
  clock_t start_time,end_time;
  float duration;

  if (fd->hasNoCode()) {
    *status->optr << "No code for " << fd->getName() << endl;
    return;
  }
  if (quick) {
    dcp->fd = fd;
    dcp->followFlow(*status->optr,0);
  }
  else {
    try {
      dcp->conf->clearAnalysis(fd); // Clear any old analysis
      dcp->conf->allacts.getCurrent()->reset(*fd);
      start_time = clock();
      dcp->conf->allacts.getCurrent()->perform( *fd );
      end_time = clock();
      *status->optr << "Decompiled " << fd->getName();
      //	  *status->optr << ": " << hex << fd->getAddress().getOffset();
      *status->optr << '(' << dec << fd->getSize() << ')';
      duration = ((float)(end_time-start_time))/CLOCKS_PER_SEC;
      duration *= 1000.0;
      *status->optr << " time=" << fixed << setprecision(0) << duration << " ms" << endl;
    }
    catch(LowlevelError &err) {
      *status->optr << "Skipping " << fd->getName() << ": " << err.explain << endl;
    }
  }
  dcp->cgraph->buildEdges(fd);
  dcp->conf->clearAnalysis(fd);
}

/// \class IfcCallGraphBuildQuick
/// \brief Build the call-graph using quick analysis: `callgraph build quick`
///
/// Build the call-graph for the architecture/program.  For each function, disassembly
/// is performed to discover call edges, rather then full decompilation.  Some forms
/// of direct call may not be discovered.
void IfcCallGraphBuildQuick::execute(istream &s)

{
  dcp->allocateCallGraph();
  dcp->cgraph->buildAllNodes();	// Build a node in the graph for existing symbols
  quick = true;
  iterateFunctionsAddrOrder();
  *status->optr << "Successfully built callgraph" << endl;
}

/// \class IfcCallGraphDump
/// \brief Write the current call-graph to a file: `callgraph dump <filename>`
///
/// The existing call-graph object is written to the provided file as an
/// XML document.
void IfcCallGraphDump::execute(istream &s)

{
  if (dcp->cgraph == (CallGraph *)0)
    throw IfaceExecutionError("No callgraph has been built");

  string name;
  s >> ws >> name;
  if (name.size() == 0)
    throw IfaceParseError("Need file name to write callgraph to");

  ofstream os;
  os.open(name.c_str());
  if (!os)
    throw IfaceExecutionError("Unable to open file "+name);

  dcp->cgraph->saveXml(os);
  os.close();
  *status->optr << "Successfully saved callgraph to " << name << endl;
}

/// \class IfcCallGraphLoad
/// \brief Load the call-graph from a file: `callgraph load <filename>`
///
/// A call-graph is loaded from the provided XML document.  Nodes in the
/// call-graph are linked to existing functions by symbol name.  This command
/// reports call-graph nodes that could not be linked.
void IfcCallGraphLoad::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("Decompile action not loaded");
  if (dcp->cgraph != (CallGraph *)0)
    throw IfaceExecutionError("Callgraph already loaded");

  string name;

  s >> ws >> name;
  if (name.size() == 0)
    throw IfaceExecutionError("Need name of file to read callgraph from");

  ifstream is(name.c_str());
  if (!is)
    throw IfaceExecutionError("Unable to open callgraph file "+name);

  DocumentStorage store;
  Document *doc = store.parseDocument(is);

  dcp->allocateCallGraph();
  dcp->cgraph->restoreXml(doc->getRoot());
  *status->optr << "Successfully read in callgraph" << endl;

  Scope *gscope = dcp->conf->symboltab->getGlobalScope();
  map<Address,CallGraphNode>::iterator iter,enditer;
  iter = dcp->cgraph->begin();
  enditer = dcp->cgraph->end();

  for(;iter!=enditer;++iter) {
    CallGraphNode *node = &(*iter).second;
    Funcdata *fd;
    fd = gscope->queryFunction(node->getName());
    if (fd == (Funcdata *)0)
      throw IfaceExecutionError("Function:" + node->getName() +" in callgraph has not been loaded");
    node->setFuncdata(fd);
  }

  *status->optr << "Successfully associated functions with callgraph nodes" << endl;
}

/// \class IfcCallGraphList
/// \brief List all functions in \e leaf order: `callgraph list`
///
/// The existing call-graph is walked, displaying function names to the console.
/// Child functions are displayed before their parents.
void IfcCallGraphList::execute(istream &s)

{
  if (dcp->cgraph == (CallGraph *)0)
    throw IfaceExecutionError("Callgraph not generated");

  iterateFunctionsLeafOrder();
}

void IfcCallGraphList::iterationCallback(Funcdata *fd)

{
  *status->optr << fd->getName() << endl;
}

/// \brief Scan a single-line p-code snippet declaration from the given stream
///
/// A declarator is scanned first, providing a name to associate with the snippet, as well
/// as potential names of the formal \e output Varnode and \e input Varnodes.
/// The body of the snippet is then surrounded by '{' and '}'  The snippet name,
/// input/output names, and the body are passed back to the caller.
/// \param s is the given stream to scan
/// \param name passes back the name of the snippet
/// \param outname passes back the formal output parameter name, or is empty
/// \param inname passes back an array of the formal input parameter names
/// \param pcodestring passes back the snippet body
void IfcCallFixup::readPcodeSnippet(istream &s,string &name,string &outname,vector<string> &inname,
				    string &pcodestring)
{
  char bracket;
  s >> outname;
  parse_toseparator(s,name);
  s >> bracket;
  if (outname == "void")
    outname = "";
  if (bracket != '(')
    throw IfaceParseError("Missing '('");
  while(bracket != ')') {
    string param;
    parse_toseparator(s,param);
    s >> bracket;
    if (param.size() != 0)
      inname.push_back(param);
  }
  s >> ws >> bracket;
  if (bracket != '{')
    throw IfaceParseError("Missing '{'");
  getline(s,pcodestring,'}');
}

/// \class IfcCallFixup
/// \brief Add a new call fix-up to the program: `fixup call ...`
///
/// Create a new call fixup-up for the architecture/program, suitable for
/// replacing called functions.  The fix-up is specified as a function-style declarator,
/// which also provides the formal name of the fix-up.
/// A "void" return-type and empty parameter list must be given.
/// \code
///   fixup call void myfixup1() { EAX = 0; RBX = RCX + RDX + 1; }
/// \endcode
void IfcCallFixup::execute(istream &s)

{
  string name,outname,pcodestring;
  vector<string> inname;

  readPcodeSnippet(s,name,outname,inname,pcodestring);
  int4 id = -1;
  try {
    id = dcp->conf->pcodeinjectlib->manualCallFixup(name,pcodestring);
  } catch(LowlevelError &err) {
    *status->optr << "Error compiling pcode: " << err.explain << endl;
    return;
  }
  InjectPayload *payload = dcp->conf->pcodeinjectlib->getPayload(id);
  payload->printTemplate(*status->optr);
}

/// \class IfcCallOtherFixup
/// \brief Add a new callother fix-up to the program: `fixup callother ...`
///
/// The new fix-up is suitable for replacing specific user-defined (CALLOTHER)
/// p-code operations. The declarator provides the name of the fix-up and can also
/// provide formal input and output parameters.
/// \code
///   fixup callother outvar myfixup2(invar1,invar2) { outvar = invar1 + invar2; }
/// \endcode
void IfcCallOtherFixup::execute(istream &s)

{
  string useropname,outname,pcodestring;
  vector<string> inname;

  IfcCallFixup::readPcodeSnippet(s,useropname,outname,inname,pcodestring);
  dcp->conf->userops.manualCallOtherFixup(useropname,outname,inname,pcodestring,dcp->conf);

  *status->optr << "Successfully registered callotherfixup" << endl;
}

/// \class IfcVolatile
/// \brief Mark a memory range as volatile: `volatile <address+size>`
///
/// The memory range provided on the command-line is marked as \e volatile, warning
/// the decompiler analysis that values in the range my change unexpectedly.
void IfcVolatile::execute(istream &s)

{
  int4 size = 0;
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");
  Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read required address

  if (size == 0)
    throw IfaceExecutionError("Must specify a size");
  Range range( addr.getSpace(), addr.getOffset(), addr.getOffset() + (size-1));
  dcp->conf->symboltab->setPropertyRange(Varnode::volatil,range);

  *status->optr << "Successfully marked range as volatile" << endl;
}

/// \class IfcReadonly
/// \brief Mark a memory range as read-only: `readonly <address+size>`
///
/// The memory range provided on the command-line is marked as \e read-only, which
/// allows the decompiler to propagate values pulled from the LoadImage for the range
/// as constants.
void IfcReadonly::execute(istream &s)

{
  int4 size = 0;
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");
  Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read required address

  if (size == 0)
    throw IfaceExecutionError("Must specify a size");
  Range range( addr.getSpace(), addr.getOffset(), addr.getOffset() + (size-1));
  dcp->conf->symboltab->setPropertyRange(Varnode::readonly,range);

  *status->optr << "Successfully marked range as readonly" << endl;
}

/// \class IfcPointerSetting
/// \brief Create a pointer with additional settings: `pointer setting <name> <basetype> offset <val>`
///
/// The new data-type is named and must be pointer.  It must have a setting
///   - \b offset which creates a shifted pointer
void IfcPointerSetting::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");
  string typeName;
  string baseType;
  string setting;

  s >> ws;
  if (s.eof())
    throw IfaceParseError("Missing name");
  s >> typeName >> ws;
  if (s.eof())
    throw IfaceParseError("Missing base-type");
  s >> baseType >> ws;
  if (s.eof())
    throw IfaceParseError("Missing setting");
  s >> setting >> ws;
  if (setting == "offset") {
    int4 off = -1;
    s.unsetf(ios::dec | ios::hex | ios::oct); // Let user specify base
    s >> off;
    if (off <= 0)
      throw IfaceParseError("Missing offset");
    Datatype *bt = dcp->conf->types->findByName(baseType);
    if (bt == (Datatype *)0 || bt->getMetatype() != TYPE_STRUCT)
      throw IfaceParseError("Base-type must be a structure");
    Datatype *ptrto = TypePointerRel::getPtrToFromParent(bt, off, *dcp->conf->types);
    AddrSpace *spc = dcp->conf->getDefaultDataSpace();
    dcp->conf->types->getTypePointerRel(spc->getAddrSize(), bt, ptrto, spc->getWordSize(), off,typeName);
  }
  else
    throw IfaceParseError("Unknown pointer setting: "+setting);
  *status->optr << "Successfully created pointer: " << typeName << endl;
}

/// \class IfcPreferSplit
/// \brief Mark a storage location to be split: `prefersplit <address+size> <splitsize>`
///
/// The storage location is marked for splitting in any future decompilation.
/// During decompilation, any Varnode matching the storage location on the command-line
/// will be generally split into two pieces, where the final command-line parameter
/// indicates the number of bytes in the first piece.  A Varnode is split only if operations
/// involving it can also be split.  See PreferSplitManager.
void IfcPreferSplit::execute(istream &s)

{
  int4 size = 0;
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");
  Address addr = parse_machaddr(s,size,*dcp->conf->types); // Read storage location
  if (size == 0)
    throw IfaceExecutionError("Must specify a size");
  int4 split = -1;

  s >> ws; 
  if (s.eof())
    throw IfaceParseError("Missing split offset");
  s >> dec >> split;
  if (split == -1)
    throw IfaceParseError("Bad split offset");
  dcp->conf->splitrecords.emplace_back();
  PreferSplitRecord &rec( dcp->conf->splitrecords.back() );

  rec.storage.space = addr.getSpace();
  rec.storage.offset = addr.getOffset();
  rec.storage.size = size;
  rec.splitoffset = split;

  *status->optr << "Successfully added split record" << endl;
}

/// \class IfcStructureBlocks
/// \brief Structure an external control-flow graph: `structure blocks <infile> <outfile>`
///
/// The control-flow graph is read in from XML file, structuring is performed, and the
/// result is written out to a separate XML file.
void IfcStructureBlocks::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("No load image present");

  string infile,outfile;
  s >> infile;
  s >> outfile;

  if (infile.empty())
    throw IfaceParseError("Missing input file");
  if (outfile.empty())
    throw IfaceParseError("Missing output file");

  ifstream fs;
  fs.open(infile.c_str());
  if (!fs)
    throw IfaceExecutionError("Unable to open file: "+infile);
  
  DocumentStorage store;
  Document *doc = store.parseDocument(fs);
  fs.close();

  try {
    BlockGraph ingraph;
    ingraph.restoreXml(doc->getRoot(),dcp->conf);
    
    BlockGraph resultgraph;
    vector<FlowBlock *> rootlist;
    
    resultgraph.buildCopy(ingraph);
    resultgraph.structureLoops(rootlist);
    resultgraph.calcForwardDominator(rootlist);

    CollapseStructure collapse(resultgraph);
    collapse.collapseAll();

    ofstream sout;
    sout.open(outfile.c_str());
    if (!sout)
      throw IfaceExecutionError("Unable to open output file: "+outfile);
    resultgraph.saveXml(sout);
    sout.close();
  }
  catch(LowlevelError &err) {
    *status->optr << err.explain << endl;
  }
}

#ifdef CPUI_RULECOMPILE
void IfcParseRule::execute(istream &s)

{ // Parse a rule and print it out as a C routine
  string filename;
  bool debug = false;

  s >> filename;
  if (filename.size() == 0)
    throw IfaceParseError("Missing rule input file");

  s >> ws;
  if (!s.eof()) {
    string val;
    s >> val;
    if ((val=="true")||(val=="debug"))
      debug = true;
  }
  ifstream thefile( filename.c_str());
  if (!thefile)
    throw IfaceExecutionError("Unable to open rule file: "+filename);

  RuleCompile ruler;
  ruler.setErrorStream(*status->optr);
  ruler.run(thefile,debug);
  if (ruler.numErrors() != 0) {
    *status->optr << "Parsing aborted on error" << endl;
    return;
  }
  int4 opparam;
  vector<OpCode> opcodelist;
  opparam = ruler.postProcessRule(opcodelist);
  UnifyCPrinter cprinter;
  cprinter.initializeRuleAction(ruler.getRule(),opparam,opcodelist);
  cprinter.addNames(ruler.getNameMap());
  cprinter.print(*status->optr);
}

void IfcExperimentalRules::execute(istream &s)

{
  string filename;

  if (dcp->conf != (Architecture *)0)
    throw IfaceExecutionError("Experimental rules must be registered before loading architecture");
  s >> filename;
  if (filename.size() == 0)
    throw IfaceParseError("Missing name of file containing experimental rules");
  dcp->experimental_file = filename;
  *status->optr << "Successfully registered experimental file " << filename << endl;
}
#endif

/// \class IfcPrintActionstats
/// \brief Print transform statistics for the decompiler engine: `print actionstats`
///
/// Counts for each Action and Rule are displayed; showing the number of attempts,
/// both successful and not, that were made to apply each one.  Counts can accumulate
/// over multiple decompilations.
void IfcPrintActionstats::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("Image not loaded");
  if (dcp->conf->allacts.getCurrent() == (Action *)0)
    throw IfaceExecutionError("No action set");

  dcp->conf->allacts.getCurrent()->printStatistics(*status->fileoptr);
}

/// \class IfcResetActionstats
/// \brief Reset transform statistics for the decompiler engine: `reset actionstats`
///
/// Counts for each Action and Rule are reset to zero.
void IfcResetActionstats::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("Image not loaded");
  if (dcp->conf->allacts.getCurrent() == (Action *)0)
    throw IfaceExecutionError("No action set");

  dcp->conf->allacts.getCurrent()->resetStats();
}

/// \class IfcCountPcode
/// \brief Count p-code in the \e current function: `count pcode`
///
/// The count is based on the number of existing p-code operations in
/// the current function, which may vary depending on the state of it transformation.
void IfcCountPcode::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("Image not loaded");

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  uint4 count = 0;
  list<PcodeOp *>::const_iterator iter,enditer;
  iter = dcp->fd->beginOpAlive();
  enditer = dcp->fd->endOpAlive();
  while(iter != enditer) {
    count += 1;
    ++iter;
  }
  *status->optr << "Count - pcode = " << dec << count << endl;
}

/// \class IfcAnalyzeRange
/// \brief Run value-set analysis on the \e current function: `analyze range full|partial <varnode>`
///
/// The analysis targets a single varnode as specified on the command-line and is based on
/// the existing data-flow graph for the current function.
/// The possible values that can reach the varnode at its point of definition, and
/// at any point it is involved in a LOAD or STORE, are displayed.
/// The keywords \b full and \b partial choose whether the value-set analysis uses
/// full or partial widening.
void IfcAnalyzeRange::execute(istream &s)

{
  if (dcp->conf == (Architecture *)0)
    throw IfaceExecutionError("Image not loaded");
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  bool useFullWidener;
  string token;
  s >> ws >> token;
  if (token == "full")
    useFullWidener = true;
  else if (token == "partial") {
    useFullWidener = false;
  }
  else
    throw IfaceParseError("Must specify \"full\" or \"partial\" widening");
  Varnode *vn = dcp->readVarnode(s);
  vector<Varnode *> sinks;
  vector<PcodeOp *> reads;
  sinks.push_back(vn);
  for(list<PcodeOp *>::const_iterator iter=vn->beginDescend();iter!=vn->endDescend();++iter) {
    PcodeOp *op = *iter;
    if (op->code() == CPUI_LOAD || op->code() == CPUI_STORE)
      reads.push_back(op);
  }
  Varnode *stackReg = dcp->fd->findSpacebaseInput(dcp->conf->getStackSpace());
  ValueSetSolver vsSolver;
  vsSolver.establishValueSets(sinks, reads, stackReg, false);
  if (useFullWidener) {
    WidenerFull widener;
    vsSolver.solve(10000,widener);
  }
  else {
    WidenerNone widener;
    vsSolver.solve(10000,widener);
  }
  list<ValueSet>::const_iterator iter;
  for(iter=vsSolver.beginValueSets();iter!=vsSolver.endValueSets();++iter) {
    (*iter).printRaw(*status->optr);
    *status->optr << endl;
  }
  map<SeqNum,ValueSetRead>::const_iterator riter;
  for(riter=vsSolver.beginValueSetReads();riter!=vsSolver.endValueSetReads();++riter) {
    (*riter).second.printRaw(*status->optr);
    *status->optr << endl;
  }
}

/// \class IfcLoadTestFile
/// \brief Load a datatest environment file: `load test <filename>`
///
/// The program and associated script from a decompiler test file is loaded
void IfcLoadTestFile::execute(istream &s)

{
  string filename;

  if (dcp->conf != (Architecture *)0)
    throw IfaceExecutionError("Load image already present");
  s >> filename;
  dcp->testCollection = new FunctionTestCollection(status);
  dcp->testCollection->loadTest(filename);
#ifdef OPACTION_DEBUG
  dcp->conf->setDebugStream(status->fileoptr);
#endif
  *status->optr << filename << " test successfully loaded: " << dcp->conf->getDescription() << endl;
}

/// \class IfcListTestCommands
/// \brief List all the script commands in the current test: `list test commands`
void IfcListTestCommands::execute(istream &s)

{
  if (dcp->testCollection == (FunctionTestCollection *)0)
    throw IfaceExecutionError("No test file is loaded");
  for(int4 i=0;i<dcp->testCollection->numCommands();++i) {
    *status->optr << ' ' << dec << i+1 << ": " << dcp->testCollection->getCommand(i) << endl;
  }
}

/// \class IfcExecuteTestCommand
/// \brief Execute a specified range of the test script: `execute test command <#>-<#>
void IfcExecuteTestCommand::execute(istream &s)

{
  if (dcp->testCollection == (FunctionTestCollection *)0)
    throw IfaceExecutionError("No test file is loaded");
  int4 first = -1;
  int4 last = -1;
  char hyphen;

  s >> ws >> dec >> first;
  first -= 1;
  if (first < 0 || first > dcp->testCollection->numCommands())
    throw IfaceExecutionError("Command index out of bounds");
  s >> ws;
  if (!s.eof()) {
    s >> ws >> hyphen;
    if (hyphen != '-')
      throw IfaceExecutionError("Missing hyphenated command range");
    s >> ws >> last;
    last -= 1;
    if (last < 0 || last < first || last > dcp->testCollection->numCommands())
      throw IfaceExecutionError("Command index out of bounds");
  }
  else {
    last = first;
  }
  ostringstream s1;
  for(int4 i=first;i<=last;++i) {
    s1 << dcp->testCollection->getCommand(i) << endl;
  }
  istringstream *s2 = new istringstream(s1.str());
  status->pushScript(s2, "test> ");
}

#ifdef OPACTION_DEBUG

void IfcDebugAction::execute(istream &s)

{
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");
  string actionname;
  s >> ws >> actionname;
  if (actionname.empty())
    throw IfaceParseError("Missing name of action to debug");
  if (!dcp->conf->allacts.getCurrent()->turnOnDebug(actionname))
    throw IfaceParseError("Unable to find action "+actionname);
}

void IfcTraceBreak::execute(istream &s)

{				// Set a opactdbg trace break point
  int4 count;
  
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  s >> ws;
  s.unsetf(ios::dec | ios::hex | ios::oct); // Let user specify base
  count = -1;
  s >> count;
  if (count == -1)
    throw IfaceParseError("Missing trace count");

  dcp->fd->debugSetBreak(count);
}

void IfcTraceAddress::execute(istream &s)

{				// Set a opactdbg trace point
  uintm uqlow,uqhigh;
  int4 discard;

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  Address pclow,pchigh;
  s >> ws;
  if (!s.eof()) {
    pclow = parse_machaddr(s,discard,*dcp->conf->types);
    s >> ws;
  }
  pchigh = pclow;
  if (!s.eof()) {
    pchigh = parse_machaddr(s,discard,*dcp->conf->types);
    s >> ws;
  }
  uqhigh = uqlow = ~((uintm)0);
  if (!s.eof()) {
    s.unsetf(ios::dec | ios::hex | ios::oct); // Let user specify base
    s >> uqlow >> uqhigh >> ws;
  }
  dcp->fd->debugSetRange(pclow,pchigh,uqlow,uqhigh);
  *status->optr << "OK (" << dec << dcp->fd->debugSize() << " ranges)\n";
}

void IfcTraceEnable::execute(istream &s)

{				// Turn on trace
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  dcp->fd->debugEnable();
  *status->optr << "OK\n";
}

void IfcTraceDisable::execute(istream &s)

{				// Turn off trace
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  dcp->fd->debugDisable();
  *status->optr << "OK\n";
}

void IfcTraceClear::execute(istream &s)

{				// Clear existing debug trace ranges
  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  *status->optr << dec << dcp->fd->debugSize() << " ranges cleared\n";
  dcp->fd->debugDisable();
  dcp->fd->debugClear();
}

void IfcTraceList::execute(istream &s)

{				// List debug trace ranges
  int4 size,i;

  if (dcp->fd == (Funcdata *)0)
    throw IfaceExecutionError("No function selected");

  size = dcp->fd->debugSize();
  if (dcp->fd->opactdbg_on)
    *status->optr << "Trace enabled (";
  else
    *status->optr << "Trace disabled (";
  *status->optr << dec << size << " total ranges)\n";
  for(i=0;i<size;++i)
    dcp->fd->debugPrintRange(i);
}
    
static vector<Funcdata *> jumpstack;
static IfaceDecompData *dcp_callback;
static IfaceStatus *status_callback;

static void jump_callback(Funcdata &orig,Funcdata &fd)

{ // Replaces reset/perform in Funcdata::stageJumpTable
  IfaceDecompData *newdcp = dcp_callback;
  IfaceStatus *newstatus = status_callback;
  jumpstack.push_back(newdcp->fd);

  // We create a new "sub" interface using the same input output
  ostringstream s1;
  s1 << fd.getName() << "> ";
  // We keep the commands already registered.
  // We should probably "de"-register some of the commands
  // that can't really be used in this subcontext.
  newdcp->fd = &fd;
  Action *rootaction = newdcp->conf->allacts.getCurrent();
  rootaction->reset(*newdcp->fd);

  // Set a break point right at the start
  rootaction->setBreakPoint(Action::tmpbreak_start,rootaction->getName());
  // Start up the action
  int4 res = rootaction->perform( *newdcp->fd );
  if (res >= 0)
    throw LowlevelError("Did not catch jumptable breakpoint");
  *newstatus->optr << "Breaking for jumptable partial function" << endl;
  *newstatus->optr << newdcp->fd->getName() << endl;
  *newstatus->optr << "Type \"cont\" to continue debugging." << endl;
  *newstatus->optr << "After completion type \"quit\" to continue in parent." << endl;
  mainloop(newstatus);
  newstatus->done = false;	// "quit" only terminates one level
  *newstatus->optr << "Finished jumptable partial function" << endl;
  newdcp->fd = jumpstack.back();
  jumpstack.pop_back();
}

void IfcBreakjump::execute(istream &s)

{
  dcp->jumptabledebug = true;
  dcp_callback = dcp;
  status_callback = status;
  *status->optr << "Jumptable debugging enabled" << endl;
  if (dcp->fd != (Funcdata *)0)
    dcp->fd->enableJTCallback(jump_callback);
}

#endif

/// Execute one command and handle any exceptions.
/// Error messages are printed to the console.  For low-level errors,
/// the current function is reset to null
/// \param status is the console interface
/// \param dcp is the shared program data
void execute(IfaceStatus *status,IfaceDecompData *dcp)

{
  try {
    status->runCommand();	// Try to run one command-line
    return;
  }
  catch(IfaceParseError &err) {
    *status->optr << "Command parsing error: " << err.explain << endl;
  }
  catch(IfaceExecutionError &err) {
    *status->optr << "Execution error: " << err.explain << endl;
  }
  catch(IfaceError &err) {
    *status->optr << "ERROR: " << err.explain << endl;
  }
  catch(ParseError &err) {
    *status->optr << "Parse ERROR: " << err.explain << endl;
  }
  catch(RecovError &err) {
    *status->optr << "Function ERROR: " << err.explain << endl;
  }
  catch(LowlevelError &err) {
    *status->optr << "Low-level ERROR: " << err.explain << endl;
    dcp->abortFunction(*status->optr);
  }
  catch(XmlError &err) {
    *status->optr << "XML ERROR: " << err.explain << endl;
    dcp->abortFunction(*status->optr);
  }
  status->evaluateError();
}

/// Execution loops until either the \e done field in the console is set
/// or if all streams have ended.  This handles popping script states pushed
/// on by the IfcSource command.
/// \param status is the console interface
void mainloop(IfaceStatus *status)

{
  IfaceDecompData *dcp = (IfaceDecompData *)status->getData("decompile");
  for(;;) {
    while(!status->isStreamFinished()) {
      status->writePrompt();
      status->optr->flush();
      execute(status,dcp);
    }
    if (status->done) break;
    if (status->getNumInputStreamSize()==0) break;
    status->popScript();
  }
}

/// \class IfcSource
/// \brief Execute a command script : `source <filename>`
///
/// A file is opened as a new streaming source of command-lines.
/// The stream is pushed onto the stack for the console.
void IfcSource::execute(istream &s)

{
  string filename;

  s >> ws;
  if (s.eof())
    throw IfaceParseError("filename parameter required for source");

  s >> filename;
  status->pushScript(filename,filename+"> ");
}