File: SingleSteppingEngine.cs

package info (click to toggle)
mono-debugger 0.60%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 9,556 kB
  • ctags: 22,787
  • sloc: ansic: 99,407; cs: 42,429; sh: 9,192; makefile: 376
file content (3838 lines) | stat: -rw-r--r-- 104,805 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Configuration;
using System.Globalization;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Remoting.Messaging;

using Mono.Debugger.Languages;
using Mono.Debugger.Languages.Mono;
using Mono.Debugger.Architectures;

namespace Mono.Debugger.Backend
{
// <summary>
//   The single stepping engine is responsible for doing all the stepping
//   operations.
//
//     sse                  - short for single stepping engine.
//
//     stepping operation   - an operation which has been invoked by the user such
//                            as StepLine(), NextLine() etc.
//
//     atomic operation     - an operation which the sse invokes on the target
//                            such as stepping one machine instruction or resuming
//                            the target until a breakpoint is hit.
//
//     step frame           - an address range; the sse invokes atomic operations
//                            until the target hit a breakpoint, received a signal
//                            or stopped at an address outside this range.
//
//     temporary breakpoint - a breakpoint which is automatically removed the next
//                            time the target stopped; it is used to step over
//                            method calls.
//
//     source stepping op   - stepping operation based on the program's source code,
//                            such as StepLine() or NextLine().
//
//     native stepping op   - stepping operation based on the machine code such as
//                            StepInstruction() or NextInstruction().
//
//   The SingleSteppingEngine supports both synchronous and asynchronous
//   operations; in synchronous mode, the engine waits until the child has stopped
//   before returning.  In either case, the step commands return true on success
//   and false an error.
//
//   Since the SingleSteppingEngine can be used from multiple threads at the same
//   time, you can no longer safely use the `State' property to find out whether
//   the target is stopped or not.  It is safe to call all the step commands from
//   multiple threads, but for obvious reasons only one command can run at a
//   time.  So if you attempt to issue a step command while the engine is still
//   busy, the step command will return false to signal this error.
// </summary>

	// <summary>
	//   The ThreadManager creates one SingleSteppingEngine instance for each thread
	//   in the target.
	//
	//   The `SingleSteppingEngine' class is basically just responsible for whatever happens
	//   in the background thread: processing commands and events.  Their methods
	//   are just meant to be called from the SingleSteppingEngine (since it's a
	//   protected nested class they can't actually be called from anywhere else).
	//
	//   See the `Thread' class for the "user interface".
	// </summary>
	internal class SingleSteppingEngine : ThreadServant
	{
		// <summary>
		//   This is invoked after compiling a trampoline - it returns whether or
		//   not we should enter that trampoline.
		// </summary>
		internal delegate bool TrampolineHandler (Method method);
		internal delegate bool CheckBreakpointHandler ();

		protected SingleSteppingEngine (ThreadManager manager, ProcessServant process,
						ProcessStart start)
			: base (manager, process)
		{
			this.start = start;

			Report.Debug (DebugFlags.Threads, "New SSE ({0}): {1}",
				      DebuggerWaitHandle.CurrentThread, this);

			exception_handlers = new Hashtable ();
		}

		public SingleSteppingEngine (ThreadManager manager, ProcessServant process,
					     ProcessStart start, out CommandResult result)
			: this (manager, process, start)
		{
			inferior = Inferior.CreateInferior (manager, process, start);
			inferior.TargetOutput += new TargetOutputHandler (inferior_output_handler);

			is_main = true;
			if (start.PID != 0) {
				this.pid = start.PID;
				inferior.Attach (pid);
			} else {
				pid = inferior.Run (true);
			}

			result = new ThreadCommandResult (thread);
			current_operation = new OperationStart (this, result);
		}

		public SingleSteppingEngine (ThreadManager manager, ProcessServant process,
					     Inferior inferior, int pid)
			: this (manager, process, inferior.ProcessStart)
		{
			this.inferior = inferior;
			this.pid = pid;
		}

		public CommandResult StartThread (bool do_attach)
		{
			CommandResult result = new ThreadCommandResult (thread);
			if (do_attach)
				current_operation = new OperationInitialize (this, result);
			else
				current_operation = new OperationRun (this, result);
			return result;
		}

		internal void InitAfterFork ()
		{
			CommandResult result = new ThreadCommandResult (thread);
			current_operation = new OperationRun (this, result);
			PushOperation (new OperationInitAfterFork (this));
		}

#region child event processing
		// <summary>
		//   This is called from the SingleSteppingEngine's main event loop to give
		//   us the next event - `status' has no meaning to us, it's just meant to
		//   be passed to inferior.ProcessEvent() to get the actual event.
		// </summary>
		// <remarks>
		//   Actually, `status' is the waitpid() status code.  In Linux 2.6.x, you
		//   can call waitpid() from any thread in the debugger, but we need to get
		//   the target's registers to find out whether it's a breakpoint etc.
		//   That's done in inferior.ProcessEvent() - which must always be called
		//   from the engine's thread.
		// </remarks>
		public void ProcessEvent (int status)
		{
			if (inferior == null)
				return;

			ProcessEvent (inferior.ProcessEvent (status));
		}

		public void ProcessEvent (Inferior.ChildEvent cevent)
		{
			Report.Debug (DebugFlags.EventLoop, "{0} received event {1} {2}",
				      this, cevent, stop_requested ? " - stop requested" : "");

			if (killed && (cevent.Type != Inferior.ChildEventType.CHILD_EXITED)) {
				Report.Debug (DebugFlags.EventLoop,
					      "{0} received event {1} when already killed",
					      this, cevent);
				return;
			}

			if (has_thread_lock) {
				Report.Debug (DebugFlags.EventLoop,
					      "{0} received event {1} while being thread-locked ({2})",
					      this, cevent, stop_event);
				if (stop_event != null)
					throw new InternalError ();
				stop_event = cevent;
				stopped = true;
				return;
			}
			if (cevent.Type == Inferior.ChildEventType.CHILD_NOTIFICATION)
				Report.Debug (DebugFlags.Notification,
					      "{0} received event {1} {2}",
					      this, cevent, (NotificationType) cevent.Argument);
			else if ((cevent.Type != Inferior.ChildEventType.CHILD_EXITED) &&
				 (cevent.Type != Inferior.ChildEventType.CHILD_SIGNALED))
				Report.Debug (DebugFlags.EventLoop,
					      "{0} received event {1} at {2} while running {3}",
					      this, cevent, inferior.CurrentFrame,
					      current_operation);
			else
				Report.Debug (DebugFlags.EventLoop,
					      "{0} received event {1} while running {2}",
					      this, cevent, current_operation);

			if ((cevent.Type == Inferior.ChildEventType.CHILD_EXITED) ||
			    (cevent.Type == Inferior.ChildEventType.CHILD_SIGNALED)) {
				Report.Debug (DebugFlags.SSE, "{0} is now dead!", this);
				dead = true;
			}

			if (cevent.Type == Inferior.ChildEventType.CHILD_INTERRUPTED) {
				stop_requested = false;
				frame_changed (inferior.CurrentFrame, null);
				OperationCompleted (new TargetEventArgs (TargetEventType.TargetInterrupted, 0, current_frame));
				return;
			}

			bool resume_target;
			if (manager.HandleChildEvent (this, inferior, ref cevent, out resume_target)) {
				Report.Debug (DebugFlags.EventLoop,
					      "{0} done handling event: {1} {2} {3} {4}",
					      this, cevent, resume_target, stop_requested,
					      has_thread_lock);
				if (!resume_target)
					return;
				if (stop_requested) {
					stop_requested = false;
					frame_changed (inferior.CurrentFrame, null);
					OperationCompleted (new TargetEventArgs (TargetEventType.TargetStopped, 0, current_frame));
					return;
				}
				inferior.Continue ();
				return;
			}
			ProcessChildEvent (cevent);
		}

		// <summary>
		//   Process one event from the target.  The return value specifies whether
		//   we started another atomic operation or whether the target is still
		//   stopped.
		//
		//   This method is called each time an atomic operation is completed - or
		//   something unexpected happened, for instance we hit a breakpoint, received
		//   a signal or just died.
		//
		//   Now, our first task is figuring out whether the atomic operation actually
		//   completed, ie. the target stopped normally.
		// </summary>
		protected void ProcessChildEvent (Inferior.ChildEvent cevent)
		{
			Inferior.ChildEventType message = cevent.Type;
			int arg = (int) cevent.Argument;

			TargetEventArgs result = null;

			if ((message == Inferior.ChildEventType.THROW_EXCEPTION) ||
			    (message == Inferior.ChildEventType.HANDLE_EXCEPTION)) {
				TargetAddress info = new TargetAddress (
					inferior.AddressDomain, cevent.Data1);
				TargetAddress ip = new TargetAddress (
					manager.AddressDomain, cevent.Data2);

				Report.Debug (DebugFlags.EventLoop,
					      "{0} received exception: {1} {2} {3}",
					      this, message, info, ip);

				TargetAddress stack = inferior.ReadAddress (info);
				TargetAddress exc = inferior.ReadAddress (info + inferior.TargetAddressSize);

				bool stop_on_exc;
				if (message == Inferior.ChildEventType.THROW_EXCEPTION)
					stop_on_exc = throw_exception (stack, exc, ip);
				else
					stop_on_exc = handle_exception (stack, exc, ip);

				Report.Debug (DebugFlags.SSE,
					      "{0} {1}stopping at exception ({2}:{3}:{4}) - {5} - {6}",
					      this, stop_on_exc ? "" : "not ", stack, exc, ip,
					      current_operation, temp_breakpoint_id);

				if (stop_on_exc) {
					inferior.WriteInteger (info + 2 * inferior.TargetAddressSize, 1);
					PushOperation (new OperationException (this, ip, exc, false));
					return;
				}

				do_continue ();
				return;
			}

			// To step over a method call, the sse inserts a temporary
			// breakpoint immediately after the call instruction and then
			// resumes the target.
			//
			// If the target stops and we have such a temporary breakpoint, we
			// need to distinguish a few cases:
			//
			// a) we may have received a signal
			// b) we may have hit another breakpoint
			// c) we actually hit the temporary breakpoint
			//
			// In either case, we need to remove the temporary breakpoint if
			// the target is to remain stopped.  Note that this piece of code
			// here only deals with the temporary breakpoint, the handling of
			// a signal or another breakpoint is done later.
			if (temp_breakpoint_id != 0) {
				if ((message == Inferior.ChildEventType.CHILD_EXITED) ||
				    (message == Inferior.ChildEventType.CHILD_SIGNALED))
					// we can't remove the breakpoint anymore after
					// the target exited, but we need to clear this id.
					temp_breakpoint_id = 0;
				else if ((message == Inferior.ChildEventType.CHILD_HIT_BREAKPOINT) &&
					 (arg == temp_breakpoint_id)) {
					// we hit the temporary breakpoint; this'll always
					// happen in the `correct' thread since the
					// `temp_breakpoint_id' is only set in this
					// SingleSteppingEngine and not in any other thread's.

					inferior.RemoveBreakpoint (temp_breakpoint_id);
					temp_breakpoint_id = 0;

					Breakpoint bpt = lookup_breakpoint (arg);
					Report.Debug (DebugFlags.SSE,
						      "{0} hit temporary breakpoint {1} at {2} {3}",
						      this, arg, inferior.CurrentFrame, bpt);
					if ((bpt == null) || !bpt.Breaks (thread.ID)) {
						message = Inferior.ChildEventType.CHILD_STOPPED;
						arg = 0;
						cevent = new Inferior.ChildEvent (
							Inferior.ChildEventType.CHILD_STOPPED, 0, 0, 0);
					} else {
						ProcessChildEvent (cevent, result);
						return;
					}
				}
			}

			if (message == Inferior.ChildEventType.CHILD_HIT_BREAKPOINT) {
				// Ok, the next thing we need to check is whether this is actually "our"
				// breakpoint or whether it belongs to another thread.  In this case,
				// `step_over_breakpoint' does everything for us and we can just continue
				// execution.
				bool remain_stopped = child_breakpoint (cevent, arg);
				if (stop_requested) {
					stop_requested = false;
					frame_changed (inferior.CurrentFrame, null);
					if (remain_stopped)
						result = new TargetEventArgs (TargetEventType.TargetHitBreakpoint, arg, current_frame);
					else
						result = new TargetEventArgs (TargetEventType.TargetStopped, 0, current_frame);
				} else if (!remain_stopped) {
					do_continue ();
					return;
				}
			}

			switch (message) {
			case Inferior.ChildEventType.CHILD_STOPPED:
				if (stop_requested || (arg != 0)) {
					stop_requested = false;
					frame_changed (inferior.CurrentFrame, null);
					result = new TargetEventArgs (
						TargetEventType.TargetStopped, arg,
						current_frame);
				}

				break;

			case Inferior.ChildEventType.UNHANDLED_EXCEPTION: {
				TargetAddress exc = new TargetAddress (
					manager.AddressDomain, cevent.Data1);
				TargetAddress ip = new TargetAddress (
					manager.AddressDomain, cevent.Data2);

				PushOperation (new OperationException (this, ip, exc, true));
				return;
			}

			case Inferior.ChildEventType.CHILD_HIT_BREAKPOINT:
				break;

			case Inferior.ChildEventType.CHILD_SIGNALED:
				if (killed)
					result = new TargetEventArgs (TargetEventType.TargetExited, 0);
				else
					result = new TargetEventArgs (TargetEventType.TargetSignaled, arg);
				break;

			case Inferior.ChildEventType.CHILD_EXITED:
				result = new TargetEventArgs (TargetEventType.TargetExited, arg);
				break;

			case Inferior.ChildEventType.CHILD_CALLBACK_COMPLETED:
				frame_changed (inferior.CurrentFrame, null);
				result = new TargetEventArgs (
					TargetEventType.TargetStopped, 0,
					current_frame);
				break;
			}

			ProcessChildEvent (cevent, result);
		}

		protected void ProcessChildEvent (Inferior.ChildEvent cevent, TargetEventArgs result)
		{
			Inferior.ChildEventType message = cevent.Type;
			int arg = (int) cevent.Argument;

		send_result:
			// If `result' is not null, then the target stopped abnormally.
			if (result != null) {
				if (is_main && !reached_main &&
				    (cevent.Type != Inferior.ChildEventType.CHILD_EXITED) &&
				    (cevent.Type != Inferior.ChildEventType.CHILD_SIGNALED)) {
					reached_main = true;

					if (!process.IsManaged)
						inferior.InitializeModules ();
				}
				// Ok, inform the user that we stopped.
				OperationCompleted (result);
				return;
			}

			//
			// Sometimes, we need to do just one atomic operation - in all
			// other cases, `current_operation' is the current stepping
			// operation.
			//
			// ProcessEvent() will either start another atomic operation
			// (and return false) or tell us the stepping operation is
			// completed by returning true.
			//

			if (current_operation != null) {
				bool send_result;

				if (!current_operation.ProcessEvent (cevent, out result, out send_result))
					return;

				if (result != null)
					goto send_result;

				if (!send_result) {
					OperationCompleted (null);
					return;
				}
			}

			//
			// Ok, the target stopped normally.  Now we need to compute the
			// new stack frame and then send the result to our caller.
			//
			TargetAddress frame = inferior.CurrentFrame;

			//
			// We're done with our stepping operation, but first we need to
			// compute the new StackFrame.  While doing this, `frame_changed'
			// may discover that we need to do another stepping operation
			// before telling the user that we're finished.  This is to avoid
			// that we stop in things like a method's prologue or epilogue
			// code.  If that happens, we just continue stepping until we reach
			// the first actual source line in the method.
			//
			Operation new_operation = frame_changed (frame, current_operation);
			if (new_operation != null) {
				Report.Debug (DebugFlags.SSE,
					      "{0} frame changed at {1} => new operation {2}",
					      this, frame, new_operation, message);

				if (message == Inferior.ChildEventType.CHILD_HIT_BREAKPOINT)
					new_operation.PendingBreakpoint = arg;

				ProcessOperation (new_operation);
				return;
			}

			//
			// Now we're really finished.
			//
			int pending_bpt = -1;
			if (message == Inferior.ChildEventType.CHILD_HIT_BREAKPOINT)
				pending_bpt = arg;
			else if (current_operation != null)
				pending_bpt = current_operation.PendingBreakpoint;
			if (pending_bpt >= 0) {
				Breakpoint bpt = lookup_breakpoint (pending_bpt);
				if ((bpt != null) && bpt.Breaks (thread.ID) && !bpt.HideFromUser) {
					result = new TargetEventArgs (
						TargetEventType.TargetHitBreakpoint, bpt.Index,
						current_frame);
					goto send_result;
				}
			}

			result = new TargetEventArgs (TargetEventType.TargetStopped, 0, current_frame);
			goto send_result;
		}
#endregion

		void OperationCompleted (TargetEventArgs result)
		{
			lock (this) {
				remove_temporary_breakpoint ();
				engine_stopped = true;
				last_target_event = result;
				Report.Debug (DebugFlags.EventLoop, "{0} completed operation {1}: {2}",
					      this, current_operation, result);
				if (result != null)
					manager.Debugger.SendTargetEvent (this, result);
				if (current_operation != null) {
					Report.Debug (DebugFlags.EventLoop, "{0} setting completed: {1}",
						      this, current_operation.Result);
					current_operation.Result.Completed ();
					current_operation = null;
				}
			}
		}

		internal void OnManagedThreadCreated (TargetAddress end_stack_address)
		{
			this.end_stack_address = end_stack_address;
		}

		internal void SetTID (long tid)
		{
			this.tid = tid;
		}

		internal void SetManagedThreadData (TargetAddress lmf_address,
						    TargetAddress extended_notifications_addr)
		{
			this.lmf_address = lmf_address;
			this.extended_notifications_addr = extended_notifications_addr;
		}

		internal void OnManagedThreadExited ()
		{
			this.end_stack_address = TargetAddress.Null;
		}

		internal void OnThreadExited (Inferior.ChildEvent cevent)
		{
			TargetEventArgs result;
			int arg = (int) cevent.Argument;
			if (killed)
				result = new TargetEventArgs (TargetEventType.TargetExited, 0);
			else if (cevent.Type == Inferior.ChildEventType.CHILD_SIGNALED)
				result = new TargetEventArgs (TargetEventType.TargetSignaled, arg);
			else
				result = new TargetEventArgs (TargetEventType.TargetExited, arg);
			temp_breakpoint_id = 0;
			OperationCompleted (result);

			process.OnThreadExitedEvent (this);
			Dispose ();
		}

		Breakpoint lookup_breakpoint (int index)
		{
			BreakpointHandle handle = process.BreakpointManager.LookupBreakpoint (index);
			if (handle == null)
				return null;

			return handle.Breakpoint;
		}

		void set_registers (Registers registers)
		{
			if (!registers.FromCurrentFrame)
				throw new InvalidOperationException ();

			this.registers = registers;
			inferior.SetRegisters (registers);
		}

		// <summary>
		//   Start a new stepping operation.
		//
		//   All stepping operations are done asynchronously.
		//
		//   The inferior basically just knows two kinds of stepping operations:
		//   there is do_continue() to continue execution (until a breakpoint is
		//   hit or the target receives a signal or exits) and there is do_step_native()
		//   to single-step one machine instruction.  There's also a version of
		//   do_continue() which takes an address - it inserts a temporary breakpoint
		//   on that address and calls do_continue().
		//
		//   Let's call these "atomic operations" while a "stepping operation" is
		//   something like stepping until the next source line.  We normally need to
		//   do several atomic operations for each stepping operation.
		//
		//   We start a new stepping operation here, but what we actually do is
		//   starting an atomic operation on the target.  Note that we just start it,
		//   but don't wait until is completed.  Once the target is running, we go
		//   back to the main event loop and wait for it (or another thread) to stop
		//   (or to get another command from the user).
		// </summary>
		void StartOperation ()
		{
			lock (this) {
				if (!engine_stopped || (has_thread_lock && (pending_operation != null))) {
					Report.Debug (DebugFlags.Wait,
						      "{0} not stopped", this);
					throw new TargetException (TargetError.NotStopped);
				}

				engine_stopped = false;
				last_target_event = null;
			}
		}

		object SendCommand (TargetAccessDelegate target)
		{
			if (inferior == null)
				throw new TargetException (TargetError.NoTarget);

			if (ThreadManager.InBackgroundThread)
				return target (thread, null);
			else
				return manager.SendCommand (this, target, null);
		}

		CommandResult StartOperation (Operation operation)
		{
			StartOperation ();

			return (CommandResult) SendCommand (delegate {
				return ProcessOperation (operation);
			});
		}

		CommandResult ProcessOperation (Operation operation)
		{
			stop_requested = false;

			if (has_thread_lock) {
				Report.Debug (DebugFlags.SSE,
					      "{0} starting {1} while being thread-locked",
					      this, operation);
				pending_operation = operation;
				return operation.Result;
			} else
				Report.Debug (DebugFlags.SSE,
					      "{0} starting {1}", this, operation);

			current_operation = operation;
			ExecuteOperation (operation);
			return operation.Result;
		}

		void PushOperation (Operation operation)
		{
			current_operation.PushOperation (operation);
			ExecuteOperation (operation);
		}

		void ExecuteOperation (Operation operation)
		{
			try {
				check_inferior ();
				operation.Execute ();
			} catch (Exception ex) {
				Report.Debug (DebugFlags.SSE, "{0} caught exception while " +
					      "processing operation {1}: {2}", this, operation, ex);
				operation.Result.Result = ex;
				OperationCompleted (null);
			}
		}

		public override TargetEventArgs LastTargetEvent {
			get { return last_target_event; }
		}

		public override Method Lookup (TargetAddress address)
		{
			process.UpdateSymbolTable (inferior);
			Method method = process.SymbolTableManager.Lookup (address);
			Report.Debug (DebugFlags.JitSymtab, "{0} lookup {1}: {2}",
				      this, address, method);
			return method;
		}

		public override Symbol SimpleLookup (TargetAddress address, bool exact_match)
		{
			return process.SymbolTableManager.SimpleLookup (address, exact_match);
		}

#region public properties
		internal Inferior Inferior {
			get { return inferior; }
		}

		internal override Architecture Architecture {
			get { return inferior.Architecture; }
		}

		public Thread Thread {
			get { return thread; }
		}

		public override int PID {
			get { return pid; }
		}

		public override long TID {
			get { return tid; }
		}

		public override bool IsAlive {
			get { return !dead && !killed && (inferior != null); }
		}

		public override TargetAddress LMFAddress {
			get { return lmf_address; }
		}

		public override bool CanRun {
			get { return true; }
		}

		public override bool CanStep {
			get { return true; }
		}

		public override bool IsStopped {
			get { return engine_stopped; }
		}

		internal override ProcessServant ProcessServant {
			get { return process; }
		}

		internal override ThreadManager ThreadManager {
			get { return manager; }
		}

		public override Backtrace CurrentBacktrace {
			get { return current_backtrace; }
		}

		public override StackFrame CurrentFrame {
			get { return current_frame; }
		}

		public override Method CurrentMethod {
			get { return current_method; }
		}

		public override TargetAddress CurrentFrameAddress {
			get { return inferior.CurrentFrame; }
		}

		protected MonoDebuggerInfo MonoDebuggerInfo {
			get { return process.MonoManager.MonoDebuggerInfo; }
		}

		public override TargetState State {
			get {
				if (inferior == null)
					return TargetState.NoTarget;
				else
					return inferior.State;
			}
		}
#endregion

		protected TargetAddress EndStackAddress {
			get { return end_stack_address; }
		}

		public override TargetMemoryInfo TargetMemoryInfo {
			get {
				check_inferior ();
				return inferior.TargetMemoryInfo;
			}
		}

		public override TargetMemoryArea[] GetMemoryMaps ()
		{
			check_inferior ();
			return inferior.GetMemoryMaps ();
		}

		public override void Kill ()
		{
			killed = true;
			SendCommand (delegate {
				inferior.Kill ();
				return null;
			});
		}

		internal override object DoTargetAccess (TargetAccessHandler func)
		{
			return SendCommand (delegate {
				return func (inferior);
			});
		}

		public override void Detach ()
		{
			SendCommand (delegate {
				if (!engine_stopped) {
					Report.Debug (DebugFlags.Wait,
						      "{0} not stopped", this);
					throw new TargetException (TargetError.NotStopped);
				}

				process.AcquireGlobalThreadLock (this);
				process.BreakpointManager.RemoveAllBreakpoints (inferior);

				if (process.MonoManager != null)
					StartOperation (new OperationDetach (this));
				else
					DoDetach ();
				return null;
			});
		}

		protected void DoDetach ()
		{
			foreach (ThreadServant servant in process.ThreadServants)
				servant.DetachThread ();
		}

		internal override void DetachThread ()
		{
			if (inferior != null) {
				inferior.Detach ();
				inferior.Dispose ();
				inferior = null;
			}

			OperationCompleted (new TargetEventArgs (TargetEventType.TargetExited, 0));
			process.OnThreadExitedEvent (this);
			Dispose ();
		}

		public override void Stop ()
		{
			lock (this) {
				Report.Debug (DebugFlags.EventLoop, "{0} interrupt: {1} {2}",
					      this, engine_stopped, current_operation);

				if (engine_stopped || stop_requested)
					return;

				stop_requested = true;
				bool stopped = inferior.Stop ();
				Report.Debug (DebugFlags.EventLoop, "{0} interrupt #1: {1}",
					      this, stopped);

				if (current_operation is OperationStepOverBreakpoint) {
					int index = ((OperationStepOverBreakpoint) current_operation).Index;

					Report.Debug (DebugFlags.SSE,
						      "{0} stepped over breakpoint {1}: {2}",
						      this, index, inferior.CurrentFrame);

					inferior.EnableBreakpoint (index);
					process.ReleaseGlobalThreadLock (this);
				}

				if (!stopped) {
					// We're already stopped, so just consider the
					// current operation as finished.
					engine_stopped = true;
					stop_requested = false;

					frame_changed (inferior.CurrentFrame, null);
					TargetEventArgs args = new TargetEventArgs (
						TargetEventType.FrameChanged, current_frame);
					OperationCompleted (args);
				}
			}
		}

		protected void check_inferior ()
		{
			if (inferior == null)
				throw new TargetException (TargetError.NoTarget);
		}

		// <summary>
		//   A breakpoint has been hit; now the sse needs to find out what do do:
		//   either ignore the breakpoint and continue or keep the target stopped
		//   and send out the notification.
		//
		//   If @index is zero, we hit an "unknown" breakpoint - ie. a
		//   breakpoint which we did not create.  Normally, this means that there
		//   is a breakpoint instruction (such as G_BREAKPOINT ()) in the code.
		//   Such unknown breakpoints are handled by the Debugger; one of
		//   the language backends may recognize the breakpoint's address, for
		//   instance if this is the JIT's breakpoint trampoline.
		//
		//   Returns true if the target should remain stopped and false to
		//   continue stepping.
		//
		//   If we can't find a handler for the breakpoint, the default is to stop
		//   the target and let the user decide what to do.
		// </summary>
		bool child_breakpoint (Inferior.ChildEvent cevent, int index)
		{
			// The inferior knows about breakpoints from all threads, so if this is
			// zero, then no other thread has set this breakpoint.
			if (index == 0)
				return true;

			Breakpoint bpt = lookup_breakpoint (index);
			if ((bpt == null) || !bpt.Breaks (thread.ID))
				return false;

			if (!process.BreakpointManager.IsBreakpointEnabled (index))
				return false;

			bool remain_stopped;
			if (bpt.BreakpointHandler (inferior, out remain_stopped))
				return remain_stopped;

			TargetAddress address = inferior.CurrentFrame;
			return bpt.CheckBreakpointHit (thread, address);
		}

		bool step_over_breakpoint (bool singlestep, TargetAddress until)
		{
			int index;
			bool is_enabled;
			process.BreakpointManager.LookupBreakpoint (
				inferior.CurrentFrame, out index, out is_enabled);

			if ((index == 0) || !is_enabled)
				return false;

			Report.Debug (DebugFlags.SSE,
				      "{0} stepping over breakpoint {1} at {2} until {3}",
				      this, index, inferior.CurrentFrame, until);

			Instruction instruction = inferior.Architecture.ReadInstruction (
				inferior, inferior.CurrentFrame);

			if ((instruction == null) || !instruction.HasInstructionSize ||
			    !process.CanExecuteCode) {
				PushOperation (new OperationStepOverBreakpoint (this, index, until));
				return true;
			}

			if (instruction.InterpretInstruction (inferior)) {
				if (!singlestep)
					return false;

				byte[] nop_insn = Architecture.Opcodes.GenerateNopInstruction ();
				inferior.ExecuteInstruction (nop_insn, false);
				return true;
			}

			if (instruction.IsIpRelative) {
				PushOperation (new OperationStepOverBreakpoint (this, index, until));
				return true;
			}

			PushOperation (new OperationExecuteInstruction (this, instruction));
			return true;
		}

		void enable_extended_notification (NotificationType type)
		{
			long notifications = inferior.ReadLongInteger (extended_notifications_addr);
			notifications |= (long) type;
			inferior.WriteLongInteger (extended_notifications_addr, notifications);
		}

		void disable_extended_notification (NotificationType type)
		{
			long notifications = inferior.ReadLongInteger (extended_notifications_addr);
			notifications &= ~(long) type;
			inferior.WriteLongInteger (extended_notifications_addr, notifications);
		}

		bool throw_exception (TargetAddress stack, TargetAddress exc, TargetAddress ip)
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} throwing exception {1} at {2} while running {3}", this, exc, ip,
				      current_operation);

			if ((current_operation != null) && (current_operation.StartFrame != null) &&
			    (current_operation.StartFrame.Address == ip))
				return false;

			if (current_operation is OperationRuntimeInvoke)
				return false;

			foreach (ExceptionCatchPoint handle in exception_handlers.Values) {
				Report.Debug (DebugFlags.SSE,
					      "{0} invoking exception handler {1} for {0}",
					      this, handle.Name, exc);

				if (!handle.CheckException (process.MonoLanguage, inferior, exc))
					continue;

				Report.Debug (DebugFlags.SSE,
					      "{0} stopped on exception {1} at {2}", this, exc, ip);

				return true;
			}

			return false;
		}

		bool handle_exception (TargetAddress stack, TargetAddress exc, TargetAddress ip)
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} handling exception {1} at {2} while running {3}", this, exc, ip,
				      current_operation);

			if (current_operation == null)
				return true;

			return current_operation.HandleException (stack, exc);
		}

		// <summary>
		//   Check whether @address is inside @frame.
		// </summary>
		bool is_in_step_frame (StepFrame frame, TargetAddress address)
                {
			if (address.IsNull || frame.Start.IsNull)
				return false;

                        if ((address < frame.Start) || (address >= frame.End))
                                return false;

                        return true;
                }

		// <summary>
		//   This is called when a stepping operation is completed or something
		//   unexpected happened (received signal etc.).
		//
		//   Normally, we just compute the new StackFrame here, but we may also
		//   discover that we need to do one more stepping operation, see
		//   check_method_operation().
		// </summary>
		Operation frame_changed (TargetAddress address, Operation operation)
		{
			// Mark the current stack frame and backtrace as invalid.
			frames_invalid ();

			bool same_method = false;

			// Only do a method lookup if we actually need it.
			if ((current_method != null) &&
			    Method.IsInSameMethod (current_method, address))
				same_method = true;
			else
				current_method = Lookup (address);

			// If some clown requested a backtrace while doing the symbol lookup ....
			frames_invalid ();

			Inferior.StackFrame iframe = inferior.GetCurrentFrame ();
			registers = inferior.GetRegisters ();

			// Compute the current stack frame.
			if ((current_method != null) && current_method.HasLineNumbers) {
				SourceAddress source = current_method.LineNumberTable.Lookup (address);

				if (!same_method) {
					// If check_method_operation() returns true, it already
					// started a stepping operation, so the target is
					// currently running.
					Operation new_operation = check_method_operation (
						address, current_method, source, operation);
					if (new_operation != null)
						return new_operation;
				}

				if (source != null)
					update_current_frame (new StackFrame (
						thread, iframe.Address, iframe.StackPointer,
						iframe.FrameAddress, registers, current_method, source));
				else
					update_current_frame (new StackFrame (
						thread, iframe.Address, iframe.StackPointer,
						iframe.FrameAddress, registers, current_method));
			} else {
				if (!same_method && (current_method != null)) {
					Operation new_operation = check_method_operation (
						address, current_method, null, operation);
					if (new_operation != null)
						return new_operation;
				}

				if (current_method != null)
					update_current_frame (new StackFrame (
						thread, iframe.Address, iframe.StackPointer,
						iframe.FrameAddress, registers, current_method));
				else {
					Symbol name;
					try {
						name = SimpleLookup (address, false);
					} catch {
						name = null;
					}
					update_current_frame (new StackFrame (
						thread, iframe.Address, iframe.StackPointer,
						iframe.FrameAddress, registers, thread.NativeLanguage,
						name));
				}
			}

			return null;
		}

		// <summary>
		//   Checks whether to do a "method operation".
		//
		//   This is only used while doing a source stepping operation and ensures
		//   that we don't stop somewhere inside a method's prologue code or
		//   between two source lines.
		// </summary>
		Operation check_method_operation (TargetAddress address, Method method,
						  SourceAddress source, Operation operation)
		{
			// Do nothing if this is not a source stepping operation.
			if ((operation == null) || !operation.IsSourceOperation)
				return null;

			if (method.WrapperType != WrapperType.None)
				return new OperationWrapper (this, method, operation.Result);

			Language language = method.Module.Language;
			if (source == null)
				return null;

			if ((source.SourceOffset > 0) && (source.SourceRange > 0)) {
				// We stopped between two source lines.  This normally
				// happens when returning from a method call; in this
				// case, we need to continue stepping until we reach the
				// next source line.
				return new OperationStep (this, new StepFrame (
					address - source.SourceOffset, address + source.SourceRange,
					null, language, StepMode.SourceLine), operation.Result);
			} else if (method.HasMethodBounds && (address < method.MethodStartAddress)) {
				// Do not stop inside a method's prologue code, but stop
				// immediately behind it (on the first instruction of the
				// method's actual code).
				return new OperationStep (this, new StepFrame (
					method.StartAddress, method.MethodStartAddress, null,
					null, StepMode.Finish), operation.Result);
			}

			return null;
		}

		void frames_invalid ()
		{
			current_frame = null;
			current_backtrace = null;
			registers = null;
		}

		void update_current_frame (StackFrame new_frame)
		{
			current_frame = new_frame;
		}

		int temp_breakpoint_id = 0;
		void insert_temporary_breakpoint (TargetAddress address)
		{
			check_inferior ();
			int dr_index;

			if (temp_breakpoint_id != 0)
				throw new InternalError ("FUCK");

			temp_breakpoint_id = inferior.InsertHardwareBreakpoint (
				address, true, out dr_index);

			Report.Debug (DebugFlags.SSE, "{0} inserted temp breakpoint {1}:{2} at {3}",
				      this, temp_breakpoint_id, dr_index, address);
		}

		// <summary>
		//   Step over the next machine instruction.
		// </summary>
		void do_next_native ()
		{
			check_inferior ();
			frames_invalid ();
			TargetAddress address = inferior.CurrentFrame;

			// Check whether this is a call instruction.
			Instruction instruction = inferior.Architecture.ReadInstruction (
				inferior, address);
			if ((instruction == null) || !instruction.HasInstructionSize) {
				do_step_native ();
				return;
			}

			Report.Debug (DebugFlags.SSE, "{0} do_next_native: {1} {2}", this,
				      address, instruction.InstructionType);

			// Step one instruction unless this is a call
			if (!instruction.IsCall) {
				do_step_native ();
				return;
			}

			// Insert a temporary breakpoint immediately behind it and continue.
			address += instruction.InstructionSize;
			do_continue (address);
		}

		// <summary>
		//   Resume the target.
		// </summary>
		void do_continue ()
		{
			do_continue (TargetAddress.Null);
		}

		void do_continue (TargetAddress until)
		{
			check_inferior ();
			frames_invalid ();

			if (step_over_breakpoint (false, until))
				return;

			if (!until.IsNull)
				insert_temporary_breakpoint (until);
			inferior.Continue ();
		}

		void remove_temporary_breakpoint ()
		{
			Report.Debug (DebugFlags.SSE, "{0} remove temp breakpoint {1}",
				      this, temp_breakpoint_id);

			if (temp_breakpoint_id != 0) {
				inferior.RemoveBreakpoint (temp_breakpoint_id);
				temp_breakpoint_id = 0;
			}
		}

		void do_step_native ()
		{
			if (step_over_breakpoint (true, TargetAddress.Null))
				return;

			inferior.Step ();
		}

		protected bool CheckTrampoline (Instruction instruction, TrampolineHandler handler)
		{
			TargetAddress trampoline;
			Instruction.TrampolineType type = instruction.CheckTrampoline (
				inferior, out trampoline);
			if (type == Instruction.TrampolineType.None)
				return false;

			Report.Debug (DebugFlags.SSE,
				      "{0} found trampoline {1}:{2} at {3} while running {4}",
				      this, type, trampoline, instruction.Address, current_operation);

			if (type == Instruction.TrampolineType.NativeTrampolineStart) {
				PushOperation (new OperationNativeTrampoline (this, trampoline, handler));
				return true;
			} else if (type == Instruction.TrampolineType.NativeTrampoline) {
				Method method = Lookup (trampoline);
				if (!MethodHasSource (method))
					do_next_native ();
				else
					do_continue (trampoline);
				return true;
			} else if (type == Instruction.TrampolineType.MonoTrampoline) {
				PushOperation (new OperationMonoTrampoline (
					this, instruction, trampoline, handler));
				return true;
			} else if (type == Instruction.TrampolineType.DelegateInvoke) {
				PushOperation (new OperationDelegateInvoke (this));
				return true;
			}

			return false;
		}

		protected bool MethodHasSource (Method method)
		{
			if ((method == null) || !method.HasLineNumbers || !method.HasMethodBounds)
				return false;

			if (method.WrapperType == WrapperType.ManagedToNative) {
				DebuggerConfiguration config = process.Session.Config;
				ModuleGroup native_group = config.GetModuleGroup ("native");
				if (!native_group.StepInto)
					return false;
			}

			if (current_method != null) {
				if ((method.Module != current_method.Module) && !method.Module.StepInto)
					return false;
			} else {
				if (!method.Module.StepInto)
					return false;
			}

			LineNumberTable lnt = method.LineNumberTable;
			if (lnt == null)
				return false;

			SourceAddress addr = lnt.Lookup (method.MethodStartAddress);
			if (addr == null) {
				Report.Error ("OOOOPS - No source for method: {0}", method);
				lnt.DumpLineNumbers ();
				return false;
			}

			return true;
		}

		// <summary>
		//   Create a step frame to step until the next source line.
		// </summary>
		StepFrame CreateStepFrame ()
		{
			check_inferior ();
			StackFrame frame = current_frame;
			Language language = (frame.Method != null) ? frame.Method.Module.Language : null;

			if (frame.SourceAddress == null)
				return new StepFrame (language, StepMode.SingleInstruction);

			// The current source line started at the current address minus
			// SourceOffset; the next source line will start at the current
			// address plus SourceRange.

			int offset = frame.SourceAddress.SourceOffset;
			int range = frame.SourceAddress.SourceRange;

			TargetAddress start = frame.TargetAddress - offset;
			TargetAddress end = frame.TargetAddress + range;

			return new StepFrame (start, end, frame, language, StepMode.StepFrame);
		}

		// <summary>
		//   Create a step frame for a native stepping operation.
		// </summary>
		StepFrame CreateStepFrame (StepMode mode)
		{
			check_inferior ();
			Language language = (current_method != null) ?
				current_method.Module.Language : null;

			return new StepFrame (language, mode);
		}

		StackData save_stack (long id)
		{
			//
			// Save current state.
			//
			StackData stack_data = new StackData (
				id, current_method, inferior.CurrentFrame, current_frame,
				current_backtrace, registers);

			current_method = null;
			current_frame = null;
			current_backtrace = null;
			registers = null;

			return stack_data;
		}

		void restore_stack (StackData stack)
		{
			if (inferior.CurrentFrame != stack.Address) {
				Report.Debug (DebugFlags.SSE,
					      "{0} discarding saved stack: stopped " +
					      "at {1}, but recorded {2}", this,
					      inferior.CurrentFrame, stack.Frame.TargetAddress);
				frame_changed (inferior.CurrentFrame, null);
				return;
			}

			current_method = stack.Method;
			current_frame = stack.Frame;
			current_backtrace = stack.Backtrace;
			registers = stack.Registers;
		}

		// <summary>
		//   Interrupt any currently running stepping operation, but don't send
		//   any notifications to the caller.  The currently running operation is
		//   automatically resumed when ReleaseThreadLock() is called.
		// </summary>
		internal override void AcquireThreadLock ()
		{
			Report.Debug (DebugFlags.Threads,
				      "{0} acquiring thread lock: {1} {2}",
				      this, engine_stopped, current_operation);

			has_thread_lock = true;
			stopped = inferior.Stop (out stop_event);

			Report.Debug (DebugFlags.Threads,
				      "{0} acquiring thread lock #1: {1} {2}",
				      this, stopped, stop_event);

			if ((stop_event != null) &&
			    ((stop_event.Type == Inferior.ChildEventType.CHILD_EXITED) ||
			     ((stop_event.Type == Inferior.ChildEventType.CHILD_SIGNALED))))
				return;

			TargetAddress new_rsp = inferior.PushRegisters ();

			Report.Debug (DebugFlags.Threads,
				      "{0} acquired thread lock: {1} {2} {3} {4} {5}",
				      this, stopped, stop_event, EndStackAddress,
				      new_rsp, inferior.CurrentFrame);

			if (!EndStackAddress.IsNull)
				inferior.WriteAddress (EndStackAddress, new_rsp);
		}

		internal override void ReleaseThreadLock ()
		{
			Report.Debug (DebugFlags.Threads,
				      "{0} releasing thread lock: {1} {2} {3} {4}",
				      this, stopped, stop_event, inferior.CurrentFrame,
				      current_operation);

			if (stop_event != null)
				manager.AddPendingEvent (this, stop_event);

			has_thread_lock = false;

			inferior.PopRegisters ();
		}

		internal void ReleaseThreadLock (Inferior.ChildEvent cevent)
		{
			// The target stopped before we were able to send the SIGSTOP,
			// but we haven't processed this event yet.
			if ((cevent.Type == Inferior.ChildEventType.CHILD_STOPPED) &&
			    (cevent.Argument == 0)) {
				do_continue ();
				return;
			}

			if (cevent.Type == Inferior.ChildEventType.CHILD_INTERRUPTED) {
				do_continue ();
				return;
			}

#if FIXME
			bool resume_target;
			if (manager.HandleChildEvent (this, inferior, ref cevent, out resume_target)) {
				if (resume_target)
					inferior.Continue ();
				return;
			}
#endif

			ProcessEvent (cevent);
		}

		internal override void ReleaseThreadLockDone ()
		{
			if (pending_operation == null)
				return;

			Report.Debug (DebugFlags.Threads, "{0} starting pending operation {1}", this,
				      pending_operation);

			current_operation = pending_operation;
			pending_operation = null;
			ExecuteOperation (current_operation);
		}

		void inferior_output_handler (bool is_stderr, string line)
		{
			manager.Debugger.OnInferiorOutput (is_stderr, line);
		}

		internal bool OnModuleLoaded ()
		{
			Inferior.StackFrame iframe = inferior.GetCurrentFrame ();
			Registers registers = inferior.GetRegisters ();

			StackFrame main_frame;
			if (process.MonoManager != null) {
				MonoLanguageBackend mono = process.MonoLanguage;

				MonoFunctionType main = mono.MainMethod;

				MethodSource source = main.MonoClass.File.GetMethodByToken (main.Token);
				if (source != null) {
					SourceLocation location = new SourceLocation (source);

					main_frame = new StackFrame (
						thread, iframe.Address, iframe.StackPointer,
						iframe.FrameAddress, registers, main, location);
				} else {
					main_frame = new StackFrame (
						thread, iframe.Address, iframe.StackPointer,
						iframe.FrameAddress, registers);
				}
				update_current_frame (main_frame);
			} else {
				Method method = Lookup (inferior.MainMethodAddress);

				main_frame = new StackFrame (
					thread, iframe.Address, iframe.StackPointer,
					iframe.FrameAddress, registers, method);
				update_current_frame (main_frame);
			}

			Queue pending = new Queue ();
			foreach (Event e in process.Session.Events) {
				Breakpoint breakpoint = e as Breakpoint;
				if (breakpoint == null)
					continue;

				if (!e.IsEnabled || e.IsActivated)
					continue;

				try {
					BreakpointHandle handle = breakpoint.Resolve (thread, main_frame);
					if (handle == null)
						continue;

					FunctionBreakpointHandle fh = handle as FunctionBreakpointHandle;
					if (fh == null) {
						handle.Insert (thread);
						continue;
					}

					pending.Enqueue (fh);
				} catch (TargetException ex) {
					Report.Error ("Cannot insert breakpoint {0}: {1}",
						      e.Index, ex.Message);
				} catch (Exception ex) {
					Report.Error ("Cannot insert breakpoint {0}: {1}",
						      e.Index, ex.Message);
				}
			}

			if (pending.Count == 0)
				return false;

			PushOperation (new OperationActivateBreakpoints (this, pending));
			return true;
		}

		public override string ToString ()
		{
			return String.Format ("SSE ({0}:{1}:{2:x})", ID, PID, TID);
		}

#region SSE Commands

		public override void StepInstruction (CommandResult result)
		{
			StartOperation (new OperationStep (this, StepMode.SingleInstruction, result));
		}

		public override void StepNativeInstruction (CommandResult result)
		{
			StartOperation (new OperationStep (this, StepMode.NativeInstruction, result));
		}

		public override void NextInstruction (CommandResult result)
		{
			StartOperation (new OperationStep (this, StepMode.NextInstruction, result));
		}

		public override void StepLine (CommandResult result)
		{
			StartOperation (new OperationStep (this, StepMode.SourceLine, result));
		}

		public override void NextLine (CommandResult result)
		{
			StartOperation (new OperationStep (this, StepMode.NextLine, result));
		}

		public override void Finish (bool native, CommandResult result)
		{
			StartOperation (new OperationFinish (this, native, result));
		}

		public override void Continue (TargetAddress until, CommandResult result)
		{
			StartOperation (new OperationRun (this, until, false, result));
		}

		public override void Background (TargetAddress until, CommandResult result)
		{
			StartOperation (new OperationRun (this, until, true, result));
		}

		public override void RuntimeInvoke (TargetFunctionType function,
						    TargetClassObject object_argument,
						    TargetObject[] param_objects,
						    bool is_virtual, bool debug,
						    RuntimeInvokeResult result)
		{
			StartOperation (new OperationRuntimeInvoke (
				this, function, object_argument, param_objects,
				is_virtual, debug, result));
		}

		public override CommandResult CallMethod (TargetAddress method, long arg1, long arg2,
							  long arg3, string string_argument)
		{
			return StartOperation (new OperationCallMethod (
				this, method, arg1, arg2, arg3, string_argument));
		}

		public override CommandResult CallMethod (TargetAddress method, long arg1, long arg2)
		{
			return StartOperation (new OperationCallMethod (this, method, arg1, arg2));
		}

		public override CommandResult Return (bool run_finally)
		{
			return (CommandResult) SendCommand (delegate {
				if (!engine_stopped) {
					Report.Debug (DebugFlags.Wait,
						      "{0} not stopped", this);
					throw new TargetException (TargetError.NotStopped);
				}

				if (current_frame == null)
					throw new TargetException (TargetError.NoStack);

				process.UpdateSymbolTable (inferior);

				Backtrace bt = new Backtrace (current_frame);
				bt.GetBacktrace (this, inferior, Backtrace.Mode.Native,
						 TargetAddress.Null, 2);

				if (bt.Count < 2)
					throw new TargetException (TargetError.NoStack);

				StackFrame parent_frame = bt.Frames [1];
				if (parent_frame == null)
					return null;

				if (!process.IsManagedApplication || !run_finally) {
					inferior.AbortInvoke (parent_frame.StackPointer);
					inferior.SetRegisters (parent_frame.Registers);
					frame_changed (inferior.CurrentFrame, null);
					TargetEventArgs args = new TargetEventArgs (
						TargetEventType.TargetStopped, 0, current_frame);
					manager.Debugger.SendTargetEvent (this, args);
					return null;
				}

				MonoLanguageBackend language = process.MonoLanguage;
				return StartOperation (new OperationReturn (this, language, parent_frame));
			});
		}

		public override CommandResult AbortInvocation ()
		{
			return (CommandResult) SendCommand (delegate {
				GetBacktrace (Backtrace.Mode.Native, -1);
				if (current_backtrace == null)
					throw new TargetException (TargetError.NoStack);

				if (!process.IsManagedApplication)
					throw new InvalidOperationException ();

				return StartOperation (new OperationAbortInvocation (
					this, current_backtrace));
			});
		}

		public override Backtrace GetBacktrace (Backtrace.Mode mode, int max_frames)
		{
			return (Backtrace) SendCommand (delegate {
				if (!engine_stopped) {
					Report.Debug (DebugFlags.Wait,
						      "{0} not stopped", this);
					throw new TargetException (TargetError.NotStopped);
				}

				process.UpdateSymbolTable (inferior);

				if (current_frame == null)
					throw new TargetException (TargetError.NoStack);

				current_backtrace = new Backtrace (current_frame);

				current_backtrace.GetBacktrace (
					this, inferior, mode, TargetAddress.Null, max_frames);

				return current_backtrace;
			});
		}

		public override Registers GetRegisters ()
		{
			return (Registers) SendCommand (delegate {
				registers = inferior.GetRegisters ();
				return registers;
			});
		}

		public override void SetRegisters (Registers registers)
		{
			if (!registers.FromCurrentFrame)
				throw new InvalidOperationException ();

			this.registers = registers;
			SendCommand (delegate {
				inferior.SetRegisters (registers);
				return registers;
			});
		}

		internal override void InsertBreakpoint (BreakpointHandle handle,
							 TargetAddress address, int domain)
		{
			SendCommand (delegate {
				process.BreakpointManager.InsertBreakpoint (
					inferior, handle, address, domain);
				return null;
			});
		}

		internal override void RemoveBreakpoint (BreakpointHandle handle)
		{
			SendCommand (delegate {
				process.BreakpointManager.RemoveBreakpoint (inferior, handle);
				return null;
			});
		}

		static int next_event_index = 0;
		public override int AddEventHandler (Event handle)
		{
			if (handle.Type != EventType.CatchException)
				throw new InternalError ();

			int index = ++next_event_index;
			exception_handlers.Add (index, handle);
			return index;
		}

		public override void RemoveEventHandler (int index)
		{
			exception_handlers.Remove (index);
		}

		public override int GetInstructionSize (TargetAddress address)
		{
			return (int) SendCommand (delegate {
				return Architecture.Disassembler.GetInstructionSize (inferior, address);
			});
		}

		public override AssemblerLine DisassembleInstruction (Method method, TargetAddress address)
		{
			return (AssemblerLine) SendCommand (delegate {
				return Architecture.Disassembler.DisassembleInstruction (
					inferior, method, address);
			});
		}

		public override AssemblerMethod DisassembleMethod (Method method)
		{
			return (AssemblerMethod) SendCommand (delegate {
				return Architecture.Disassembler.DisassembleMethod (inferior, method);
			});
		}

		public override byte[] ReadBuffer (TargetAddress address, int size)
		{
			return (byte[]) SendCommand (delegate {
				return inferior.ReadBuffer (address, size);
			});
		}

		public override TargetBlob ReadMemory (TargetAddress address, int size)
		{
			return new TargetBlob (ReadBuffer (address, size), TargetMemoryInfo);
		}

		public override byte ReadByte (TargetAddress address)
		{
			return (byte) SendCommand (delegate {
				return inferior.ReadByte (address);
			});
		}

		public override int ReadInteger (TargetAddress address)
		{
			return (int) SendCommand (delegate {
				return inferior.ReadInteger (address);
			});
		}

		public override long ReadLongInteger (TargetAddress address)
		{
			return (long) SendCommand (delegate {
				return inferior.ReadLongInteger (address);
			});
		}

		public override TargetAddress ReadAddress (TargetAddress address)
		{
			return (TargetAddress) SendCommand (delegate {
				return inferior.ReadAddress (address);
			});
		}

		public override string ReadString (TargetAddress address)
		{
			return (string) SendCommand (delegate {
				return inferior.ReadString (address);
			});
		}

		internal override Registers GetCallbackFrame (TargetAddress stack_pointer,
							      bool exact_match)
		{
			return (Registers) SendCommand (delegate {
				return inferior.GetCallbackFrame (stack_pointer, exact_match);
			});
		}

		public override void WriteBuffer (TargetAddress address, byte[] buffer)
		{
			SendCommand (delegate {
				inferior.WriteBuffer (address, buffer);
				return null;
			});
		}

		public override void WriteByte (TargetAddress address, byte value)
		{
			SendCommand (delegate {
				inferior.WriteByte (address, value);
				return null;
			});
		}

		public override void WriteInteger (TargetAddress address, int value)
		{
			SendCommand (delegate {
				inferior.WriteInteger (address, value);
				return null;
			});
		}

		public override void WriteLongInteger (TargetAddress address, long value)
		{
			SendCommand (delegate {
				inferior.WriteLongInteger (address, value);
				return null;
			});
		}

		public override void WriteAddress (TargetAddress address, TargetAddress value)
		{
			SendCommand (delegate {
				inferior.WriteAddress (address, value);
				return null;
			});
		}

		public override bool CanWrite {
			get { return true; }
		}

		public override string PrintObject (Style style, TargetObject obj,
						    DisplayFormat format)
		{
			return (string) SendCommand (delegate {
				return style.FormatObject (thread, obj, format);
			});
		}

		public override string PrintType (Style style, TargetType type)
		{
			return (string) SendCommand (delegate {
				return style.FormatType (thread, type);
			});
		}

		internal override object Invoke (TargetAccessDelegate func, object data)
		{
			return SendCommand (delegate {
				return func (thread, data);
			});
		}
#endregion

#region IDisposable implementation
		protected override void DoDispose ()
		{
			if (inferior != null) {
				inferior.Dispose ();
				inferior = null;
			}

			base.DoDispose ();
		}
#endregion

		protected Method current_method;
		protected StackFrame current_frame;
		protected Backtrace current_backtrace;
		protected Registers registers;

		bool stopped;
		Inferior.ChildEvent stop_event;
		Operation current_operation;
		Operation pending_operation;

		Inferior inferior;
		Disassembler disassembler;
		ProcessStart start;
		Hashtable exception_handlers;
		bool engine_stopped;
		bool stop_requested;
		bool has_thread_lock;
		bool is_main, reached_main;
		bool killed, dead;
		long tid;
		int pid;

		int stepping_over_breakpoint;

		TargetEventArgs last_target_event;

		TargetAddress lmf_address = TargetAddress.Null;
		TargetAddress end_stack_address = TargetAddress.Null;
		TargetAddress extended_notifications_addr = TargetAddress.Null;

#region Nested SSE classes
		protected sealed class StackData : DebuggerMarshalByRefObject
		{
			public readonly long ID;
			public readonly Method Method;
			public readonly TargetAddress Address;
			public readonly StackFrame Frame;
			public readonly Backtrace Backtrace;
			public readonly Registers Registers;

			public StackData (long id, Method method, TargetAddress address,
					  StackFrame frame, Backtrace backtrace,
					  Registers registers)
			{
				this.ID = id;
				this.Method = method;
				this.Address = address;
				this.Frame = frame;
				this.Backtrace = backtrace;
				this.Registers = registers;
			}
		}
#endregion

#region SSE Operations
	protected abstract class Operation {
		protected enum EventResult
		{
			Running,
			Completed,
			CompletedCallback,
			AskParent,
			ResumeOperation
		}

		public abstract bool IsSourceOperation {
			get;
		}

		protected bool HasChild {
			get { return child != null; }
		}

		protected readonly SingleSteppingEngine sse;
		protected readonly Inferior inferior;

		public readonly CommandResult Result;
		public Inferior.StackFrame StartFrame;
		public int PendingBreakpoint = -1;

		protected Operation (SingleSteppingEngine sse, CommandResult result)
		{
			this.sse = sse;
			this.inferior = sse.inferior;

			if (result != null)
				this.Result = result;
			else
				this.Result = new SimpleCommandResult (this);
		}

		public virtual void Execute ()
		{
			StartFrame = inferior.GetCurrentFrame (true);
			Report.Debug (DebugFlags.SSE, "{0} executing {1} at {2}",
				      sse, this, StartFrame);
			DoExecute ();
		}

		protected abstract void DoExecute ();

		protected virtual void Abort ()
		{
			sse.Stop ();
		}

		protected virtual bool ResumeOperation ()
		{
			return false;
		}

		Operation child;

		public void PushOperation (Operation op)
		{
			if (child != null)
				child.PushOperation (op);
			else
				child = op;
		}

		public virtual bool ProcessEvent (Inferior.ChildEvent cevent,
						  out TargetEventArgs args, out bool send_result)
		{
			EventResult result = ProcessEvent (cevent, out args);

			switch (result) {
			case EventResult.Running:
				send_result = false;
				return false;

			case EventResult.Completed:
				send_result = true;
				return true;

			case EventResult.CompletedCallback:
				send_result = false;
				return true;

			default:
				throw new InternalError ("FUCK: {0} {1}", this, result);
			}
		}

		protected virtual EventResult ProcessEvent (Inferior.ChildEvent cevent,
							    out TargetEventArgs args)
		{
			if (child != null) {
				EventResult result = child.ProcessEvent (cevent, out args);

				if ((result != EventResult.AskParent) &&
				    (result != EventResult.ResumeOperation))
					return result;

				Operation old_child = child;
				child = null;

				if ((result == EventResult.ResumeOperation) && ResumeOperation ()) {
					args = null;
					return EventResult.Running;
				}

				Report.Debug (DebugFlags.EventLoop,
					      "{0} resending event {1} from {2} to {3}",
					      sse, cevent, old_child, this);
			}

			return DoProcessEvent (cevent, out args);
		}

		protected abstract EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args);

		public virtual bool HandleException (TargetAddress stack, TargetAddress exc)
		{
			return true;
		}

		protected virtual string MyToString ()
		{
			return "";
		}

		public override string ToString ()
		{
			if (child == null)
				return String.Format ("{0} ({1})", GetType ().Name, MyToString ());
			else
				return String.Format ("{0}:{1}", GetType ().Name, child);
		}

		protected class SimpleCommandResult : CommandResult
		{
			Operation operation;
			ManualResetEvent completed_event = new ManualResetEvent (false);

			internal SimpleCommandResult (Operation operation)
			{
				this.operation = operation;
			}

			public override WaitHandle CompletedEvent {
				get { return completed_event; }
			}

			public override void Abort ()
			{
				operation.Abort ();
			}

			public override void Completed ()
			{
				completed_event.Set ();
			}
		}
	}

	protected class OperationStart : Operation
	{
		public OperationStart (SingleSteppingEngine sse, CommandResult result)
			: base (sse, result)
		{ }

		public override bool IsSourceOperation {
			get { return true; }
		}

		protected override void DoExecute ()
		{ }

		bool initialized;
		bool has_lmf;

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} start: {1} {2} {3} {4}", sse, initialized,
				      cevent, sse.ProcessServant.IsAttached,
				      inferior.CurrentFrame);

			args = null;
			if ((cevent.Type != Inferior.ChildEventType.CHILD_STOPPED) &&
			    (cevent.Type != Inferior.ChildEventType.CHILD_CALLBACK))
				return EventResult.Completed;

			if (sse.Architecture.IsSyscallInstruction (inferior, inferior.CurrentFrame)) {
				inferior.Step ();
				return EventResult.Running;
			}

			if (sse.ProcessServant.MonoManager != null) {
				if (sse.ProcessServant.IsAttached) {
					sse.PushOperation (new OperationAttach (sse, null));
					return EventResult.Running;
				}

				if (!initialized) {
					initialized = true;
					inferior.Continue ();
					return EventResult.Running;
				}

				if (!has_lmf) {
					has_lmf = true;
					sse.PushOperation (new OperationGetLMFAddr (sse, null));
					return EventResult.Running;
				}
			} else {
				if (sse.OnModuleLoaded ())
					return EventResult.Running;
			}

			if (sse.ProcessServant.IsAttached)
				return EventResult.Completed;

			Report.Debug (DebugFlags.SSE,
				      "{0} start #1: {1} {2} {3}", sse, cevent,
				      sse.ProcessServant.IsAttached, inferior.MainMethodAddress);
			sse.PushOperation (new OperationRun (sse, true, Result));
			return EventResult.Running;
		}

	}

	protected class OperationActivateBreakpoints : Operation
	{
		MonoLanguageBackend language;

		public OperationActivateBreakpoints (SingleSteppingEngine sse, Queue pending)
			: base (sse, null)
		{
			this.pending_events = pending;
			this.language = sse.process.MonoLanguage;
		}

		protected override void DoExecute ()
		{
			do_execute ();
		}

		public override bool IsSourceOperation {
			get { return false; }
		}

		Queue pending_events;
		bool completed;

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			args = null;

			Report.Debug (DebugFlags.SSE,
				      "{0} activate breakpoints: {1}", sse, completed);

			while (!completed) {
				if (do_execute ())
					return EventResult.Running;

				Report.Debug (DebugFlags.SSE,
					      "{0} activate breakpoints done - continue", sse);

				return EventResult.ResumeOperation;

				sse.do_continue ();
				return EventResult.Running;
			}

			Report.Debug (DebugFlags.SSE,
				      "{0} activate breakpoints completed", sse);
			return EventResult.AskParent;
		}

		bool do_execute ()
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} activate breakpoints execute: {1} {2}", sse,
				      inferior.CurrentFrame, pending_events.Count);

			if (pending_events.Count == 0) {
				completed = true;
				return false;
			}

			FunctionBreakpointHandle handle =
				(FunctionBreakpointHandle) pending_events.Dequeue ();

			Report.Debug (DebugFlags.SSE,
				      "{0} activate breakpoints: {1}", sse, handle);

			sse.PushOperation (new OperationInsertBreakpoint (sse, handle));
			return true;
		}
	}

	protected class OperationInsertBreakpoint : OperationCallback
	{
		public readonly FunctionBreakpointHandle Handle;

		public OperationInsertBreakpoint (SingleSteppingEngine sse,
						  FunctionBreakpointHandle handle)
			: base (sse, null)
		{
			this.Handle = handle;
		}

		protected override void DoExecute ()
		{
			MonoDebuggerInfo info = sse.ProcessServant.MonoManager.MonoDebuggerInfo;
			MonoLanguageBackend mono = sse.process.MonoLanguage;

			MonoFunctionType func = (MonoFunctionType) Handle.Function;
			TargetAddress image = func.MonoClass.File.MonoImage;
			int index = MonoLanguageBackend.GetUniqueID ();

			mono.RegisterMethodLoadHandler (index, Handle.MethodLoaded);

			inferior.CallMethod (
				info.InsertSourceBreakpoint, image.Address,
				func.Token, index, func.MonoClass.Name, ID);
		}

		protected override EventResult CallbackCompleted (long data1, long data2)
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} insert breakpoint done: {1:x} {2:x}",
				      sse, data1, data2);

			return EventResult.AskParent;
		}
	}

	protected class OperationInitialize : Operation
	{
		public OperationInitialize (SingleSteppingEngine sse, CommandResult result)
			: base (sse, result)
		{ }

		public override bool IsSourceOperation {
			get { return true; }
		}

		protected override void DoExecute ()
		{ }

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} initialize ({1})", sse,
				      DebuggerWaitHandle.CurrentThread);

			args = null;
			return EventResult.Completed;
		}
	}

	protected class OperationAttach : OperationCallback
	{
		public OperationAttach (SingleSteppingEngine sse, CommandResult result)
			: base (sse, result)
		{ }

		public override bool IsSourceOperation {
			get { return false; }
		}

		protected override void DoExecute ()
		{
			MonoDebuggerInfo info = sse.ProcessServant.MonoManager.MonoDebuggerInfo;
			inferior.CallMethod (info.Attach, 0, 0, ID);
		}

		protected override EventResult CallbackCompleted (long data1, long data2)
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} attach done: {1:x} {2:x} {3}",
				      sse, data1, data2, Result);

			inferior.InitializeModules ();

			sse.PushOperation (new OperationGetLMFAddr (sse, null));
			return EventResult.Running;
		}
	}

	protected class OperationInitAfterFork : Operation
	{
		public OperationInitAfterFork (SingleSteppingEngine sse)
			: base (sse, null)
		{ }

		public override bool IsSourceOperation {
			get { return false; }
		}

		protected override void DoExecute ()
		{ }

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} init after fork ({1})", sse,
				      DebuggerWaitHandle.CurrentThread);

			sse.ProcessServant.BreakpointManager.InitializeAfterFork (inferior);

			args = null;
			return EventResult.AskParent;
		}
	}

	protected class OperationGetLMFAddr : OperationCallback
	{
		public OperationGetLMFAddr (SingleSteppingEngine sse, CommandResult result)
			: base (sse, result)
		{ }

		public override bool IsSourceOperation {
			get { return true; }
		}

		protected override void DoExecute ()
		{
			MonoDebuggerInfo info = sse.ProcessServant.MonoManager.MonoDebuggerInfo;
			inferior.CallMethod (info.GetLMFAddress, 0, 0, ID);
		}

		protected override EventResult CallbackCompleted (long data1, long data2)
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} get lmf: {1:x} {2:x} {3}",
				      sse, data1, data2, Result);

			RestoreStack ();
			sse.lmf_address = new TargetAddress (inferior.AddressDomain, data1);
			return EventResult.AskParent;
		}
	}

	protected class OperationDetach : OperationCallback
	{
		public OperationDetach (SingleSteppingEngine sse)
			: base (sse)
		{ }

		public override bool IsSourceOperation {
			get { return false; }
		}

		protected override void DoExecute ()
		{
			MonoDebuggerInfo info = sse.ProcessServant.MonoManager.MonoDebuggerInfo;
			inferior.CallMethod (info.Detach, 0, 0, ID);
		}

		protected override EventResult CallbackCompleted (long data1, long data2)
		{
			Report.Debug (DebugFlags.SSE, "{0} detach done: {1}", sse, Result);

			sse.DoDetach ();
			return EventResult.CompletedCallback;
		}
	}

	protected class OperationStepOverBreakpoint : Operation
	{
		TargetAddress until;
		public readonly int Index;
		bool has_thread_lock;

		public OperationStepOverBreakpoint (SingleSteppingEngine sse, int index,
						    TargetAddress until)
			: base (sse, null)
		{
			this.Index = index;
			this.until = until;
		}

		public override bool IsSourceOperation {
			get { return false; }
		}

		protected override void DoExecute ()
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} stepping over breakpoint: {1}", sse, until);

			sse.process.AcquireGlobalThreadLock (sse);
			inferior.DisableBreakpoint (Index);

			has_thread_lock = true;

			Report.Debug (DebugFlags.SSE,
				      "{0} stepping over breakpoint {1} at {2} until {3} ({4})",
				      sse, Index, inferior.CurrentFrame, until, sse.current_method);

			inferior.Step ();
		}

		bool ReleaseThreadLock (Inferior.ChildEvent cevent)
		{
			if (!has_thread_lock)
				return true;

			Report.Debug (DebugFlags.SSE,
				      "{0} releasing thread lock at {1}",
				      sse, inferior.CurrentFrame);

			inferior.EnableBreakpoint (Index);
			sse.process.ReleaseGlobalThreadLock (sse);

			Report.Debug (DebugFlags.SSE,
				      "{0} done releasing thread lock at {1} - {2}",
				      sse, inferior.CurrentFrame, sse.has_thread_lock);

			has_thread_lock = false;

			if (!sse.has_thread_lock)
				return true;

			sse.stopped = true;
			sse.stop_event = cevent;
			return false;
		}

		protected override EventResult ProcessEvent (Inferior.ChildEvent cevent,
							     out TargetEventArgs args)
		{
			if (((cevent.Type == Inferior.ChildEventType.CHILD_STOPPED) &&
			     (cevent.Argument == 0)) ||
			    (cevent.Type != Inferior.ChildEventType.CHILD_CALLBACK)) {
				if (!ReleaseThreadLock (cevent)) {
					args = null;
					return EventResult.Running;
				}
			}
			return base.ProcessEvent (cevent, out args);
		}

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} stepped over breakpoint {1} at {2}: {3} {4}",
				      sse, Index, inferior.CurrentFrame, cevent, until);

			if ((cevent.Type == Inferior.ChildEventType.CHILD_HIT_BREAKPOINT) &&
			    (cevent.Argument != Index)) {
				args = null;
				return EventResult.Completed;
			}

			if (!until.IsNull) {
				sse.do_continue (until);

				args = null;
				until = TargetAddress.Null;
				return EventResult.Running;
			}

			args = null;
			return EventResult.ResumeOperation;
		}
	}

	protected class OperationExecuteInstruction : Operation
	{
		public readonly Instruction Instruction;

		public OperationExecuteInstruction (SingleSteppingEngine sse, Instruction insn)
			: base (sse, null)
		{
			this.Instruction = insn;
		}

		public override bool IsSourceOperation {
			get { return false; }
		}

		protected override void DoExecute ()
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} executing instruction: {1}", sse, Instruction);

			inferior.ExecuteInstruction (Instruction.Code, true);
		}

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} executed instruction {1} at {2}: {3}",
				      sse, Instruction, inferior.CurrentFrame, cevent);

			args = null;
			return EventResult.ResumeOperation;
		}
	}

	protected abstract class OperationStepBase : Operation
	{
		protected OperationStepBase (SingleSteppingEngine sse, CommandResult result)
			: base (sse, result)
		{ }

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			args = null;
			if (DoProcessEvent ())
				return EventResult.Completed;
			else
				return EventResult.Running;
		}

		protected abstract bool DoProcessEvent ();

		protected abstract bool TrampolineHandler (Method method);
	}

	protected class OperationStep : OperationStepBase
	{
		public StepMode StepMode;
		public StepFrame StepFrame;

		public OperationStep (SingleSteppingEngine sse, StepMode mode, CommandResult result)
			: base (sse, result)
		{
			this.StepMode = mode;
		}

		public OperationStep (SingleSteppingEngine sse, StepFrame frame, CommandResult result)
			: base (sse, result)
		{
			this.StepFrame = frame;
			this.StepMode = frame.Mode;
		}

		public override bool IsSourceOperation {
			get {
				return (StepMode == StepMode.SourceLine) ||
					(StepMode == StepMode.NextLine);
			}
		}

		protected override void DoExecute ()
		{
			switch (StepMode) {
			case StepMode.NativeInstruction:
				sse.do_step_native ();
				break;

			case StepMode.NextInstruction:
				sse.do_next_native ();
				break;

			case StepMode.SourceLine:
				if (StepFrame == null)
					StepFrame = sse.CreateStepFrame ();
				if (StepFrame == null)
					sse.do_step_native ();
				else
					Step (true);
				break;

			case StepMode.NextLine:
				// We cannot just set a breakpoint on the next line
				// since we do not know which way the program's
				// control flow will go; ie. there may be a jump
				// instruction before reaching the next line.
				StepFrame frame = sse.CreateStepFrame ();
				if (frame == null)
					sse.do_next_native ();
				else {
					StepFrame = new StepFrame (
						frame.Start, frame.End, frame.StackFrame,
						null, StepMode.Finish);
					Step (true);
				}
				break;

			case StepMode.SingleInstruction:
				StepFrame = sse.CreateStepFrame (StepMode.SingleInstruction);
				Step (true);
				break;

			case StepMode.Finish:
				Step (true);
				break;

			default:
				throw new InvalidOperationException ();
			}
		}

		protected override bool ResumeOperation ()
		{
			Report.Debug (DebugFlags.SSE, "{0} resuming operation {1}", sse, this);

			if (sse.temp_breakpoint_id != 0) {
				inferior.Continue ();
				return true;
			}

			return !Step (false);
		}

		public override bool HandleException (TargetAddress stack, TargetAddress exc)
		{
			if ((StepMode != StepMode.SourceLine) && (StepMode != StepMode.NextLine) &&
			    (StepMode != StepMode.StepFrame))
				return true;

			/*
			 * If we don't have a StepFrame or if the StepFrame doesn't have a
			 * SimpleStackFrame, we're doing something like instruction stepping -
			 * always stop in this case.
			 */
			if ((StepFrame == null) || (StepFrame.StackFrame == null))
				return true;

			StackFrame oframe = StepFrame.StackFrame;

			Report.Debug (DebugFlags.SSE,
				      "{0} handling exception: {1} {2} - {3} {4} - {5}", sse,
				      StepFrame, oframe, stack, oframe.StackPointer,
				      stack < oframe.StackPointer);

			if (stack < oframe.StackPointer)
				return false;

			return true;
		}

		protected override bool TrampolineHandler (Method method)
		{
			if (StepMode == StepMode.SingleInstruction)
				return true;

			if (method == null)
				return false;

			if (method.WrapperType == WrapperType.DelegateInvoke)
				return true;

			if (StepMode == StepMode.SourceLine)
				return sse.MethodHasSource (method);

			return true;
		}

		protected bool Step (bool first)
		{
			if (StepFrame == null)
				return true;

			TargetAddress current_frame = inferior.CurrentFrame;
			bool in_frame = sse.is_in_step_frame (StepFrame, current_frame);
			Report.Debug (DebugFlags.SSE, "{0} stepping at {1} in {2} ({3}in frame)",
				      sse, current_frame, StepFrame, !in_frame ? "not " : "");

			if (!first && !in_frame)
				return true;

			/*
			 * If this is not a call instruction, continue stepping until we leave
			 * the specified step frame.
			 */
			Instruction instruction = inferior.Architecture.ReadInstruction (
				inferior, current_frame);
			if ((instruction == null) || !instruction.IsCall) {
				sse.do_step_native ();
				return false;
			}

			if (!instruction.HasInstructionSize) {
				/* Ooops, we don't know anything about this instruction */
				sse.do_step_native ();
				return false;
			}

			TargetAddress call_target = instruction.GetEffectiveAddress (inferior);

			if ((sse.current_method != null) && (sse.current_method.HasMethodBounds) &&
			    !call_target.IsNull &&
			    (call_target >= sse.current_method.MethodStartAddress) &&
			    (call_target < sse.current_method.MethodEndAddress)) {
				/* Intra-method call (we stay outside the prologue/epilogue code,
				 * so this also can't be a recursive call). */
				sse.do_step_native ();
				return false;
			}

			/*
			 * In StepMode.Finish, always step over all methods.
			 */
			if ((StepMode == StepMode.Finish) || (StepMode == StepMode.NextLine)) {
				sse.do_next_native ();
				return false;
			}

			if (sse.CheckTrampoline (instruction, TrampolineHandler))
				return false;

			/*
			 * When StepMode.SingleInstruction was requested, enter the method
			 * no matter whether it's a system function or not.
			 */
			if (StepMode == StepMode.SingleInstruction) {
				sse.do_step_native ();
				return false;
			}

			/*
			 * Try to find out whether this is a system function by doing a symbol lookup.
			 * If it can't be found in the symbol tables, assume it's a system function
			 * and step over it.
			 */
			Method method = sse.Lookup (call_target);

			/*
			 * If this is a PInvoke/icall wrapper, check whether we want to step into
			 * the wrapped function.
			 */
			if ((method != null) && (method.WrapperType != WrapperType.None)) {
				if (method.WrapperType == WrapperType.DelegateInvoke) {
					sse.do_step_native ();
					return false;
				}
			}

			if (!sse.MethodHasSource (method)) {
				sse.do_next_native ();
				return false;
			}

			/*
			 * Finally, step into the method.
			 */
			sse.do_step_native ();
			return false;
		}

		protected override bool DoProcessEvent ()
		{
			Report.Debug (DebugFlags.SSE, "{0} processing {1} event.",
				      sse, this);
			return Step (false);
		}

		protected override string MyToString ()
		{
			return String.Format ("{0}:{1}", StepMode, StepFrame);
		}
	}

	protected class OperationRun : Operation
	{
		TargetAddress until;
		bool in_background;

		public OperationRun (SingleSteppingEngine sse, TargetAddress until,
				     bool in_background, CommandResult result)
			: base (sse, result)
		{
			this.until = until;
			this.in_background = in_background;
		}

		public OperationRun (SingleSteppingEngine sse, bool in_background,
				     CommandResult result)
			: this (sse, TargetAddress.Null, in_background, result)
		{ }

		public OperationRun (SingleSteppingEngine sse, CommandResult result)
			: this (sse, TargetAddress.Null, true, result)
		{ }


		public bool InBackground {
			get { return in_background; }
		}

		public override bool IsSourceOperation {
			get { return true; }
		}

		protected override void DoExecute ()
		{
			if (!until.IsNull)
				sse.do_continue (until);
			else
				sse.do_continue ();
		}

		protected override bool ResumeOperation ()
		{
			Report.Debug (DebugFlags.SSE, "{0} resuming operation {1}", sse, this);

			sse.do_continue ();
			return true;
		}

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			args = null;
			if (!until.IsNull && inferior.CurrentFrame == until)
				return EventResult.Completed;
			Report.Debug (DebugFlags.EventLoop, "{0} received {1} at {2} in {3}",
				      sse, cevent, inferior.CurrentFrame, this);
			if ((cevent.Type == Inferior.ChildEventType.CHILD_HIT_BREAKPOINT) ||
			    (cevent.Type == Inferior.ChildEventType.CHILD_CALLBACK))
				return EventResult.Completed;
			Execute ();
			return EventResult.Running;
		}

		public override bool HandleException (TargetAddress stack, TargetAddress exc)
		{
			return false;
		}
	}

	protected class OperationFinish : OperationStepBase
	{
		public readonly bool Native;

		public OperationFinish (SingleSteppingEngine sse, bool native, CommandResult result)
			: base (sse, result)
		{
			this.Native = native;
		}

		public override bool IsSourceOperation {
			get { return !Native; }
		}

		StepFrame step_frame;
		TargetAddress until;

		protected override void DoExecute ()
		{
			if (!Native) {
				StackFrame frame = sse.CurrentFrame;
				if (frame.Method == null)
					throw new TargetException (TargetError.NoMethod);

				step_frame = new StepFrame (
					frame.Method.StartAddress, frame.Method.EndAddress,
					frame, null, StepMode.Finish);
			} else {
				Inferior.StackFrame frame = inferior.GetCurrentFrame ();
				until = frame.StackPointer;

				Report.Debug (DebugFlags.SSE,
					      "{0} starting finish native until {1} {2}",
					      sse, until, sse.temp_breakpoint_id);
			}

			sse.do_next_native ();
		}

		protected override bool ResumeOperation ()
		{
			Report.Debug (DebugFlags.SSE, "{0} resuming operation {1}", sse, this);

			if (sse.temp_breakpoint_id != 0) {
				inferior.Continue ();
				return true;
			}

			return !DoProcessEvent ();
		}

		protected override bool DoProcessEvent ()
		{
			if (step_frame != null) {
				bool in_frame = sse.is_in_step_frame (step_frame, inferior.CurrentFrame);
				Report.Debug (DebugFlags.SSE,
					      "{0} finish {1} at {2} ({3}", sse, step_frame,
					      inferior.CurrentFrame, in_frame);

				if (!in_frame)
					return true;

				sse.do_next_native ();
				return false;
			}

			Inferior.StackFrame frame = inferior.GetCurrentFrame ();
			TargetAddress stack = frame.StackPointer;

			Report.Debug (DebugFlags.SSE,
				      "{0} finish native: stack = {1}, " +
				      "until = {2}", sse, stack, until);

			if (stack <= until) {
				sse.do_next_native ();
				return false;
			}

			return true;
		}

		protected override bool TrampolineHandler (Method method)
		{
			return false;
		}
	}

	protected abstract class OperationCallback : Operation
	{
		public readonly long ID = ++next_id;
		StackData stack_data;

		static int next_id = 0;

		protected OperationCallback (SingleSteppingEngine sse)
			: base (sse, null)
		{ }

		protected OperationCallback (SingleSteppingEngine sse, CommandResult result)
			: base (sse, result)
		{ }

		public override void Execute ()
		{
			stack_data = sse.save_stack (ID);
			base.Execute ();
		}

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			Report.Debug (DebugFlags.EventLoop,
				      "{0} received event {1} at {2} while waiting for " +
				      "callback {4}:{3}", sse, cevent, inferior.CurrentFrame,
				      ID, this);

			args = null;
			if ((cevent.Type == Inferior.ChildEventType.CHILD_STOPPED) &&
			    (cevent.Argument == 0)) {
				sse.do_continue ();
				return EventResult.Running;
			} else if (cevent.Type != Inferior.ChildEventType.CHILD_CALLBACK) {
				Report.Debug (DebugFlags.SSE,
					      "{0} aborting callback {1} ({2}) at {3}: {4}",
					      sse, this, ID, inferior.CurrentFrame, cevent);
				AbortOperation ();
				return EventResult.Completed;
			}

			if (ID != cevent.Argument) {
				Report.Debug (DebugFlags.SSE,
					      "{0} aborting callback {1} ({2}) at {3}: {4}",
					      sse, this, ID, inferior.CurrentFrame, cevent);
				AbortOperation ();
				return EventResult.Completed;
			}

			try {
				args = null;
				return CallbackCompleted (cevent);
			} catch {
				RestoreStack ();
				return EventResult.CompletedCallback;
			}
		}

		protected virtual EventResult CallbackCompleted (Inferior.ChildEvent cevent)
		{
			return CallbackCompleted (cevent.Data1, cevent.Data2);
		}

		protected abstract EventResult CallbackCompleted (long data1, long data2);

		public override bool IsSourceOperation {
			get { return false; }
		}

		protected void AbortOperation ()
		{
			stack_data = null;
		}

		protected void RestoreStack ()
		{
			if (stack_data != null)
				sse.restore_stack (stack_data);
			stack_data = null;
		}

		protected void DiscardStack ()
		{
			stack_data = null;
		}
	}

	protected class OperationRuntimeInvoke : OperationCallback
	{
		new public readonly RuntimeInvokeResult Result;
		public readonly MonoFunctionType Function;
		public readonly TargetObject[] ParamObjects;
		public readonly bool IsVirtual;
		public readonly bool Debug;

		private readonly TargetMemoryAccess internal_target;

		MonoLanguageBackend language;
		TargetAddress method = TargetAddress.Null;
		TargetAddress invoke = TargetAddress.Null;
		TargetStructObject instance;
		MonoClassInfo class_info;
		Stage stage;

		protected enum Stage {
			Uninitialized,
			ResolvedClass,
			BoxingInstance,
			HasMethodAddress,
			GettingVirtualMethod,
			HasVirtualMethod,
			CompilingMethod,
			CompiledMethod,
			InvokedMethod
		}

		public override bool IsSourceOperation {
			get { return true; }
		}

		public OperationRuntimeInvoke (SingleSteppingEngine sse,
					       TargetFunctionType function,
					       TargetClassObject instance,
					       TargetObject[] param_objects,
					       bool is_virtual, bool debug,
					       RuntimeInvokeResult result)
			: base (sse, result)
		{
			this.Result = result;
			this.Function = (MonoFunctionType) function;
			this.instance = instance;
			this.ParamObjects = param_objects;
			this.IsVirtual = is_virtual;
			this.Debug = debug;
			this.method = TargetAddress.Null;
			this.stage = Stage.Uninitialized;

			this.internal_target = inferior;
		}

		protected override void DoExecute ()
		{
			language = sse.process.MonoLanguage;

			class_info = Function.MonoClass.ResolveClass (inferior, false);
			if (class_info == null) {
				TargetAddress image = Function.MonoClass.File.MonoImage;
				int token = Function.MonoClass.Token;

				Report.Debug (DebugFlags.SSE,
					      "{0} rti resolving class {1}:{2:x}", sse, image, token);

				inferior.CallMethod (
					sse.MonoDebuggerInfo.LookupClass, image.Address, 0, 0,
					Function.MonoClass.Name, ID);
				return;
			}

			stage = Stage.ResolvedClass;
			do_execute ();
		}

		void do_execute ()
		{
			switch (stage) {
			case Stage.ResolvedClass:
				if (!get_method_address ())
					return;
				goto case Stage.HasMethodAddress;

			case Stage.HasMethodAddress:
				if (!get_virtual_method ())
					return;
				goto case Stage.HasVirtualMethod;

			case Stage.HasVirtualMethod: {
				Report.Debug (DebugFlags.SSE,
					      "{0} rti compiling method: {1}", sse, method);

				stage = Stage.CompilingMethod;
				inferior.CallMethod (
					sse.MonoDebuggerInfo.CompileMethod, method.Address, 0, ID);
				return;
			}

			case Stage.CompiledMethod: {
				sse.insert_temporary_breakpoint (invoke);

				inferior.RuntimeInvoke (
					sse.MonoDebuggerInfo.RuntimeInvoke,
					method, instance, ParamObjects, ID, Debug);

				stage = Stage.InvokedMethod;
				return;
			}

			default:
				throw new InternalError ();
			}
		}

		bool get_method_address ()
		{
			method = class_info.GetMethodAddress (inferior, Function.Token);

			if ((instance == null) || instance.Type.IsByRef)
				return true;

			TargetType decl = Function.DeclaringType;
			if ((decl.Name != "System.ValueType") && (decl.Name != "System.Object"))
				return true;

			TargetStructType parent_type = instance.Type.GetParentType (inferior);

			if (!instance.Type.IsByRef && parent_type.IsByRef) {
				TargetAddress klass = ((MonoClassObject) instance).GetKlassAddress (inferior);
				stage = Stage.BoxingInstance;
				inferior.CallMethod (
					sse.MonoDebuggerInfo.GetBoxedObjectMethod, klass.Address,
					instance.Location.GetAddress (internal_target).Address, ID);
				return false;
			}

			return true;
		}

		bool get_virtual_method ()
		{
			if (!IsVirtual || (instance == null) || !instance.HasAddress ||
			    !instance.Type.IsByRef)
				return true;

			stage = Stage.GettingVirtualMethod;
			inferior.CallMethod (
				sse.MonoDebuggerInfo.GetVirtualMethod,
				instance.Location.GetAddress (internal_target).Address,
				method.Address, ID);
			return false;
		}

		protected override EventResult CallbackCompleted (long data1, long data2)
		{
			switch (stage) {
			case Stage.Uninitialized: {
				TargetAddress klass = new TargetAddress (inferior.AddressDomain, data1);

				Report.Debug (DebugFlags.SSE,
					      "{0} rti resolved class: {1}", sse, klass);

				class_info = Function.MonoClass.ClassResolved (inferior, klass);
				stage = Stage.ResolvedClass;
				do_execute ();
				return EventResult.Running;
			}

			case Stage.BoxingInstance: {
				TargetAddress boxed = new TargetAddress (inferior.AddressDomain, data1);

				Report.Debug (DebugFlags.SSE,
					      "{0} rti boxed object: {1}", sse, boxed);

				TargetLocation new_loc = new AbsoluteTargetLocation (boxed);
				TargetStructType parent_type = instance.Type.GetParentType (inferior);
				instance = (TargetStructObject) parent_type.GetObject (inferior, new_loc);
				stage = Stage.HasMethodAddress;
				do_execute ();
				return EventResult.Running;
			}

			case Stage.GettingVirtualMethod: {
				method = new TargetAddress (inferior.AddressDomain, data1);

				Report.Debug (DebugFlags.SSE,
					      "{0} rti got virtual method: {1}", sse, method);

				TargetAddress klass = inferior.ReadAddress (method + 8);
				TargetType class_type = language.ReadMonoClass (inferior, klass);

				if (class_type == null) {
					Result.ExceptionMessage = String.Format (
						"Unable to get virtual method `{0}'.", Function.FullName);
					Result.InvocationCompleted = true;
					RestoreStack ();
					return EventResult.CompletedCallback;
				}

				if (!class_type.IsByRef) {
					TargetLocation new_loc = instance.Location.GetLocationAtOffset (
						2 * inferior.TargetMemoryInfo.TargetAddressSize);
					instance = (TargetClassObject) class_type.GetObject (
						inferior, new_loc);
				}

				stage = Stage.HasVirtualMethod;
				do_execute ();
				return EventResult.Running;
			}

			case Stage.CompilingMethod: {
				invoke = new TargetAddress (inferior.AddressDomain, data1);

				Report.Debug (DebugFlags.SSE,
					      "{0} rti compiled method: {1}", sse, invoke);

				stage = Stage.CompiledMethod;
				do_execute ();
				return EventResult.Running;
			}

			case Stage.InvokedMethod: {
				Report.Debug (DebugFlags.SSE,
					      "{0} rti done: {1:x} {2:x}",
					      sse, data1, data2);

				if (data2 != 0) {
					TargetAddress exc_address = new TargetAddress (
						inferior.AddressDomain, data2);
					TargetFundamentalObject exc_obj = (TargetFundamentalObject)
						language.CreateObject (inferior, exc_address);

					Result.ExceptionMessage = (string) exc_obj.GetObject (inferior);
				}

				if (data1 != 0) {
					TargetAddress retval_address = new TargetAddress (
						inferior.AddressDomain, data1);

					Result.ReturnObject = language.CreateObject (
						inferior, retval_address);
				}

				Result.InvocationCompleted = true;
				RestoreStack ();
				return EventResult.CompletedCallback;
			}

			default:
				throw new InternalError ();
			}
		}

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			if (cevent.Type == Inferior.ChildEventType.CHILD_HIT_BREAKPOINT) {
				Report.Debug (DebugFlags.SSE,
					      "{0} hit breakpoint {1} at {2} during runtime-invoke",
					      sse, cevent.Argument, inferior.CurrentFrame);
			} else if ((cevent.Type == Inferior.ChildEventType.CHILD_STOPPED) &&
				   (cevent.Argument == 0)) {
				Report.Debug (DebugFlags.SSE,
					      "{0} stopped at {1} during runtime-invoke",
					      sse, inferior.CurrentFrame);
			}

			if ((cevent.Type == Inferior.ChildEventType.CHILD_HIT_BREAKPOINT) ||
			    (cevent.Type == Inferior.ChildEventType.CHILD_STOPPED)) {
				if (inferior.CurrentFrame == invoke) {
					Report.Debug (DebugFlags.SSE,
						      "{0} stopped at invoke method {1}",
						      sse, invoke);

					inferior.MarkRuntimeInvokeFrame ();
				}

				args = null;
				if (Debug)
					return EventResult.Completed;
				else {
					sse.do_continue ();
					return EventResult.Running;
				}
			}

			return base.DoProcessEvent (cevent, out args);
		}

		public override bool HandleException (TargetAddress stack, TargetAddress exc)
		{
			return false;
		}
	}

	protected class OperationCallMethod : OperationCallback
	{
		public readonly CallMethodType Type;
		public readonly TargetAddress Method;
		public readonly long Argument1;
		public readonly long Argument2;
		public readonly long Argument3;
		public readonly string StringArgument;

		public OperationCallMethod (SingleSteppingEngine sse,
					    TargetAddress method, long arg1, long arg2, long arg3,
					    string sarg)
			: base (sse)
		{
			this.Type = CallMethodType.LongLongLongString;
			this.Method = method;
			this.Argument1 = arg1;
			this.Argument2 = arg2;
			this.Argument3 = arg3;
			this.StringArgument = sarg;
		}

		public OperationCallMethod (SingleSteppingEngine sse,
					    TargetAddress method, long arg1, long arg2)
			: base (sse)
		{
			this.Type = CallMethodType.LongLong;
			this.Method = method;
			this.Argument1 = arg1;
			this.Argument2 = arg2;
		}

		protected override void DoExecute ()
		{
			switch (Type) {
			case CallMethodType.LongLong:
				inferior.CallMethod (Method, Argument1, Argument2, ID);
				break;

			case CallMethodType.LongLongLongString:
				inferior.CallMethod (Method, Argument1, Argument2, Argument3,
						     StringArgument, ID);
				break;

			default:
				throw new InvalidOperationException ();
			}
		}

		protected override EventResult CallbackCompleted (long data1, long data2)
		{
			if (inferior.TargetAddressSize == 4)
				data1 &= 0xffffffffL;

			Report.Debug (DebugFlags.SSE,
				      "{0} call method done: {1:x} {2:x} {3}",
				      sse, data1, data2, Result);

			RestoreStack ();
			Result.Result = new TargetAddress (inferior.AddressDomain, data1);
			return EventResult.CompletedCallback;
		}
	}

	protected class OperationMonoTrampoline : Operation
	{
		public readonly Instruction CallSite;
		public readonly TargetAddress Trampoline;
		public readonly TrampolineHandler TrampolineHandler;

		TargetAddress address = TargetAddress.Null;
		bool compiled;

		public OperationMonoTrampoline (SingleSteppingEngine sse, Instruction call_site,
						TargetAddress trampoline, TrampolineHandler handler)
			: base (sse, null)
		{
			this.CallSite = call_site;
			this.Trampoline = trampoline;
			this.TrampolineHandler = handler;
		}

		public override bool IsSourceOperation {
			get { return true; }
		}

		protected override void DoExecute ()
		{
			sse.enable_extended_notification (NotificationType.Trampoline);
			sse.do_continue ();
		}

		protected void TrampolineCompiled (TargetAddress mono_method, TargetAddress code)
		{
			sse.disable_extended_notification (NotificationType.Trampoline);

			if (TrampolineHandler != null) {
				Method method = sse.Lookup (code);
				if (!TrampolineHandler (method)) {
					sse.do_continue (CallSite.Address + CallSite.InstructionSize);
					return;
				}
			}

			sse.do_continue (code);
		}

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			if ((cevent.Type == Inferior.ChildEventType.CHILD_NOTIFICATION) &&
			    ((NotificationType) cevent.Argument == NotificationType.Trampoline)) {
				TargetAddress method = new TargetAddress (
					inferior.AddressDomain, cevent.Data1);
				TargetAddress code = new TargetAddress (
					inferior.AddressDomain, cevent.Data2);

				args = null;
				compiled = true;
				TrampolineCompiled (method, code);
				return EventResult.Running;
			}

			args = null;
			if (!compiled) {
				sse.disable_extended_notification (NotificationType.Trampoline);
				return EventResult.Completed;
			} else
				return EventResult.ResumeOperation;
		}
	}

	protected class OperationNativeTrampoline : Operation
	{
		public readonly TrampolineHandler TrampolineHandler;
		public readonly TargetAddress Trampoline;

		TargetAddress stack_pointer;
		bool entered_trampoline;
		bool done;

		public OperationNativeTrampoline (SingleSteppingEngine sse, TargetAddress trampoline,
						  TrampolineHandler handler)
			: base (sse, null)
		{
			this.TrampolineHandler = handler;
			this.Trampoline = trampoline;
		}

		public override bool IsSourceOperation {
			get { return true; }
		}

		protected override void DoExecute ()
		{
			Inferior.StackFrame frame = inferior.GetCurrentFrame ();
			stack_pointer = frame.StackPointer;

			Report.Debug (DebugFlags.SSE,
				      "{0} starting native trampoline {1} at {2}: {3}",
				      sse, Trampoline, frame.Address, stack_pointer);

			sse.do_continue (Trampoline);
		}

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} native trampoline event: {1}", sse, cevent);

			args = null;

			Inferior.StackFrame frame = inferior.GetCurrentFrame ();

			if (done)
				return EventResult.Completed;

			if (!entered_trampoline) {
				stack_pointer = frame.StackPointer;

				sse.do_step_native ();
				entered_trampoline = true;
				return EventResult.Running;
			}

			if (frame.StackPointer <= stack_pointer) {
				sse.do_next_native ();
				return EventResult.Running;
			}

			done = true;

			Instruction instruction = sse.Architecture.ReadInstruction (
				inferior, frame.Address);
			if ((instruction == null) || !instruction.HasInstructionSize) {
				sse.do_step_native ();
				return EventResult.Running;
			}

			if (instruction.InstructionType != Instruction.Type.Jump) {
				sse.do_step_native ();
				return EventResult.Running;
			}

			return EventResult.Completed;
		}
	}

	protected class OperationException : Operation
	{
		TargetAddress ip;
		TargetAddress exc;
		bool unhandled;

		public OperationException (SingleSteppingEngine sse,
					   TargetAddress ip, TargetAddress exc, bool unhandled)
			: base (sse, null)
		{
			this.ip = ip;
			this.exc = exc;
			this.unhandled = unhandled;
		}

		public override bool IsSourceOperation {
			get { return false; }
		}

		protected override void DoExecute ()
		{
			sse.remove_temporary_breakpoint ();
			sse.do_continue (ip);
		}

		protected override EventResult DoProcessEvent (Inferior.ChildEvent cevent,
							       out TargetEventArgs args)
		{
			Report.Debug (DebugFlags.SSE,
				      "{0} processing OperationException at {1}: {2} {3} {4}",
				      sse, inferior.CurrentFrame, ip, exc, unhandled);
				      
			if (unhandled) {
				sse.frame_changed (inferior.CurrentFrame, null);
				sse.current_frame.SetExceptionObject (exc);
				args = new TargetEventArgs (
					TargetEventType.UnhandledException,
					exc, sse.current_frame);
				return EventResult.Completed;
			} else {
				sse.frame_changed (inferior.CurrentFrame, null);
				sse.current_frame.SetExceptionObject (exc);
				args = new TargetEventArgs (
					TargetEventType.Exception,
					exc, sse.current_frame);
				return EventResult.Completed;
			}
		}
	}

	protected class OperationWrapper : OperationStepBase
	{
		Method method;

		public OperationWrapper (SingleSteppingEngine sse,
					 Method method, CommandResult result)
			: base (sse, result)
		{
			this.method = method;
		}

		public override bool IsSourceOperation {
			get { return true; }
		}

		protected override void DoExecute ()
		{
			sse.do_step_native ();
		}

		protected override bool DoProcessEvent ()
		{
			TargetAddress current_frame = inferior.CurrentFrame;

			Report.Debug (DebugFlags.SSE, "{0} wrapper stopped at {1} ({2}:{3})",
				      sse, current_frame, method.StartAddress, method.EndAddress);
			if ((current_frame < method.StartAddress) || (current_frame > method.EndAddress))
				return true;

			/*
			 * If this is not a call instruction, continue stepping until we leave
			 * the current method.
			 */
			Instruction instruction = inferior.Architecture.ReadInstruction (
				inferior, current_frame);
			if ((instruction == null) || !instruction.HasInstructionSize) {
				sse.do_step_native ();
				return false;
			}

			if (sse.CheckTrampoline (instruction, TrampolineHandler))
				return false;

			sse.do_step_native ();
			return false;
		}

		protected override bool TrampolineHandler (Method method)
		{
			if (method == null)
				return false;

			if (method.WrapperType == WrapperType.DelegateInvoke)
				return true;

			return sse.MethodHasSource (method);
		}
	}

	protected class OperationDelegateInvoke : OperationStepBase
	{
		public OperationDelegateInvoke (SingleSteppingEngine sse)
			: base (sse, null)
		{ }

		public override bool IsSourceOperation {
			get { return true; }
		}

		protected override void DoExecute ()
		{
			sse.do_step_native ();
		}

		bool finished;

		protected override bool DoProcessEvent ()
		{
			TargetAddress current_frame = inferior.CurrentFrame;

			Report.Debug (DebugFlags.SSE, "{0} delegate impl stopped at {1}",
				      sse, current_frame);

			if (finished)
				return true;

			/*
			 * If this is not a call instruction, continue stepping until we leave
			 * the current method.
			 */
			Instruction instruction = inferior.Architecture.ReadInstruction (
				inferior, current_frame);
			if ((instruction == null) || !instruction.HasInstructionSize) {
				sse.do_step_native ();
				return false;
			}

			Report.Debug (DebugFlags.SSE, "{0} delegate impl stopped at {1}: {2}",
				      sse, current_frame, instruction);

			if ((instruction.InstructionType == Instruction.Type.IndirectJump) ||
			    (instruction.InstructionType == Instruction.Type.IndirectCall))
				finished = true;

			sse.do_step_native ();
			return false;
		}

		protected override bool TrampolineHandler (Method method)
		{
			return false;
		}
	}

	protected class OperationReturn : OperationCallback
	{
		public readonly MonoLanguageBackend Language;
		public readonly StackFrame ParentFrame;

		public OperationReturn (SingleSteppingEngine sse,
					MonoLanguageBackend language, StackFrame parent_frame)
			: base (sse)
		{
			this.Language = language;
			this.ParentFrame = parent_frame;
		}

		protected override void DoExecute ()
		{
			inferior.CallMethod (sse.MonoDebuggerInfo.RunFinally, null, ID);
		}

		protected override EventResult CallbackCompleted (long data1, long data2)
		{
			DiscardStack ();
			inferior.AbortInvoke (ParentFrame.StackPointer);
			inferior.SetRegisters (ParentFrame.Registers);
			return EventResult.Completed;
		}
	}

	protected class OperationAbortInvocation : OperationCallback
	{
		public readonly Backtrace Backtrace;
		int level = 0;

		public OperationAbortInvocation (SingleSteppingEngine sse, Backtrace backtrace)
			: base (sse)
		{
			this.Backtrace = backtrace;
		}

		protected override void DoExecute ()
		{
			inferior.CallMethod (sse.MonoDebuggerInfo.RunFinally, null, ID);
		}

		protected override EventResult CallbackCompleted (long data1, long data2)
		{
			StackFrame parent_frame = Backtrace.Frames [++level];

			if (inferior.AbortInvoke (parent_frame.StackPointer)) {
				DiscardStack ();
				return EventResult.Completed;
			}

			inferior.SetRegisters (parent_frame.Registers);
			inferior.CallMethod (sse.MonoDebuggerInfo.RunFinally, null, ID);
			return EventResult.Running;
		}
	}
#endregion
	}

	[Serializable]
	internal enum CommandType {
		TargetAccess,
		CreateProcess
	}

	[Serializable]
	internal class Command {
		public SingleSteppingEngine Engine;
		public readonly CommandType Type;
		public object Data1, Data2;
		public object Result;

		public Command (SingleSteppingEngine sse, TargetAccessDelegate func, object data)
		{
			this.Type = CommandType.TargetAccess;
			this.Engine = sse;
			this.Data1 = func;
			this.Data2 = data;
		}

		public Command (CommandType type, object data)
		{
			this.Type = type;
			this.Data1 = data;
		}

		public override string ToString ()
		{
			return String.Format ("Command ({0}:{1}:{2}:{3})",
					      Engine, Type, Data1, Data2);
		}
	}

	[Serializable]
	internal enum CallMethodType
	{
		LongLong,
		LongLongLongString
	}
}