Welcome to mirror list, hosted at ThFree Co, Russian Federation.

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

//#define DEBUG_EVENT_QUEUEING

using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Net.Sockets;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

using Newtonsoft.Json;

using Mono.Debugger.Soft;

using Mono.Debugging.Client;
using Mono.Debugging.Evaluation;

using StackFrame = Mono.Debugger.Soft.StackFrame;
using System.Collections.Immutable;

namespace Mono.Debugging.Soft
{
	public class SoftDebuggerSession : DebuggerSession
	{
		readonly Dictionary<AppDomainMirror, HashSet<AssemblyMirror>> domainAssembliesToUnload = new Dictionary<AppDomainMirror, HashSet<AssemblyMirror>> ();
		readonly Dictionary<Tuple<TypeMirror, string>, MethodMirror[]> overloadResolveCache = new Dictionary<Tuple<TypeMirror, string>, MethodMirror[]> ();
		readonly Dictionary<string, List<TypeMirror>> source_to_type = new Dictionary<string, List<TypeMirror>> (PathComparer);
		readonly Dictionary<long,ObjectMirror> activeExceptionsByThread = new Dictionary<long, ObjectMirror> ();
		readonly Dictionary<EventRequest, BreakInfo> breakpoints = new Dictionary<EventRequest, BreakInfo> ();
		readonly Dictionary<TypeMirror, string[]> type_to_source = new Dictionary<TypeMirror, string[]> ();
		readonly Dictionary<string, List<TypeMirror>> aliases = new Dictionary<string, List<TypeMirror>> ();
		readonly Dictionary<string, List<TypeMirror>> types = new Dictionary<string, List<TypeMirror>> ();
		readonly LinkedList<List<Event>> queuedEventSets = new LinkedList<List<Event>> ();
		readonly Dictionary<long,long> localThreadIds = new Dictionary<long, long> ();
		readonly List<BreakInfo> pending_bes = new List<BreakInfo> ();
		TypeLoadEventRequest typeLoadReq, typeLoadTypeNameReq;
		ExceptionEventRequest unhandledExceptionRequest;
		Dictionary<string, string> assemblyPathMap;
		Dictionary<string, string> symbolPathMap;
		ThreadMirror current_thread, recent_thread;
		List<AssemblyMirror> assemblyFilters;
		StepEventRequest currentStepRequest;
		IConnectionDialog connectionDialog;
		Thread outputReader, errorReader;
		bool loggedSymlinkedRuntimesBug;
		SoftDebuggerStartArgs startArgs;
		List<string> userAssemblyNames;
		List<SourceUpdate> sourceUpdates;
		ThreadInfo[] current_threads;
		string remoteProcessName;
		long currentAddress = -1;
		IAsyncResult connection;
		int currentStackDepth;
		ProcessInfo[] procs;
		Thread eventHandler;
		VirtualMachine vm;
		bool autoStepInto;
		bool disposed;
		bool started;

		internal int StackVersion;

		public SoftDebuggerAdaptor Adaptor {
			get; private set;
		}

		public SoftDebuggerSession ()
		{
			Adaptor = CreateSoftDebuggerAdaptor ();
			Adaptor.BusyStateChanged += (sender, e) => SetBusyState (e);
			Adaptor.DebuggerSession = this;
			sourceUpdates = new List<SourceUpdate> ();
		}

		protected virtual SoftDebuggerAdaptor CreateSoftDebuggerAdaptor ()
		{
			return new SoftDebuggerAdaptor ();
		}

		public Version ProtocolVersion {
			get { return new Version (vm.Version.MajorVersion, vm.Version.MinorVersion); }
		}

		protected override void OnRun (DebuggerStartInfo startInfo)
		{
			if (HasExited)
				throw new InvalidOperationException ("Already exited");

			SetupProcessStartHooks ();
			
			var dsi = (SoftDebuggerStartInfo) startInfo;
			if (dsi.StartArgs is SoftDebuggerLaunchArgs) {
				remoteProcessName = Path.GetFileNameWithoutExtension (dsi.Command);
				StartLaunching (dsi);
			} else if (dsi.StartArgs is SoftDebuggerConnectArgs) {
				StartConnecting (dsi);
			} else if (dsi.StartArgs is SoftDebuggerListenArgs) {
				StartListening (dsi);
			} else if (dsi.StartArgs.ConnectionProvider != null) {
				StartConnection (dsi);
			} else {
				throw new ArgumentException ("StartArgs has no ConnectionProvider");
			}
		}
		
		void StartConnection (SoftDebuggerStartInfo dsi)
		{
			startArgs = dsi.StartArgs;
			
			RegisterUserAssemblies (dsi);
			
			if (!String.IsNullOrEmpty (dsi.LogMessage))
				OnDebuggerOutput (false, dsi.LogMessage + Environment.NewLine);
			
			AsyncCallback callback = null;
			int attemptNumber = 0;
			int maxAttempts = startArgs.MaxConnectionAttempts;
			int timeBetweenAttempts = startArgs.TimeBetweenConnectionAttempts;
			callback = delegate (IAsyncResult ar) {
				try {
					string appName;
					VirtualMachine machine;
					startArgs.ConnectionProvider.EndConnect (ar, out machine, out appName);
					remoteProcessName = appName;
					ConnectionStarted (machine);
					return;
				} catch (Exception ex) {
					attemptNumber++;
					if (!ShouldRetryConnection (ex, attemptNumber)
						|| startArgs?.ConnectionProvider?.ShouldRetryConnection (ex) == false
						|| attemptNumber == maxAttempts
						|| HasExited) {
						OnConnectionError (ex);
						return;
					}
				}
				try {
					if (timeBetweenAttempts > 0)
						Thread.Sleep (timeBetweenAttempts);
					ConnectionStarting (startArgs.ConnectionProvider.BeginConnect (dsi, callback), dsi, false, attemptNumber);
				} catch (Exception ex2) {
					OnConnectionError (ex2);
				}
			};
			//the "listening" value is never used, pass a dummy value
			ConnectionStarting (startArgs.ConnectionProvider.BeginConnect (dsi, callback), dsi, false, 0);
		}
		
		void StartLaunching (SoftDebuggerStartInfo dsi)
		{
			var args = (SoftDebuggerLaunchArgs) dsi.StartArgs;
			var executable = string.IsNullOrEmpty (args.MonoExecutableFileName) ? "mono" : args.MonoExecutableFileName;
			var runtime = string.IsNullOrEmpty (args.MonoRuntimePrefix) ? executable : Path.Combine (Path.Combine (args.MonoRuntimePrefix, "bin"), executable);
			RegisterUserAssemblies (dsi);
			
			var psi = new System.Diagnostics.ProcessStartInfo (runtime) {
				Arguments = string.Format ("{2} \"{0}\" {1}", dsi.Command, dsi.Arguments, dsi.RuntimeArguments),
				WorkingDirectory = dsi.WorkingDirectory,
				RedirectStandardOutput = true,
				RedirectStandardError = true,
				UseShellExecute = false,
				CreateNoWindow = true,
			};
			
			LaunchOptions options = null;
			
			if (dsi.UseExternalConsole && args.ExternalConsoleLauncher != null) {
				options = new LaunchOptions ();
				options.CustomTargetProcessLauncher = args.ExternalConsoleLauncher;
				psi.RedirectStandardOutput = false;
				psi.RedirectStandardError = false;
			}
			if (args.CustomProcessLauncher != null) {
				options = options ?? new LaunchOptions ();
				options.CustomProcessLauncher = args.CustomProcessLauncher;
			}

			var sdbLog = Environment.GetEnvironmentVariable ("MONODEVELOP_SDB_LOG");
			if (!string.IsNullOrEmpty (sdbLog)) {
				options = options ?? new LaunchOptions ();
				options.AgentArgs = string.Format ("loglevel=10,logfile='{0}',setpgid=y", sdbLog);
			}
			
			foreach (var env in args.MonoRuntimeEnvironmentVariables)
				psi.EnvironmentVariables[env.Key] = env.Value;
			
			foreach (var env in dsi.EnvironmentVariables)
				psi.EnvironmentVariables[env.Key] = env.Value;
			
			if (!string.IsNullOrEmpty (dsi.LogMessage))
				OnDebuggerOutput (false, dsi.LogMessage + Environment.NewLine);

			var callback = HandleConnectionCallbackErrors (ar => ConnectionStarted (VirtualMachineManager.EndLaunch (ar)));
			ConnectionStarting (VirtualMachineManager.BeginLaunch (psi, callback, options), dsi, true, 0);
		}
		
		/// <summary>Starts the debugger listening for a connection over TCP/IP</summary>
		protected void StartListening (SoftDebuggerStartInfo dsi)
		{
			int dp, cp;
			StartListening (dsi, out dp, out cp);
		}
		
		/// <summary>Starts the debugger listening for a connection over TCP/IP</summary>
		protected void StartListening (SoftDebuggerStartInfo dsi, out int assignedDebugPort)
		{
			int cp;
			StartListening (dsi, out assignedDebugPort, out cp);
		}
		
		/// <summary>Starts the debugger listening for a connection over TCP/IP</summary>
		protected void StartListening (SoftDebuggerStartInfo dsi, out int assignedDebugPort, out int assignedConsolePort)
		{
			IPEndPoint dbgEP, conEP;
			InitForRemoteSession (dsi, out dbgEP, out conEP);

			var callback = HandleConnectionCallbackErrors (ar => ConnectionStarted (VirtualMachineManager.EndListen (ar)));
			var a = VirtualMachineManager.BeginListen (dbgEP, conEP, callback, out assignedDebugPort, out assignedConsolePort);
			ConnectionStarting (a, dsi, true, 0);
		}

		protected virtual bool ShouldRetryConnection (Exception ex, int attemptNumber)
		{
			var sx = ex as SocketException;
			if (sx != null) {
				if (sx.ErrorCode == 10061) //connection refused
					return true;
			}
			//retry if it receives 0 byte and threw an exception in the handshake
			return true;
		}
		
		protected void StartConnecting (SoftDebuggerStartInfo dsi)
		{
			StartConnecting (dsi, dsi.StartArgs.MaxConnectionAttempts, dsi.StartArgs.TimeBetweenConnectionAttempts);
		}
		
		/// <summary>Starts the debugger connecting to a remote IP</summary>
		protected void StartConnecting (SoftDebuggerStartInfo dsi, int maxAttempts, int timeBetweenAttempts)
		{	
			if (timeBetweenAttempts < 0 || timeBetweenAttempts > 10000)
				throw new ArgumentException ("timeBetweenAttempts");
			
			IPEndPoint dbgEP, conEP;
			InitForRemoteSession (dsi, out dbgEP, out conEP);

			AsyncCallback callback = null;
			int attemptNumber = 0;
			callback = delegate (IAsyncResult ar) {
				try {
					ConnectionStarted (VirtualMachineManager.EndConnect (ar));
					return;
				} catch (Exception ex) {
					attemptNumber++;
					if (!ShouldRetryConnection (ex, attemptNumber) || attemptNumber == maxAttempts || HasExited) {
						OnConnectionError (ex);
						return;
					}
				}
				try {
					if (timeBetweenAttempts > 0)
						Thread.Sleep (timeBetweenAttempts);
					
					ConnectionStarting (VirtualMachineManager.BeginConnect (dbgEP, conEP, callback), dsi, false, attemptNumber);
					
				} catch (Exception ex2) {
					OnConnectionError (ex2);
				}
			};
			
			ConnectionStarting (VirtualMachineManager.BeginConnect (dbgEP, conEP, callback), dsi, false, 0);
		}
		
		void InitForRemoteSession (SoftDebuggerStartInfo dsi, out IPEndPoint dbgEP, out IPEndPoint conEP)
		{
			if (remoteProcessName != null)
				throw new InvalidOperationException ("Cannot initialize connection more than once");
			
			var args = (SoftDebuggerRemoteArgs) dsi.StartArgs;
			
			remoteProcessName = args.AppName;
			
			RegisterUserAssemblies (dsi);
			
			dbgEP = new IPEndPoint (args.Address, args.DebugPort);
			conEP = args.RedirectOutput? new IPEndPoint (args.Address, args.OutputPort) : null;
			
			if (!String.IsNullOrEmpty (dsi.LogMessage))
				OnDebuggerOutput (false, dsi.LogMessage + Environment.NewLine);
		}
		
		///<summary>Catches errors in async callbacks and hands off to OnConnectionError</summary>
		AsyncCallback HandleConnectionCallbackErrors (AsyncCallback callback)
		{
			return delegate (IAsyncResult ar) {
				connection = null;
				try {
					callback (ar);
				} catch (Exception ex) {
					OnConnectionError (ex);
				}
			};
		}
		
		/// <summary>
		/// Called if an error happens while making the connection. Default terminates the session.
		/// </summary>
		protected virtual void OnConnectionError (Exception ex)
		{
			//if the exception was caused by cancelling the session
			if (HasExited)
				return;
			
			if (!HandleException (new ConnectionException (ex))) {
				DebuggerLoggingService.LogAndShowException ("Unhandled error launching soft debugger", ex);
			}
			
			// The session is dead
			// HandleException doesn't actually handle exceptions, it just displays them.
			try {
				EndSession ();
			} catch (Exception e) {
				DebuggerLoggingService.LogError ("Unhandled error ending the debugger session", e);
			}
		}
		
		void ConnectionStarting (IAsyncResult connectionHandle, DebuggerStartInfo dsi, bool listening, int attemptNumber) 
		{
			if (connection != null && (attemptNumber == 0 || !connection.IsCompleted))
				throw new InvalidOperationException ("Already connecting");
			
			connection = connectionHandle;

			if (attemptNumber == 0) {
				if (ConnectionDialogCreatorExtended != null)
					connectionDialog = ConnectionDialogCreatorExtended (dsi);
				else if (ConnectionDialogCreator != null)
					connectionDialog = ConnectionDialogCreator ();

				if (connectionDialog != null) {
					connectionDialog.UserCancelled += delegate {
						EndSession ();
					};
				}
			}

			if (connectionDialog != null)
				connectionDialog.SetMessage (dsi, GetConnectingMessage (dsi), listening, attemptNumber);
		}
		
		protected virtual string GetConnectingMessage (DebuggerStartInfo dsi)
		{
			return null;
		}
		
		void EndLaunch ()
		{
			HideConnectionDialog ();
			if (connection != null) {
				try {
					if (startArgs != null && startArgs.ConnectionProvider != null) {
						startArgs.ConnectionProvider.CancelConnect(connection);
						startArgs = null;
					} else {
						VirtualMachineManager.CancelConnection(connection);
					}
				} catch(Exception e) {
					DebuggerLoggingService.LogError("Unhandled error canceling the debugger connection", e);
				}
				connection = null;
			}
		}
		
		protected virtual void EndSession ()
		{
			if (!HasExited) {
				EndLaunch ();
				OnTargetEvent (new TargetEventArgs (TargetEventType.TargetExited));
			}
		}

		const string StartWithShellExecuteExMarker = "___Process_StartWithShellExecuteEx_Marker___";
		const string StartWithCreateProcessMarker = "___Process_StartWithCreateProcess_Marker__";
		const string SetProcessIdMarker = "___Process_SetProcessId_Marker__";

		void SetupProcessStartHooks ()
		{
			if (!Options.DebugSubprocesses)
				return;

			// Subprocess lauch is intercepted using 3 function breakpoints.
			// The first breakpoint is used to intercept calls to start a process with shell execute.
			var bp = Breakpoints.OfType< FunctionBreakpoint> ().FirstOrDefault (b => b.CustomActionId == StartWithShellExecuteExMarker);
			if (bp == null) {
				bp = new FunctionBreakpoint ("System.Diagnostics.Process.StartWithShellExecuteEx", "C#");
				bp.HitAction = HitAction.CustomAction;
				bp.CustomActionId = StartWithShellExecuteExMarker;
				bp.NonUserBreakpoint = true;
				Breakpoints.Add (bp);
			}

			// The second breakpoint is used to intercept calls to start a process with CreateProcess
			bp = Breakpoints.OfType<FunctionBreakpoint> ().FirstOrDefault (b => b.CustomActionId == StartWithCreateProcessMarker);
			if (bp == null) {
				bp = new FunctionBreakpoint ("System.Diagnostics.Process.StartWithCreateProcess", "C#");
				bp.HitAction = HitAction.CustomAction;
				bp.CustomActionId = StartWithCreateProcessMarker;
				bp.NonUserBreakpoint = true;
				Breakpoints.Add (bp);
			}

			// The third breakpoint is used to intercept the method that assigns an ID to the process. This is used to
			// retrieve the process id, and also as a signal that the process has started running
			bp = Breakpoints.OfType<FunctionBreakpoint> ().FirstOrDefault (b => b.CustomActionId == SetProcessIdMarker);
			if (bp == null) {
				bp = new FunctionBreakpoint ("System.Diagnostics.Process.SetProcessId", "C#");
				bp.HitAction = HitAction.CustomAction;
				bp.CustomActionId = SetProcessIdMarker;
				bp.NonUserBreakpoint = true;
				Breakpoints.Add (bp);
			}
		}

		bool HandleProcessStartHook (ThreadMirror thread, BreakEvent b)
		{
			if (!Options.DebugSubprocesses)
				return false;

			// Subprocess debugging is achieved by intercepting calls to start a process using function breakpoints.
			// This is achieved in 3 stages:
			// 1) Process start interception: this is done by adding a function breakpoint to Process.StartWithShellExecuteEx
			//    and Process.StartWithCreateProcess. If the process being launched is a mono process a new debug session
			//    is creaated, and the process start info object is patched to add the debugger agent configuration options.
			// 2) Process launch. This is actually done by the current executing process. The new process is bound to
			//    the new debug session. However, to complete the debug session initialization we need an actual reference
			//    to the process, so that the session can get the process id and subscribe process events, and that's
			//    done in step 3.
			// 3) Process launched interception: this is done by adding a function breakpoint to Process.SetProcessId.
			//    This method is called after starting the process, so at this point it is possible to get a reference
			//    to the running process object and assign it to the debug session to complete the initialization.

			// A potential process start call has been intercepted.

			var evalOptions = EvaluationOptions.DefaultOptions.Clone ();
			evalOptions.AllowTargetInvoke = evalOptions.AllowMethodEvaluation = evalOptions.FlattenHierarchy = true;
			evalOptions.GroupPrivateMembers = evalOptions.GroupStaticMembers = evalOptions.AllowToStringCalls = evalOptions.EllipsizeStrings = false;

			if (b.CustomActionId == StartWithShellExecuteExMarker || b.CustomActionId == StartWithCreateProcessMarker) {

				// A project start call has been intercepted. We need to check if a mono process is being started.

				var fr = thread.GetFrames ()[0];
				var ctx = new SoftEvaluationContext (this, fr, evalOptions);
				var eval = ctx.Evaluator;

				var parameters = eval.GetParameters (ctx);
				var startInfo = parameters.First();
				var exe = (string) startInfo.GetChild ("FileName", evalOptions).GetRawValue (evalOptions);

				// The process being launched is a mono process if the target file is a .exe or .dll, or if the launcher is mono.

				var ext = Path.GetExtension (exe).ToLower ();
				if (ext == ".exe" || ext == ".dll" || Subprocess.IsMonoLauncher (exe)) {

					// If the runtime arguments are already setting up a debugger agent, don't override it
					var arguments = (string)startInfo.GetChild ("Arguments", evalOptions).GetRawValue (evalOptions);
					if (arguments.Contains ("--debugger-agent"))
						return false;

					// Create the new debug session
					Subprocess sp;
					lock (subprocessesStarting) {
						sp = new Subprocess (GetId (thread), this);
						subprocessesStarting.Add (sp);
					}

					if (sp.CreateSession (startInfo, evalOptions)) {
						// Notify that the new session has started
						OnSubprocessStarted (sp.SubprocessSession);
					}
				}
				return true;
			} else if (b.CustomActionId == SetProcessIdMarker) {

				// A call to SetProcessId has been intercepted
				// Check if there is a subprocess waiting for the start signal

				var tid = GetId (thread);
				Subprocess subprocess;

				lock (subprocessesStarting)
					subprocess  = subprocessesStarting.FirstOrDefault (s => s.ThreadId == tid);

				if (subprocess != null) {
					lock (subprocessesStarting)
						subprocessesStarting.Remove (subprocess);

					var fr = thread.GetFrames ()[0];
					var ctx = new SoftEvaluationContext (this, fr, evalOptions);
					var eval = ctx.Evaluator;

					try {
						// The first parameter is the process ID
						var parameters = eval.GetParameters (ctx);
						var id = (int)parameters.First ().GetRawValue (evalOptions);

						// Get the start info object from the process
						var ts = eval.GetThisReference (ctx);
						var si = ts.GetChild ("startInfo", evalOptions);

						// Tell the subprocess that the process has started. This will finish the initialization
						// of the debug session.
						subprocess.SetStarted (si, id, ctx);
					} catch {
						subprocess.Shutdown ();
						throw;
					}
				}
				return true;
			}
			return false;
		}

		List<Subprocess> subprocessesStarting = new List<Subprocess> ();

		public Dictionary<Tuple<TypeMirror, string>, MethodMirror[]> OverloadResolveCache {
			get {
				return overloadResolveCache;
			}
		}
		
		void HideConnectionDialog ()
		{
			if (connectionDialog != null) {
				connectionDialog.Dispose ();
				connectionDialog = null;
			}
		}
		
		/// <summary>
		/// If subclasses do an async connect in OnRun, they should pass the resulting VM to this method.
		/// If the vm is null, the session will be closed.
		/// </summary>
		void ConnectionStarted (VirtualMachine machine)
		{
			if (vm != null)
				throw new InvalidOperationException ("The VM has already connected");
			
			if (machine == null) {
				EndSession ();
				return;
			}
			
			connection = null;
			
			vm = machine;

			// Allocate the process list now, so it is cached and can be queried while the session is running
			OnGetProcesses ();

			ConnectOutput (machine.StandardOutput, false);
			ConnectOutput (machine.StandardError, true);
			
			HideConnectionDialog ();
			
			machine.EnableEvents (EventType.AssemblyLoad, EventType.ThreadStart, EventType.ThreadDeath,
				EventType.AppDomainUnload, EventType.UserBreak, EventType.UserLog);
			try {
				unhandledExceptionRequest = machine.CreateExceptionRequest (null, false, true);
				unhandledExceptionRequest.Enable ();
			} catch (NotSupportedException) {
				//Mono < 2.6.3 doesn't support catching unhandled exceptions
			}

			if (machine.Version.AtLeast (2, 9)) {
				/* Created later */
			} else {
				machine.EnableEvents (EventType.TypeLoad);
			}
			

			machine.EnableEvents (EventType.MethodUpdate);

			started = true;
			
			/* Wait for the VMStart event */
			HandleEventSet (machine.GetNextEventSet ());
			
			eventHandler = new Thread (EventHandler);
			eventHandler.Name = "SDB Event Handler";
			eventHandler.IsBackground = true;
			eventHandler.Start ();
		}
		
		void RegisterUserAssemblies (SoftDebuggerStartInfo dsi)
		{
			if (Options.ProjectAssembliesOnly && dsi.UserAssemblyNames != null) {
				assemblyFilters = new List<AssemblyMirror> ();
				userAssemblyNames = dsi.UserAssemblyNames.Select (x => x.ToString ()).ToList ();
			}
			
			assemblyPathMap = dsi.AssemblyPathMap;
			if (assemblyPathMap == null)
				assemblyPathMap = new Dictionary<string, string> ();

			if (dsi.SymbolPathMap == null)
				symbolPathMap = new Dictionary<string, string>();
			else
				symbolPathMap = dsi.SymbolPathMap;
		}

		public void AddOrReplaceAssemblyPathMap(string assembly, string path)
		{
			assemblyPathMap[assembly] = path;
		}

		public void AddOrReplaceSymbolPathMap (string assembly, string path)
		{
			symbolPathMap[assembly] = path;
		}

		protected bool SetSocketTimeouts (int sendTimeout, int receiveTimeout, int keepaliveInterval)
		{
			try {
				if (vm.Version.AtLeast (2, 4)) {
					vm.EnableEvents (EventType.KeepAlive);
					vm.SetSocketTimeouts (sendTimeout, receiveTimeout, keepaliveInterval);
					return true;
				}

				return false;
			} catch {
				return false;
			}
		}

		protected void ConnectOutput (StreamReader reader, bool error)
		{
			Thread t = (error ? errorReader : outputReader);
			if (t != null || reader == null)
				return;

			t = new Thread (() => ReadOutput (reader, error));
			t.Name = error ? "SDB error reader" : "SDB output reader";
			t.IsBackground = true;
			t.Start ();

			if (error)
				errorReader = t;	
			else
				outputReader = t;
		}

		void ReadOutput (TextReader reader, bool isError)
		{
			try {
				var buffer = new char [1024];
				while (!HasExited) {
					int c = reader.Read (buffer, 0, buffer.Length);
					if (c > 0) {
						OnTargetOutput (isError, new string (buffer, 0, c));
					} else {
						//FIXME: workaround for buggy console stream that never blocks
						Thread.Sleep (250);
					}
				}
			} catch (IOException) {
				// Ignore
			}
		}

		protected virtual void OnResumed ()
		{
			current_threads = null;
			current_thread = null;
			activeExceptionsByThread.Clear ();
		}
		
		public VirtualMachine VirtualMachine {
			get { return vm; }
		}
		
		public TypeMirror GetType (string fullName)
		{
			List<TypeMirror> typesList;

			if (!types.TryGetValue (fullName, out typesList))
				aliases.TryGetValue (fullName, out typesList);
			if (typesList == null)
				return null;
			if (typesList.Count == 1)
				return typesList [0];
			//Idea here is... If we have multiple types with same name... they must be in different .dlls
			//so find 1st matching assembly with stackframes and then return type that belongs to that assembly
			var assembly = current_thread.GetFrames ().Select (f => f.Method.DeclaringType.Assembly).FirstOrDefault (asm => typesList.Select (t => t.Assembly).Contains (asm));
			return typesList.FirstOrDefault (t => t.Assembly == assembly) ?? typesList.FirstOrDefault ();
		}

		public IEnumerable<TypeMirror> GetAllTypes ()
		{
			return types.Values.SelectMany (l => l);
		}

		protected override bool AllowBreakEventChanges {
			get { return true; }
		}

		public override void Dispose ()
		{
			base.Dispose ();

			if (disposed)
				return;

			disposed = true;

			lock (subprocessesStarting) {
				foreach (var s in subprocessesStarting)
					s.Shutdown ();
			}

			if (!HasExited)
				EndLaunch ();

			exceptionRequests.Clear();

			if (!HasExited) {
				if (vm != null) {
					ThreadPool.QueueUserWorkItem (delegate {
						try {
							vm.Exit (0);
						} catch (VMDisconnectedException) {
						} catch (Exception ex) {
							DebuggerLoggingService.LogError ("Error exiting SDB VM:", ex);
						}
					});
				}
			}

			Adaptor.Dispose ();
		}

		protected override void OnAttachToProcess (long processId)
		{
			throw new NotSupportedException ();
		}

		protected override void OnContinue ()
		{
			ThreadPool.QueueUserWorkItem (delegate {
				try {
					Adaptor.CancelAsyncOperations (); // This call can block, so it has to run in background thread to avoid keeping the main session lock
					OnResumed ();
					vm.Resume ();
					DequeueEventsForFirstThread ();
				} catch (Exception ex) {
					if (!HandleException (ex) && outputOptions.ExceptionMessage)
						OnDebuggerOutput (true, ex.ToString ());
				}
			});
		}

		protected override void OnDetach ()
		{
			vm.Detach ();
		}

		protected override void OnExit ()
		{
			HasExited = true;
			EndLaunch ();
			if (vm != null) {
				try {
					vm.Exit (0);
				} catch (VMDisconnectedException) {
					// The VM was already disconnected, ignore.
				} catch (SocketException se) {
					// This will often happen during normal operation
					DebuggerLoggingService.LogError ("Error closing debugger session", se);
				} catch (IOException ex) {
					// This will often happen during normal operation
					DebuggerLoggingService.LogError ("Error closing debugger session", ex);
				}
			}
			QueueEnsureExited ();
		}
		
		void QueueEnsureExited ()
		{
			if (vm != null) {
				//FIXME: this might never get reached if the IDE is Exited first
				try {
					if (vm.Process != null) {
						ThreadPool.QueueUserWorkItem (delegate {
							// This is a workaround for a mono bug
							// Without this call, the process may become zombie in mono < 2.10.2
							vm.Process.WaitForExit ();
						});
					}
				} catch (InvalidOperationException) {
					// ignore - this is thrown by the vm.Process getter when the process has already exited
				} catch (Exception ex) {
					DebuggerLoggingService.LogError ("Failed to launch a thread to wait for the process to exit", ex);
				}

				var t = new System.Timers.Timer ();
				t.Interval = 3000;
				t.Elapsed += delegate {
					try {
						t.Enabled = false;
						t.Dispose ();
						EnsureExited ();
					} catch (Exception ex) {
						DebuggerLoggingService.LogError ("Failed to force-terminate process", ex);
					}

					try {
						if (vm != null) {
							//this is a no-op if it already closed
							vm.ForceDisconnect ();
						}
					} catch (Exception ex) {
						DebuggerLoggingService.LogError ("Failed to force-close debugger connection", ex);
					}
				};

				t.Enabled = true;
			}	
		}
		
		/// <summary>This is a fallback in case the debugger agent doesn't respond to an exit call</summary>
		protected virtual void EnsureExited ()
		{
			try {
				if (vm != null && vm.TargetProcess != null && !vm.TargetProcess.HasExited)
					vm.TargetProcess.Kill ();
			} catch (Exception ex) {
				DebuggerLoggingService.LogError ("Error force-terminating soft debugger process", ex);
			}
		}

		protected override void OnFinish ()
		{
			Step (StepDepth.Out, StepSize.Line);
		}

		protected override ProcessInfo[] OnGetProcesses ()
		{
			if (procs == null) {
				if (vm == null)//process didn't start yet
					return new ProcessInfo [0];
				if (vm.TargetProcess == null) {
					procs = new [] { new ProcessInfo (0, remoteProcessName ?? "mono") };
				} else {
					try {
						procs = new [] { new ProcessInfo (vm.TargetProcess.Id, remoteProcessName ?? vm.TargetProcess.ProcessName) };
					} catch (Exception ex) {
						if (!loggedSymlinkedRuntimesBug) {
							loggedSymlinkedRuntimesBug = true;
							DebuggerLoggingService.LogError ("Error getting debugger process info. Known Mono bug with symlinked runtimes.", ex);
						}
						procs = new [] { new ProcessInfo (0, "mono") };
					}
				}
			}
			return new [] { new ProcessInfo (procs[0].Id, procs[0].Name) };
		}

		internal PortablePdbData GetPdbData (AssemblyMirror asm)
		{
			string pdbFileName;
			if (!symbolPathMap.TryGetValue(asm.GetName().FullName, out pdbFileName) || Path.GetExtension(pdbFileName) != ".pdb")
			{
				string assemblyFileName;
				if (!assemblyPathMap.TryGetValue (asm.GetName ().FullName, out assemblyFileName))
					assemblyFileName = asm.Location;
				pdbFileName = Path.ChangeExtension (assemblyFileName, ".pdb");
			}
			if (PortablePdbData.IsPortablePdb (pdbFileName))
				return new PortablePdbData (pdbFileName);
			// Attempt to fetch pdb from the debuggee over the wire
			var pdbBlob = asm.GetPdbBlob ();
			return pdbBlob != null ? new PortablePdbData (pdbBlob) : null;
		}

		internal PortablePdbData GetPdbData (MethodMirror method)
		{
			return GetPdbData (method.DeclaringType.Assembly);
		}

		readonly Dictionary<AssemblyMirror, SourceLinkMap []> SourceLinkCache = new Dictionary<AssemblyMirror, SourceLinkMap []> ();
		SourceLinkMap [] GetSourceLinkMaps (MethodMirror method)
		{
			var asm = method.DeclaringType.Assembly;
			SourceLinkMap[] maps;

			lock (SourceLinkCache) {
				if (SourceLinkCache.TryGetValue (asm, out maps))
					return maps;
			}

			string jsonString = null;

			if (asm.VirtualMachine.Version.AtLeast (2, 48)) {
				jsonString = asm.ManifestModule.SourceLink;
			} else {
				// Read the pdb ourselves
				jsonString = GetPdbData (asm)?.GetSourceLinkBlob ();
			}

			if (!string.IsNullOrWhiteSpace(jsonString)) {
				try {
					var jsonSourceLink = JsonConvert.DeserializeObject<JsonSourceLink> (jsonString);

					if (jsonSourceLink != null && jsonSourceLink.Maps != null && jsonSourceLink.Maps.Any ())
						maps = jsonSourceLink.Maps.Select (kv => new SourceLinkMap (kv.Key, kv.Value)).ToArray ();
				} catch (JsonException ex) {
					DebuggerLoggingService.LogError ("Error reading source link", ex);
				}
			}

			lock (SourceLinkCache) {
				SourceLinkCache[asm] = maps ?? Array.Empty<SourceLinkMap> ();
			}

			return maps;
		}

		internal SourceLink GetSourceLink (MethodMirror method, string originalFileName)
		{
			if (originalFileName == null)
				return null;

			var maps = GetSourceLinkMaps (method);
			if (maps == null || maps.Length == 0)
				return null;

			originalFileName = originalFileName.Replace ('\\', '/');
			foreach (var map in maps) {
				var pattern = map.RelativePathWildcard.Replace ("*", "").Replace ('\\', '/');

				if (originalFileName.StartsWith (pattern, StringComparison.Ordinal)) {
					var localPath = originalFileName.Replace (pattern.Replace (".*", ""), "");
					var httpBasePath = map.UriWildcard.Replace ("*", "");
					// org/project-name/git-sha (usually)
					var pathAndQuery = new Uri (httpBasePath).GetComponents (UriComponents.Path, UriFormat.SafeUnescaped);
					// org/projectname/git-sha/path/to/file.cs
					var relativePath = Path.Combine (pathAndQuery, localPath);
					// Replace something like "f:/build/*" with "https://raw.githubusercontent.com/org/projectname/git-sha/*"
					var httpPath = Regex.Replace (originalFileName, pattern, httpBasePath);
					return new SourceLink (httpPath, relativePath);
				}
			}
			return null;
		}

		protected override Backtrace OnGetThreadBacktrace (long processId, long threadId)
		{
			return GetThreadBacktrace (GetThread (threadId));
		}

		protected override long OnGetElapsedTime (long processId, long threadId)
		{
			return GetElapsedTime (GetThread (threadId));
		}

		Backtrace GetThreadBacktrace (ThreadMirror thread)
		{
			return new Backtrace (new SoftDebuggerBacktrace (this, thread));
		}

		long GetElapsedTime (ThreadMirror thread)
		{
			return thread.ElapsedTime ();
		}

		string GetThreadName (ThreadMirror t)
		{
			string name = t.Name;
			if (string.IsNullOrEmpty (name)) {
				try {
					if (t.IsThreadPoolThread)
						return "<Thread Pool>";
				} catch {
					if (vm.Version.AtLeast (2, 2)) {
						throw;
					}
					return "<Thread>";
				}
			}
			return name;
		}

		protected override void OnFetchFrames (ThreadInfo [] threads)
		{
			var mirrorThreads = new List<ThreadMirror> (threads.Length);
			for (int i = 0; i < threads.Length; i++) {
				var thread = GetThread (threads [i].Id);
				if (thread != null) {
					mirrorThreads.Add (thread);
				}
			}
			ThreadMirror.FetchFrames (mirrorThreads);
		}

		protected override ThreadInfo[] OnGetThreads (long processId)
		{
			if (current_threads == null) {
				var mirrors = vm.GetThreads ();
				var threads = new ThreadInfo[mirrors.Count];

				for (int i = 0; i < mirrors.Count; i++) {
					var thread = mirrors[i];

					threads[i] = new ThreadInfo (processId, GetId (thread), GetThreadName (thread), null);
				}

				current_threads = threads;
			}

			return current_threads;
		}
		
		ThreadMirror GetThread (long threadId)
		{
			foreach (var thread in vm.GetThreads ()) {
				if (GetId (thread) == threadId)
					return thread;
			}

			return null;
		}
		
		ThreadInfo GetThread (ProcessInfo process, ThreadMirror thread)
		{
			long id = GetId (thread);

			foreach (var threadInfo in OnGetThreads (process.Id)) {
				if (threadInfo.Id == id)
					return threadInfo;
			}

			return null;
		}

		public override bool CanSetNextStatement {
			get { return vm.Version.AtLeast (2, 29); }
		}

		protected override void OnSetNextStatement (long threadId, string fileName, int line, int column)
		{
			if (!CanSetNextStatement)
				throw new NotSupportedException ();

			var thread = GetThread (threadId);
			if (thread == null)
				throw new ArgumentException ("Unknown thread.");

			var frames = thread.GetFrames ();
			if (frames.Length == 0)
				throw new NotSupportedException ();

			bool dummy = false;
			var location = FindLocationByMethod (frames[0].Method, fileName, line, column, ref dummy);
			if (location == null)
				throw new NotSupportedException ("Unable to set the next statement. The next statement cannot be set to another function.");
			try {
				thread.SetIP (location);
				currentAddress = location.ILOffset;
				currentStackDepth = frames.Length;
			} catch (ArgumentException) {
				throw new NotSupportedException ();
			}
		}

		protected override void OnSetNextStatement (long threadId, int ilOffset)
		{
			if (!CanSetNextStatement)
				throw new NotSupportedException ();

			var thread = GetThread (threadId);
			if (thread == null)
				throw new ArgumentException ("Unknown thread.");

			var frames = thread.GetFrames ();
			if (frames.Length == 0)
				throw new NotSupportedException ();

			var location = frames[0].Method.LocationAtILOffset (ilOffset);
			if (location == null)
				throw new NotSupportedException ();

			try {
				thread.SetIP (location);
				StackVersion++;
				RaiseStopEvent ();
			} catch (ArgumentException) {
				throw new NotSupportedException ();
			}
		}
		
		protected override BreakEventInfo OnInsertBreakEvent (BreakEvent breakEvent)
		{
			var breakInfo = new BreakInfo ();

			if (HasExited) {
				breakInfo.SetStatus (BreakEventStatus.Disconnected, null);
				return breakInfo;
			}

			if (breakEvent is FunctionBreakpoint function) {
				foreach (var method in FindMethodsByName (function.FunctionName, function.ParamTypes)) {
					if (!ResolveFunctionBreakpoint (breakInfo, function, method)) {
						breakInfo.SetStatus (BreakEventStatus.NotBound, null);
					}
				}

				// FIXME: handle types like GenericType<>, GenericType<SomeOtherType>, and GenericType<...>+NestedGenricType<...>
				var openParen = function.FunctionName.IndexOf ('(');
				int dot;

				if (openParen != -1) {
					//Handle stuff like SomeNamespace.SomeType.Method(SomeOtherNamespace.SomeOtherType)
					dot = function.FunctionName.LastIndexOf ('.', openParen);
				} else {
					dot = function.FunctionName.LastIndexOf ('.');
				}
				if (dot != -1)
					breakInfo.TypeName = function.FunctionName.Substring (0, dot);

				lock (pending_bes) {
					pending_bes.Add (breakInfo);
				}
			} else if (breakEvent is InstructionBreakpoint instruction) {
				Location location;

				breakInfo.FileName = instruction.FileName;

				if ((location = FindLocationByILOffset (instruction, instruction.FileName, out _, out var insideTypeRange)) != null) {
					breakInfo.Location = location;
					InsertBreakpoint (instruction, breakInfo);
					breakInfo.SetStatus (BreakEventStatus.Bound, null);
				} else if (insideTypeRange)
					breakInfo.SetStatus (BreakEventStatus.Invalid, null);
				else
					breakInfo.SetStatus (BreakEventStatus.NotBound, null);

				lock (pending_bes) {
					pending_bes.Add (breakInfo);
				}
			} else if (breakEvent is Breakpoint breakpoint) {
				bool insideLoadedRange;
				bool found = false;

				breakInfo.FileName = breakpoint.FileName;

				foreach (var location in FindLocationsByFile (breakpoint.FileName, breakpoint.Line, breakpoint.Column, out _, out insideLoadedRange)) {
					OnDebuggerOutput (false, string.Format ("Resolved pending breakpoint at '{0}:{1},{2}' to {3} [0x{4:x5}].\n",
					                                        breakpoint.FileName, breakpoint.Line, breakpoint.Column,
															GetPrettyMethodName (location.Method), location.ILOffset));

					breakInfo.Location = location;
					InsertBreakpoint (breakpoint, breakInfo);
					found = true;
					breakInfo.SetStatus (BreakEventStatus.Bound, null);
				}
				lock (pending_bes) {
					pending_bes.Add (breakInfo);
				}

				if (!found) {
					breakInfo.Breakpoint = breakpoint;
					if (insideLoadedRange)
						breakInfo.SetStatus (BreakEventStatus.Invalid, null);
					else
						breakInfo.SetStatus (BreakEventStatus.NotBound, null);
				}
			} else if (breakEvent is Catchpoint catchpoint) {
				if (!types.ContainsKey (catchpoint.ExceptionName)) {
					//
					// Same as in FindLocationByFile (), fetch types matching the type name
					if (vm.Version.AtLeast (2, 9)) {
						foreach (TypeMirror t in vm.GetTypes (catchpoint.ExceptionName, false))
							ProcessType (t);
					}
				}

				List<TypeMirror> typesList;
				if (types.TryGetValue (catchpoint.ExceptionName, out typesList)) {
					foreach (var type in typesList)
						InsertCatchpoint (catchpoint, breakInfo, type);
					breakInfo.SetStatus (BreakEventStatus.Bound, null);
				} else {
					breakInfo.SetStatus (BreakEventStatus.NotBound, null);
				}

				breakInfo.TypeName = catchpoint.ExceptionName;
				lock (pending_bes) {
					pending_bes.Add (breakInfo);
				}
			}
			UpdateTypeLoadFilters ();
			return breakInfo;
		}

		void UpdateTypeLoadFilters()
		{
			/*
			 * TypeLoad events lead to too much wire traffic + suspend/resume work, so
			 * filter them using the file names used by pending breakpoints.
			 */
			if (vm.Version.AtLeast (2, 9)) {
				string [] sourceFileList;
				lock (pending_bes) {
					sourceFileList = pending_bes.Where (b => b.FileName != null).SelectMany ((b, i) => new [] {
					Path.GetFileName (b.FileName),
					b.FileName
					}).Distinct ().ToArray ();
				}
				if (sourceFileList.Length > 0) {
					//HACK: with older versions of sdb that don't support case-insenitive compares,
					//explicitly try lowercased drivename on windows, since csc (when not hosted in VS) lowercases
					//the drivename in the pdb files that get converted to mdbs as-is
					if (IsWindows && !vm.Version.AtLeast (2, 12)) {
						int originalCount = sourceFileList.Length;
						Array.Resize (ref sourceFileList, originalCount * 2);
						for (int i = 0; i < originalCount; i++) {
							string n = sourceFileList[i];
							sourceFileList[originalCount + i] = char.ToLower (n[0]) + n.Substring (1);
						}
					}

					if (typeLoadReq == null) {
						typeLoadReq = vm.CreateTypeLoadRequest ();
					}
					typeLoadReq.Enabled = false;
					typeLoadReq.SourceFileFilter = sourceFileList;
					typeLoadReq.Enabled = true;
				}

				string [] typeNameList;
				lock (pending_bes) {
					typeNameList = pending_bes.Where (b => b.TypeName != null).Select (b => b.TypeName).ToArray ();
				}
				if (typeNameList.Length > 0) {
					// Use a separate request since the filters are ANDed together
					if (typeLoadTypeNameReq == null) {
						typeLoadTypeNameReq = vm.CreateTypeLoadRequest ();
					}
					typeLoadTypeNameReq.Enabled = false;
					typeLoadTypeNameReq.TypeNameFilter = typeNameList;
					typeLoadTypeNameReq.Enabled = true;
				}
			}
		}

		private Location FindLocationByILOffset (InstructionBreakpoint bp, string filename, out bool isGeneric, out bool insideTypeRange)
		{
			var typesInFile = new List<TypeMirror> ();

			AddFileToSourceMapping (filename);

			insideTypeRange = true;
			isGeneric = false;

			lock (source_to_type) {
				if (source_to_type.TryGetValue (filename, out typesInFile)) {
					foreach (var type in typesInFile) {
						var method = type.GetMethod (bp.MethodName);
						if (method != null) {
							foreach (var location in method.Locations) {
								if (location.ILOffset == bp.ILOffset) {
									isGeneric = type.IsGenericType;
									return location;
								}
							}
						}
					}
				}
			}

			return null;
		}

		protected override void OnRemoveBreakEvent (BreakEventInfo eventInfo)
		{
			if (HasExited)
				return;

			var bi = (BreakInfo) eventInfo;
			if (bi.Requests.Count != 0) {
				foreach (var request in bi.Requests.Keys) {
					request.Enabled = false;
					breakpoints.Remove (request);
				}

				RemoveQueuedBreakEvents (bi.Requests);
			}

			lock (pending_bes) {
				pending_bes.Remove (bi);
			}
		}

		protected override void OnEnableBreakEvent (BreakEventInfo eventInfo, bool enable)
		{
			if (HasExited)
				return;
			
			var bi = (BreakInfo) eventInfo;
			if (bi.Requests.Count != 0) {
				foreach (var request in bi.Requests.Keys)
					request.Enabled = enable;

				if (!enable)
					RemoveQueuedBreakEvents (bi.Requests);
			}
		}

		protected override void OnUpdateBreakEvent (BreakEventInfo eventInfo)
		{
		}

		void InsertBreakpoint (Breakpoint bp, BreakInfo bi)
		{
			InsertBreakpoint (bp, bi, bi.Location.Method, bi.Location.ILOffset);
		}

		void UpdateBreakpoint (Breakpoint bp, BreakInfo bi)
		{
			foreach (var req in bi.Requests)
			{
				req.Key.Disable ();
				var request = vm.SetBreakpoint (bi.Location.Method, bi.Location.ILOffset);
				req.Key.UpdateReqId (request.GetId());
				req.Key.Enabled = bp.Enabled;
			}
		}

		void InsertBreakpoint (Breakpoint bp, BreakInfo bi, MethodMirror method, int ilOffset)
		{
			EventRequest request;

			request = vm.SetBreakpoint (method, ilOffset);
			request.Enabled = bp.Enabled;
			bi.Requests.Add (request, method.DeclaringType.Assembly);

			breakpoints [request] = bi;

			if (bi.Location != null && (bi.Location.LineNumber != bp.Line || bi.Location.ColumnNumber != bp.Column))
				bi.AdjustBreakpointLocation (bi.Location.LineNumber, bi.Location.ColumnNumber);
		}
		
		void InsertCatchpoint (Catchpoint cp, BreakInfo bi, TypeMirror excType)
		{
			ExceptionEventRequest request;

			request = vm.CreateExceptionRequest (excType, true, true);
			//Commenting Count so we have better control of counting
			//because VM only allows count equal to some number but we need also
			//lower, greater, equal or greater...
			//Plus some day we might want to put filtering before counting...
			//request.Count = cp.HitCount; // Note: need to set HitCount *before* enabling
			if (vm.Version.AtLeast (2, 25))
				request.IncludeSubclasses = cp.IncludeSubclasses; // Note: need to set IncludeSubclasses *before* enabling
			request.Enabled = cp.Enabled;
			bi.Requests.Add (request, excType.Assembly);

			breakpoints[request] = bi;
		}

		#region ExceptionRequest
		//VS in Windows doesn't have the concept of a Catchpoint. In the past we did use it anyway, but that leads to all sort of issues and bugs.
		//The most important difference is that subclasses are never caught, and that Others is a concept that the Catchpoint doesn't support properly.
		//This region is for Windows, to be able to properly handle exceptions with an exception list. The concept of Other is supported starting with vm version 2.54.

		readonly Dictionary<string, ExceptionEventRequest> exceptionRequests = new Dictionary<string, ExceptionEventRequest>();
		ExceptionEventRequest otherExceptions;

		public void EnableException(string exceptionType, bool caught = true)
		{
			lock (exceptionRequests) {
				if (!types.ContainsKey (exceptionType)) {
					if (vm.Version.AtLeast (2, 9)) {
						try {
							foreach (TypeMirror t in vm.GetTypes (exceptionType, false))
								ProcessType (t);
						}
						catch (CommandException exc) {
							if (outputOptions.ExceptionMessage)
								OnDebuggerOutput (false, string.Format ("Error while parsing type ‘{0}’.\n", exceptionType));
						}
					}
				}

				if (types.TryGetValue(exceptionType, out var typemirrors)) { 
					var exception = typemirrors.First();
					var request = vm.CreateExceptionRequest (exception, caught, true, false);
					request.Enable();
					exceptionRequests[exceptionType] = request;
				}
			}
		}

		public void EnableOtherExceptions()
		{
			if (!vm.Version.AtLeast(2, 54))
				return;

			if (otherExceptions == null)
				otherExceptions = vm.CreateExceptionRequest (null, true, true, true);
			otherExceptions.Enable ();
		}

		public void DisableException(string exceptionType, bool setuncaught = true)
		{
			lock (exceptionRequests) {
				if (exceptionRequests.TryGetValue (exceptionType, out var request)) {
					request.Disable();
					exceptionRequests.Remove(exceptionType);
				}
				if (setuncaught)
					EnableException (exceptionType, false);
			}
		}

		public void DisableOtherExceptions()
		{
			if (otherExceptions != null) {
				otherExceptions.Disable();
			}
		}

		public void RemoveException(string exceptionType)
		{
			DisableException(exceptionType, false);
		}

		#endregion

		static bool CheckTypeName (string typeName, string name)
		{
			// if the name provided is empty, it matches anything.
			if (string.IsNullOrEmpty (name))
				return true;

			if (name.StartsWith ("global::", StringComparison.Ordinal)) {
				if (typeName != name.Substring ("global::".Length))
					return false;
			} else if (name.StartsWith ("::", StringComparison.Ordinal)) {
				if (typeName != name.Substring ("::".Length))
					return false;
			} else {
				// be a little more flexible with what we match... i.e. "Console" should match "System.Console"
				if (typeName != null && typeName.Length > name.Length) {
					if (!typeName.EndsWith (name, StringComparison.Ordinal))
						return false;

					char delim = typeName[typeName.Length - name.Length];
					if (delim != '.' && delim != '+')
						return false;
				} else if (typeName != name) {
					return false;
				}
			}

			return true;
		}

		static bool CheckTypeName (TypeMirror type, string name)
		{
			if (string.IsNullOrEmpty (name)) {
				// empty name matches anything
				return true;
			}

			if (name[name.Length - 1] == '?') {
				// canonicalize the user-specified nullable type
				return CheckTypeName (type, string.Format ("System.Nullable<{0}>", name.Substring (0, name.Length - 1)));
			}

			if (type.IsArray) {
				int startIndex = name.LastIndexOf ('[');
				int endIndex = name.Length - 1;

				if (startIndex == -1 || name[endIndex] != ']') {
					// the user-specified type is not an array
					return false;
				}

				var rank = name.Substring (startIndex + 1, endIndex - (startIndex + 1)).Split (new [] { ',' });
				if (rank.Length != type.GetArrayRank ())
					return false;

				return CheckTypeName (type.GetElementType (), name.Substring (0, startIndex).TrimEnd ());
			}

			if (type.IsPointer) {
				if (name.Length < 2 || name[name.Length - 1] != '*')
					return false;

				return CheckTypeName (type.GetElementType (), name.Substring (0, name.Length - 1).TrimEnd ());
			}

			if (type.IsGenericType) {
				int startIndex = name.IndexOf ('<');
				int endIndex = name.Length - 1;

				if (startIndex == -1 || name[endIndex] != '>') {
					// the user-specified type is not a generic type
					return false;
				}

				// make sure that the type name matches (minus generics)
				string subName = name.Substring (0, startIndex);
				string typeName = type.FullName;
				int tick;

				if ((tick = typeName.IndexOf ('`')) != -1)
					typeName = typeName.Substring (0, tick);

				if (!CheckTypeName (typeName, subName))
					return false;

				string[] paramTypes;
				if (!FunctionBreakpoint.TryParseParameters (name, startIndex + 1, endIndex, out paramTypes))
					return false;

				TypeMirror[] argTypes = type.GetGenericArguments ();
				if (paramTypes.Length != argTypes.Length)
					return false;

				for (int i = 0; i < paramTypes.Length; i++) {
					if (!CheckTypeName (argTypes[i], paramTypes[i]))
						return false;
				}
			} else if (!CheckTypeName (type.CSharpName, name)) {
				if (!CheckTypeName (type.FullName, name))
					return false;
			}

			return true;
		}

		static bool CheckMethodParams (MethodMirror method, string[] paramTypes)
		{
			if (paramTypes == null) {
				// User supplied no params to match against, match anything we find.
				return true;
			}

			var parameters = method.GetParameters ();
			if (parameters.Length != paramTypes.Length)
				return false;

			for (int i = 0; i < paramTypes.Length; i++) {
				if (!CheckTypeName (parameters[i].ParameterType, paramTypes[i]))
					return false;
			}

			return true;
		}
		
		bool IsGenericMethod (MethodMirror method)
		{
			return vm.Version.AtLeast (2, 12) && method.IsGenericMethod;
		}

		//If paramType == null all overloads are returned
		IEnumerable<MethodMirror> FindMethodsByName (string function, string[] paramTypes)
		{
			if (!started)
				yield break;
			
			if (vm.Version.AtLeast (2, 9)) {
				var bracket = function.IndexOf ('(');
				int dot;
				if (bracket != -1) {
					//Handle stuff like SomeNamespace.SomeType.Method(SomeOtherNamespace.SomeOtherType)
					dot = function.LastIndexOf ('.', bracket);
				} else {
					dot = function.LastIndexOf ('.');
				}
				if (dot == -1 || dot + 1 == function.Length)
					yield break;

				// FIXME: handle types like GenericType<>, GenericType<SomeOtherType>, and GenericType<...>+NestedGenricType<...>
				string methodName;
				string typeName = function.Substring (0, dot);
				if (bracket == -1) {
					methodName = function.Substring (dot + 1);
				} else {
					methodName = function.Substring (dot + 1, bracket - (dot + 1));
				}

				// FIXME: need a way of querying all types so we can substring match typeName (e.g. user may have typed "Console" instead of "System.Console")
				foreach (var type in vm.GetTypes (typeName, false)) {
					ProcessType (type);
					
					foreach (var method in type.GetMethodsByNameFlags (methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, false)) {
						if (!CheckMethodParams (method, paramTypes))
							continue;
						
						yield return method;
					}
				}
			}
			
			yield break;
		}
		
		IList<Location> FindLocationsByFile (string file, int line, int column, out bool genericTypeOrMethod, out bool insideLoadedRange)
		{
			var locations = new List<Location> ();

			genericTypeOrMethod = false;
			insideLoadedRange = false;
			
			if (!started)
				return locations;

			var filename = Path.GetFileName (file);

			AddFileToSourceMapping (filename);

			lock (source_to_type) {
				// Try already loaded types in the current source file
				if (source_to_type.TryGetValue (filename, out var mirrors)) {
					foreach (var type in mirrors) {
						var location = FindLocationByType (type, file, line, column, out var genericMethod, out var insideRange);
						if (insideRange)
							insideLoadedRange = true;

						if (location != null) {
							if (genericMethod || type.IsGenericType)
								genericTypeOrMethod = true;

							locations.Add (location);
						}
					}
				}
			}

			return locations;
		}

		private void AddFileToSourceMapping (string filename)
		{
			//
			// Fetch types matching the source file from the debuggee, and add them
			// to the source file->type mapping tables.
			// This is needed because we don't receive type load events for all types,
			// just the ones which match a source file with an existing breakpoint.
			//
			if (vm.Version.AtLeast (2, 9)) {
				IList<TypeMirror> typesInFile;
				if (vm.Version.AtLeast (2, 12)) {
					typesInFile = vm.GetTypesForSourceFile (filename, IgnoreFilenameCase);
				} else {
					typesInFile = vm.GetTypesForSourceFile (filename, false);
					//HACK: with older versions of sdb that don't support case-insenitive compares,
					//explicitly try lowercased drivename on windows, since csc (when not hosted in VS) lowercases
					//the drivename in the pdb files that get converted to mdbs as-is
					if (typesInFile.Count == 0 && IsWindows) {
						string alternateCaseFilename = char.ToLower (filename [0]) + filename.Substring (1);
						typesInFile = vm.GetTypesForSourceFile (alternateCaseFilename, false);
					}
				}
				
				foreach (TypeMirror t in typesInFile)
					ProcessType (t);
			}
		}

		public override bool CanCancelAsyncEvaluations
		{
			get
			{
				return Adaptor.IsEvaluating;
			}
		}
		
		protected override void OnCancelAsyncEvaluations ()
		{
			Adaptor.CancelAsyncOperations ();
		}
		
		protected override void OnNextInstruction ()
		{
			Step (StepDepth.Over, StepSize.Min);
		}

		protected override void OnNextLine ()
		{
			Step (StepDepth.Over, StepSize.Line);
		}

		void Step (StepDepth depth, StepSize size)
		{
			try {
				Adaptor.CancelAsyncOperations (); // This call can block, so it has to run in background thread to avoid keeping the main session lock
				var req = vm.CreateStepRequest (current_thread);
				req.Depth = depth;
				req.Size = size;
				req.Filter = ShouldFilterStaticCtor () | StepFilter.DebuggerHidden | StepFilter.DebuggerStepThrough;
				if (Options.ProjectAssembliesOnly)
					req.Filter |= StepFilter.DebuggerNonUserCode;
				if (assemblyFilters != null && assemblyFilters.Count > 0)
					req.AssemblyFilter = assemblyFilters;
				try {
					req.Enabled = true;
				} catch (NotSupportedException e) {
					if (vm.Version.AtLeast (2, 19)) //catch NotSupportedException thrown by old version of protocol
						throw e;
				}
				currentStepRequest = req;
				OnResumed ();
				vm.Resume ();
				DequeueEventsForFirstThread ();
			} catch (CommandException ex) {
				string reason;

				switch (ex.ErrorCode) {
				case ErrorCode.INVALID_FRAMEID: reason = "invalid frame id"; break;
				case ErrorCode.NOT_SUSPENDED: reason = "VM not suspended"; break;
				case ErrorCode.ERR_UNLOADED: reason = "AppDomain has been unloaded"; break;
				case ErrorCode.NO_SEQ_POINT_AT_IL_OFFSET: reason = "no sequence point at the specified IL offset"; break;
				default: reason = ex.ErrorCode.ToString (); break;
				}

				if (outputOptions.ExceptionMessage)
					OnDebuggerOutput (true, string.Format ("Step request failed: {0}.", reason));
				DebuggerLoggingService.LogError ("Step request failed", ex);
			} catch (Exception ex) {
				if (outputOptions.ExceptionMessage)
					OnDebuggerOutput(true, string.Format ("Step request failed: {0}", ex.Message));
				DebuggerLoggingService.LogError ("Step request failed", ex);
			}
		}

		private StepFilter ShouldFilterStaticCtor()
		{
			var frames = current_thread.GetFrames();
			return (frames.Any(f => f.Method.Name == ".cctor" && f.Method.IsSpecialName && f.Method.IsStatic))
				? StepFilter.None : StepFilter.StaticCtor;
		}

		void EventHandler ()
		{
			int? exit_code = null;

			while (true) {
				try {
					EventSet e = vm.GetNextEventSet ();
					var type = e[0].EventType;
					if (type == EventType.VMDeath || type == EventType.VMDisconnect) {
						if (type == EventType.VMDeath && vm.Version.AtLeast (2, 27)) {
							exit_code = ((VMDeathEvent) e[0]).ExitCode;
						}
						break;
					}
					HandleEventSet (e);
				} catch (Exception ex) {
					if (HasExited)
						break;

					if (!HandleException (ex) && outputOptions.ExceptionMessage)
						OnDebuggerOutput (true, ex.ToString ());

					if (ex is VMDisconnectedException || ex is IOException || ex is SocketException)
						break;
				}
			}
			
			try {
				// This is a workaround for a mono bug
				// Without this call, the process may become zombie in mono < 2.10.2
				if (vm.Process != null)
					vm.Process.WaitForExit (1);
			} catch (SystemException) {
			}

			OnTargetEvent (new TargetEventArgs (TargetEventType.TargetExited) {
				ExitCode = exit_code
			});
		}
		
		protected override bool HandleException (Exception ex)
		{
			HideConnectionDialog ();

			if (HasExited)
				return true;
			
			if (ex is VMDisconnectedException || ex is IOException) {
				ex = new DisconnectedException (ex);
				HasExited = true;
			} else if (ex is SocketException) {
				ex = new DebugSocketException (ex);
				HasExited = true;
			}
			
			return base.HandleException (ex);
		}

		void HandleEventSet (EventSet es)
		{
			var type = es[0].EventType;

#if DEBUG_EVENT_QUEUEING
			if (type != TypeLoadEvent)
				Console.WriteLine ("pp eventset({0}): {1}", es.Events.Length, es[0]);
#endif

			// If we are currently stopped on a thread, and the break events are on a different thread, we must queue
			// that event set and dequeue it next time we resume. This eliminates race conditions when multiple threads
			// hit breakpoints or catchpoints simultaneously.
			//
			bool isBreakEvent = type == EventType.Step || type == EventType.Breakpoint || type == EventType.Exception || type == EventType.UserBreak;
			if (isBreakEvent) {
				if (current_thread != null && es[0].Thread.Id != current_thread.Id) {
					QueueBreakEventSet (es.Events);
				} else {
					HandleBreakEventSet (es.Events, false);
				}
				return;
			}

			switch (type) {
			case EventType.AssemblyLoad:
				HandleAssemblyLoadEvents (Array.ConvertAll (es.Events, item => (AssemblyLoadEvent)item));
				break;
			case EventType.AppDomainUnload:
				HandleDomainUnloadEvents (Array.ConvertAll (es.Events, item => (AppDomainUnloadEvent)item));
				break;
			case EventType.VMStart:
				HandleVMStartEvents (Array.ConvertAll (es.Events, item => (VMStartEvent)item));
				break;
			case EventType.TypeLoad:
				HandleTypeLoadEvents (Array.ConvertAll (es.Events, item => (TypeLoadEvent)item));
				break;
			case EventType.ThreadStart:
				HandleThreadStartEvents (Array.ConvertAll (es.Events, item => (ThreadStartEvent)item));
				break;
			case EventType.ThreadDeath:
				HandleThreadDeathEvents (Array.ConvertAll (es.Events, item => (ThreadDeathEvent)item));
				break;
			case EventType.UserLog:
				HandleUserLogEvents (Array.ConvertAll (es.Events, item => (UserLogEvent)item));
				break;
			case EventType.MethodUpdate:
				HandleMethodUpdateEvents (Array.ConvertAll (es.Events, item => (MethodUpdateEvent)item));
				break;
			default:
				DebuggerLoggingService.LogMessage ("Ignoring unknown debugger event type {0}", type);
				break;
			}

			try {
				if (!vm.Version.AtLeast (2, 55) || es.SuspendPolicy != SuspendPolicy.None)
					vm.Resume ();
			} catch (VMNotSuspendedException) {
				if (type != EventType.VMStart && vm.Version.AtLeast (2, 2))
					throw;
			}
		}
		
		static bool IsStepIntoRequest (StepEventRequest stepRequest)
		{
			return stepRequest.Depth == StepDepth.Into;
		}
		
		static bool IsStepOutRequest (StepEventRequest stepRequest)
		{
			return stepRequest.Depth == StepDepth.Out;
		}
		
		static bool IsPropertyOrOperatorMethod (MethodMirror method)
		{
			string name = method.Name;
			
			return method.IsSpecialName &&
				(name.StartsWith ("get_", StringComparison.Ordinal) ||
				 name.StartsWith ("set_", StringComparison.Ordinal) ||
				 name.StartsWith ("op_", StringComparison.Ordinal));
		}

		static bool IsCompilerGenerated (MethodMirror method)
		{
			foreach (var attr in method.GetCustomAttributes(false)) {
				if (attr.Constructor.DeclaringType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute")
					return true;
			}
			return false;
		}

		bool IsUserAssembly (AssemblyMirror assembly)
		{
			if (userAssemblyNames == null)
				return true;

			var name = assembly.GetName ().FullName;

			foreach (var n in userAssemblyNames) {
				if (n == name)
					return true;
			}

			return false;
		}

		bool IsAutoGeneratedFrameworkEnumerator (TypeMirror type)
		{
			if (IsUserAssembly (type.Assembly))
				return false;

			if (!SoftDebuggerAdaptor.IsGeneratedType (type))
				return false;

			foreach (var iface in type.GetInterfaces ()) {
				if (iface.Namespace == "System.Collections" && iface.Name == "IEnumerator")
					return true;
			}

			return false;
		}

		bool StepThrough (MethodMirror method)
		{
			if (Options.ProjectAssembliesOnly && !IsUserAssembly (method.DeclaringType.Assembly))
				return true;

			//With Sdb 2.30 this logic was moved to Runtime no need to spend time on checking this
			if (!vm.Version.AtLeast (2, 30)) {
				if (vm.Version.AtLeast (2, 21)) {
					foreach (var attr in method.GetCustomAttributes (false)) {
						var attrName = attr.Constructor.DeclaringType.FullName;

						switch (attrName) {
						case "System.Diagnostics.DebuggerHiddenAttribute":
							return true;
						case "System.Diagnostics.DebuggerStepThroughAttribute":
							return true;
						case "System.Diagnostics.DebuggerNonUserCodeAttribute":
							return Options.ProjectAssembliesOnly;
						}
					}
				}

				if (Options.ProjectAssembliesOnly) {
					foreach (var attr in method.DeclaringType.GetCustomAttributes (false)) {
						var attrName = attr.Constructor.DeclaringType.FullName;

						if (attrName == "System.Diagnostics.DebuggerNonUserCodeAttribute")
							return Options.ProjectAssembliesOnly;
					}
				}
			}

			return false;
		}

		bool ContinueOnStepInto (MethodMirror method)
		{
			if (vm.Version.AtLeast (2, 21)) {
				foreach (var attr in method.GetCustomAttributes (false)) {
					var attrName = attr.Constructor.DeclaringType.FullName;

					if (attrName == "System.Diagnostics.DebuggerStepperBoundaryAttribute")
						return true;
				}
			}

			return false;
		}

		bool IgnoreBreakpoint (MethodMirror method)
		{
			if (vm.Version.AtLeast (2, 21)) {
				foreach (var attr in method.GetCustomAttributes (false)) {
					var attrName = attr.Constructor.DeclaringType.FullName;

					switch (attrName) {
					case "System.Diagnostics.DebuggerHiddenAttribute":      return true;
					case "System.Diagnostics.DebuggerStepThroughAttribute": return true;
					case "System.Diagnostics.DebuggerNonUserCodeAttribute": return Options.ProjectAssembliesOnly;
					case "System.Diagnostics.DebuggerStepperBoundaryAttribute": return true;
					}
				}
			}

			if (Options.ProjectAssembliesOnly) {
				foreach (var attr in method.DeclaringType.GetCustomAttributes (false)) {
					var attrName = attr.Constructor.DeclaringType.FullName;

					if (attrName == "System.Diagnostics.DebuggerNonUserCodeAttribute")
						return Options.ProjectAssembliesOnly;
				}
			}

			return false;
		}

		/// <summary>
		/// Checks all frames in thread where exception occured and if any frame has user code it returns true.
		/// Also notice that this method already check if Options.ProjectAssembliesOnly==false 
		/// </summary>
		bool ExceptionInUserCode (ExceptionEvent ev)
		{
			// this is just optimization to prevent need to fetch Frames
			if (Options.ProjectAssembliesOnly == false)
				return true;
			foreach (var frame in ev.Thread.GetFrames ()) {
				if (!IsExternalCode (frame))
					return true;
			}
			return false;
		}

		bool ShouldIgnore (ExceptionEvent ev)
		{
			BreakInfo binfo;
			if (!breakpoints.TryGetValue (ev.Request, out binfo))
				return false;

			var cp = binfo.BreakEvent as Catchpoint;
			if (cp == null)
				return false;

			var backtrace = GetThreadBacktrace (ev.Thread);
			if (backtrace.FrameCount == 0) {
				return cp.ShouldIgnore (ev.Exception.Type.FullName, null);
			} else {
				var frame = backtrace.GetFrame (0);
				return cp.ShouldIgnore (ev.Exception.Type.FullName, frame.GetLocationSignature ());
			}
		}

		void HandleBreakEventSet (Event[] es, bool dequeuing)
		{
			if (dequeuing && HasExited)
				return;

			TargetEventType etype = TargetEventType.TargetStopped;
			ObjectMirror exception = null;
			BreakEvent breakEvent = null;
			bool redoCurrentStep = false;
			bool steppedInto = false;
			bool steppedOut = false;
			bool resume = true;
			BreakInfo binfo;
			
			if (es [0].EventType == EventType.Exception) {
				var bad = es.FirstOrDefault (ee => ee.EventType != EventType.Exception);
				if (bad != null)
					throw new Exception ("Catchpoint eventset had unexpected event type " + bad.GetType ());
				var ev = (ExceptionEvent)es [0];
				exception = ev.Exception;
				if (ev.Request == unhandledExceptionRequest) {
					etype = TargetEventType.UnhandledException;
					if (exception.Type.FullName != "System.Threading.ThreadAbortException")
						resume = false;
				} else {
					// Set the exception for this thread so that CatchPoint Print message(tracing) of {$exception} works
					activeExceptionsByThread [es[0].Thread.ThreadId] = exception;
					if (ExceptionInUserCode(ev) && !ShouldIgnore(ev) && !HandleBreakpoint (es [0].Thread, ev.Request)) {
						etype = TargetEventType.ExceptionThrown;
						resume = false;
					}

					// Remove exception from the thread so that when the program stops due to stepFinished/programPause/breakPoint...
					// we don't have on out-dated exception(setting and unsetting few lines later is needed because it's used inside HandleBreakpoint)
					activeExceptionsByThread.Remove (es[0].Thread.ThreadId);

					// Get the breakEvent so that we can check if we should ignore it later
					if (breakpoints.TryGetValue (ev.Request, out binfo))
						breakEvent = binfo.BreakEvent;
				}
			} else {
				//always need to evaluate all breakpoints, some might be tracepoints or conditional bps with counters
				foreach (Event e in es) {
					if (e.EventType == EventType.Breakpoint) {
						var be = (BreakpointEvent) e;
						var hasBreakInfo = breakpoints.TryGetValue (be.Request, out binfo);

						if (!HandleBreakpoint (e.Thread, be.Request)) {
							etype = TargetEventType.TargetHitBreakpoint;
							autoStepInto = false;
							resume = false;
							if (hasBreakInfo)
								breakEvent = binfo.BreakEvent;
						}
						
						if (hasBreakInfo) {
							if (currentStepRequest != null &&
							    currentStepRequest.Depth != StepDepth.Out &&
							    binfo.Location.ILOffset == currentAddress && 
							    e.Thread.Id == currentStepRequest.Thread.Id &&
								currentStackDepth == e.Thread.GetFrames ().Length)
								redoCurrentStep = true;
						}
					} else if (e.EventType == EventType.Step) {
						var stepRequest = e.Request as StepEventRequest;
						steppedInto = IsStepIntoRequest (stepRequest);
						steppedOut = IsStepOutRequest (stepRequest);
						etype = TargetEventType.TargetStopped;
						resume = false;
					} else if (e.EventType == EventType.UserBreak) {
						etype = TargetEventType.TargetStopped;
						autoStepInto = false;
						resume = false;
					} else {
						throw new Exception ("Break eventset had unexpected event type " + e.GetType ());
					}
				}
			}
			
			if (redoCurrentStep) {
				StepDepth depth = currentStepRequest.Depth;
				StepSize size = currentStepRequest.Size;
				
				current_thread = recent_thread = es[0].Thread;
				currentStepRequest.Enabled = false;
				currentStepRequest = null;
				
				Step (depth, size);
			} else if (resume) {
				// all breakpoints were conditional and evaluated as false
				current_thread = null;
				vm.Resume ();
				DequeueEventsForFirstThread ();
			} else {
				if (currentStepRequest != null) {
					currentStepRequest.Enabled = false;
					currentStepRequest = null;
				}
				
				current_thread = recent_thread = es[0].Thread;
				
				if (exception != null)
					activeExceptionsByThread [current_thread.ThreadId] = exception;
				
				var backtrace = GetThreadBacktrace (current_thread);
				bool stepInto = false;
				bool stepOut = false;
				
				if (backtrace.FrameCount > 0) {
					var frame = backtrace.GetFrame (0) as SoftDebuggerStackFrame;
					currentAddress = frame != null ? frame.Address : -1;
					currentStackDepth = backtrace.FrameCount;

					if (frame != null && steppedInto) {
						if (ContinueOnStepInto (frame.StackFrame.Method)) {
							current_thread = null;
							vm.Resume ();
							DequeueEventsForFirstThread ();
							return;
						}

						if (StepThrough (frame.StackFrame.Method)) {
							// The method has a Debugger[Hidden,StepThrough,NonUserCode]Attribute on it
							// Keep calling StepInto until we land somewhere without one of these attributes
							stepInto = true;
						} else if (frame.StackFrame.ILOffset == 0 && IsPropertyOrOperatorMethod (frame.StackFrame.Method) &&
						           (Options.StepOverPropertiesAndOperators || IsCompilerGenerated (frame.StackFrame.Method))) {
							//We want to skip property only when we just stepped into property(ILOffset==0)
							//so if user puts breakpoint inside property we don't want to StepOut for him when he steps after breakpoint is hit

							//mcs.exe and Roslyn are also emmiting Sequence point inside auto-properties so breakpoint can be placed
							//we want to always skip auto-properties also when StepOverProperties is disabled hence "|| IsCompilerGenerated"

							// We will want to call StepInto once StepOut returns...
							autoStepInto = true;
							stepOut = true;
						} else if (IsAutoGeneratedFrameworkEnumerator (frame.StackFrame.Method.DeclaringType)) {
							// User asked to step in, but we landed in an autogenerated type (probably an iterator)
							autoStepInto = true;
							stepOut = true;
						}
					} else if (etype == TargetEventType.TargetHitBreakpoint && breakEvent != null && !breakEvent.NonUserBreakpoint && IgnoreBreakpoint (frame.StackFrame.Method)) {
						current_thread = null;
						vm.Resume ();
						DequeueEventsForFirstThread ();
						return;
					}
				}

				if (stepOut) {
					Step (StepDepth.Out, StepSize.Min);
				} else if (stepInto) {
					Step (StepDepth.Into, StepSize.Min);
				} else if (steppedOut && autoStepInto) {
					autoStepInto = false;
					Step (StepDepth.Into, StepSize.Min);
				} else {
					var args = new TargetEventArgs (etype);
					args.Process = OnGetProcesses () [0];
					args.Thread = GetThread (args.Process, current_thread);
					args.Backtrace = backtrace;
					args.BreakEvent = breakEvent;
					
					OnTargetEvent (args);
				}
			}
		}

		public void AddUserAssembly(string userAssembly)
		{
			if (userAssemblyNames != null && !userAssemblyNames.Contains(userAssembly))
				userAssemblyNames.Add(userAssembly);
		}

		void HandleAssemblyLoadEvents (AssemblyLoadEvent[] events)
		{
			var asm = events [0].Assembly;
			if (events.Length > 1 && events.Any (a => a.Assembly != asm))
				throw new InvalidOperationException ("Simultaneous AssemblyLoadEvent for multiple assemblies");

			OnAssemblyLoaded(asm.Location);

			RegisterAssembly(asm);
			bool isExternal;
			isExternal = !UpdateAssemblyFilters (asm) && userAssemblyNames != null;

			if (outputOptions.ModuleLoaded) { 
				string flagExt = isExternal ? " [External]" : "";
				OnDebuggerOutput (false, string.Format ("Loaded assembly: {0}{1}\n", asm.Location, flagExt));
			}
		}

		void RegisterAssembly (AssemblyMirror asm)
		{
			var domain = vm.Version.AtLeast (2, 45) ? asm.Domain : asm.GetAssemblyObject ().Domain;
			if (domainAssembliesToUnload.TryGetValue (domain, out var asmList)) {
				asmList.Add (asm);
			} else {
				domainAssembliesToUnload.Add (domain, new HashSet<AssemblyMirror> (new [] { asm }));
			}
		}

		void HandleDomainUnloadEvents (AppDomainUnloadEvent [] events)
		{
			var domain = events [0].Domain;
			if (events.Length > 1 && events.Any (a => a.Domain != domain))
				throw new InvalidOperationException ("Simultaneous DomainUnloadEvents for multiple domains");
			if (domainAssembliesToUnload.TryGetValue (domain, out var asmList)) {
				foreach (var asm in asmList) {
					HandleAssemblyUnloadEvents (asm);
				}
			}
		}

		void HandleAssemblyUnloadEvents (AssemblyMirror asm)
		{
			assemblyFilters?.Remove (asm);

			// Mark affected breakpoints as pending again
			var affectedBreakpoints = new List<KeyValuePair<EventRequest, BreakInfo>> (breakpoints.Where (x => x.Value.Requests.TryGetValue (x.Key, out var a) && a == asm));
			foreach (var breakpoint in affectedBreakpoints) {
				var affectedRequests = breakpoint.Value.Requests.Where (r => r.Value == asm).ToArray ();
				foreach (var item in affectedRequests) {
					breakpoint.Value.Requests.Remove (item.Key);
					breakpoints.Remove (breakpoint.Key);
				}
				if (!breakpoint.Value.Requests.Any ()) {
					string file = breakpoint.Value.Location.SourceFile;
					int line = breakpoint.Value.Location.LineNumber;
					OnDebuggerOutput (false, string.Format ("Re-pending breakpoint at {0}:{1}\n", file, line));
					breakpoint.Value.SetStatus (BreakEventStatus.NotBound, "Assembly unloaded");
				}
			}

			// Remove affected types from the loaded types list
			var affectedTypes = types.SelectMany (l => l.Value).Where (t => t.Assembly == asm).ToArray ();

			foreach (var tm in affectedTypes) {
				List<TypeMirror> typesList;
				if (tm.IsNested) {
					if (aliases.TryGetValue (NestedTypeNameToAlias (tm.FullName), out typesList)) {
						typesList.Remove (tm);
						if (typesList.Count == 0)
							aliases.Remove (NestedTypeNameToAlias (tm.FullName));
					}
				}
				if (types.TryGetValue (tm.FullName, out typesList)) {
					typesList.Remove (tm);
					if (typesList.Count == 0)
						types.Remove (tm.FullName);
				}
			}

			lock (source_to_type) {
				foreach (var pair in source_to_type)
					pair.Value.RemoveAll (m => m.Assembly == asm);
			}

			if (outputOptions.ModuleUnoaded)
				OnDebuggerOutput (false, string.Format ("Unloaded assembly: {0}\n", GetAssemblyLocation (asm) ?? "<unknown>"));
		}

		static string GetAssemblyLocation (AssemblyMirror asm)
		{
			if (asm == null)
				return null;
			try {
				return asm.Location;
			} catch (CommandException ex) {
				if (ex.ErrorCode != ErrorCode.ERR_UNLOADED)
					throw ex;
				return null;
			}
		}

		void HandleVMStartEvents (VMStartEvent[] events)
		{
			var thread = events [0].Thread;
			if (events.Length > 1)
				throw new InvalidOperationException ("Simultaneous VMStartEvents");

			OnStarted (new ThreadInfo (0, GetId (thread), GetThreadName (thread), null));
			//HACK: 2.6.1 VM doesn't emit type load event, so work around it
			var t = vm.RootDomain.Corlib.GetType ("System.Exception", false, false);
			if (t != null) {
				ResolveBreakpoints (t);
			}
		}

		void HandleTypeLoadEvents (TypeLoadEvent[] events)
		{
			var type = events [0].Type;
			if (events.Length > 1 && events.Any (a => a.Type != type))
				throw new InvalidOperationException ("Simultaneous TypeLoadEvents for multiple types");

			List<TypeMirror> typesList;
			if (!(types.TryGetValue (type.FullName, out typesList) && typesList.Contains (type)))
				ResolveBreakpoints (type);
		}

		void HandleThreadStartEvents (ThreadStartEvent[] events)
		{
			current_threads = null;
			var thread = events [0].Thread;
			if (events.Length > 1 && events.Any (a => a.Thread != thread))
				throw new InvalidOperationException ("Simultaneous ThreadStartEvents for multiple threads");

			var name = GetThreadName (thread);
			var id = GetId (thread);
			OnDebuggerOutput (false, string.Format ("Thread started: {0} #{1}\n", name, id));
			OnTargetEvent (new TargetEventArgs (TargetEventType.ThreadStarted) {
				Thread = new ThreadInfo (0, id, name, null),
			});
		}

		void HandleThreadDeathEvents (ThreadDeathEvent[] events)
		{
			current_threads = null;
			ThreadMirror thread;
			try {
				thread = events [0].Thread;
			} catch (ObjectCollectedException) {
				// A 2.1 debugger-agent can send a ThreadDeath event for a ThreadMirror
				// already collected, in that case just allow the session to continue
				if (!vm.Version.AtLeast (2, 2))
					return;

				// Otherwise just report the error
				throw;
			}
			if (events.Length > 1 && events.Any (a => a.Thread != thread))
				throw new InvalidOperationException ("Simultaneous ThreadDeathEvents for multiple threads");

			var name = GetThreadName (thread);
			var id = GetId (thread);
			if (outputOptions.ThreadExited)
				OnDebuggerOutput (false, string.Format ("Thread finished: {0} #{1}\n", name, id));
			OnTargetEvent (new TargetEventArgs (TargetEventType.ThreadStopped) {
				Thread = new ThreadInfo (0, id, name, null),
			});
		}

		void HandleUserLogEvents (UserLogEvent[] events)
		{
			foreach (var ul in events)
				OnTargetDebug (ul.Level, ul.Category, ul.Message);
		}

		void HandleMethodUpdateEvents(MethodUpdateEvent[] methods)
		{
			foreach (var method in methods) //add new methods to type
			{
				method.GetMethod ().ClearCachedLocalsDebugInfo ();
				method.GetMethod ().DeclaringType.AddMethodIfNotExist (method.GetMethod ());
			}
			foreach (var breakpoint in breakpoints) {
				Breakpoint bp = ((Breakpoint)breakpoint.Value.BreakEvent);
				if (bp.UpdatedByEnC) {
					bool dummy = false;
					var l = FindLocationByMethod (breakpoint.Value.Location.Method, bp.FileName, bp.Line, bp.Column, ref dummy);
					if (l != null) {
						breakpoint.Value.Location = l;
						UpdateBreakpoint (bp, breakpoint.Value);
						bp.UpdatedByEnC = false;
					}
				}
			}
			foreach (var bp in pending_bes) {
				if (bp.Status != BreakEventStatus.Bound) {
					foreach (var location in FindLocationsByFile (bp.Breakpoint.FileName, bp.Breakpoint.Line, bp.Breakpoint.Column, out _, out bool insideLoadedRange)) {
						OnDebuggerOutput (false, string.Format ("Resolved pending breakpoint at '{0}:{1},{2}' to {3} [0x{4:x5}].\n",
																bp.Breakpoint.FileName, bp.Breakpoint.Line, bp.Breakpoint.Column,
																GetPrettyMethodName (location.Method), location.ILOffset));

						bp.Location = location;
						InsertBreakpoint (bp.Breakpoint, bp);
						bp.SetStatus (BreakEventStatus.Bound, null);
					}
				}
			}
		}

		public ObjectMirror GetExceptionObject (ThreadMirror thread)
		{
			ObjectMirror obj;

			return activeExceptionsByThread.TryGetValue (thread.ThreadId, out obj) ? obj : null;
		}
		
		void QueueBreakEventSet (Event[] eventSet)
		{
#if DEBUG_EVENT_QUEUEING
			Console.WriteLine ("qq eventset({0}): {1}", eventSet.Length, eventSet[0]);
#endif
			var events = new List<Event> (eventSet);
			lock (queuedEventSets) {
				queuedEventSets.AddLast (events);
			}
		}
		
		void RemoveQueuedBreakEvents (Dictionary<EventRequest, AssemblyMirror> requests)
		{
			int resume = 0;
			
			lock (queuedEventSets) {
				var node = queuedEventSets.First;
				
				while (node != null) {
					List<Event> q = node.Value;
					
					for (int i = 0; i < q.Count; i++) {
						foreach (var request in requests.Keys) {
							if (q[i].Request == request) {
								q.RemoveAt (i--);
								break;
							}
						}
					}
					
					if (q.Count == 0) {
						var d = node;
						node = node.Next;
						queuedEventSets.Remove (d);
						resume++;
					} else {
						node = node.Next;
					}
				}
			}
			
			for (int i = 0; i < resume; i++)
				vm.Resume ();
		}
		
		void DequeueEventsForFirstThread ()
		{
			List<List<Event>> dequeuing;
			lock (queuedEventSets) {
				if (queuedEventSets.Count < 1)
					return;
				
				dequeuing = new List<List<Event>> ();
				var node = queuedEventSets.First;
				
				//making this the current thread means that all events from other threads will get queued
				current_thread = node.Value[0].Thread;
				while (node != null) {
					if (node.Value[0].Thread.Id == current_thread.Id) {
						var d = node;
						node = node.Next;
						dequeuing.Add (d.Value);
						queuedEventSets.Remove (d);
					} else {
						node = node.Next;
					}
				}
			}

#if DEBUG_EVENT_QUEUEING
			foreach (var e in dequeuing)
				Console.WriteLine ("dq eventset({0}): {1}", e.Count, e[0]);
#endif

			//firing this off in a thread prevents possible infinite recursion
			ThreadPool.QueueUserWorkItem (delegate {
				if (!HasExited) {
					foreach (var es in dequeuing) {
						try {
							 HandleBreakEventSet (es.ToArray (), true);
						} catch (Exception ex) {
							if (!HandleException (ex) && outputOptions.ExceptionMessage)
								OnDebuggerOutput (true, ex.ToString ());

							if (ex is VMDisconnectedException || ex is IOException || ex is SocketException) {
								OnTargetEvent (new TargetEventArgs (TargetEventType.TargetExited));
								break;
							}
						}
					}
				}
			});
		}
		
		bool HandleBreakpoint (ThreadMirror thread, EventRequest er)
		{
			BreakInfo binfo;
			if (!breakpoints.TryGetValue (er, out binfo))
				return false;
			
			var bp = binfo.BreakEvent;
			if (bp == null)
				return false;

			binfo.IncrementHitCount ();
			if (!binfo.HitCountReached)
				return true;
			
			if (!string.IsNullOrEmpty (bp.ConditionExpression)) {
				string res = EvaluateExpression (thread, bp.ConditionExpression, bp);
				if (bp.BreakIfConditionChanges) {
					if (res == binfo.LastConditionValue)
						return true;
					binfo.LastConditionValue = res;
				} else {
					if (res == null || res.ToLowerInvariant () != "true")
						return true;
				}
			}
			if ((bp.HitAction & HitAction.CustomAction) != HitAction.None) {
				if (HandleProcessStartHook (thread, bp))
					return true;
				// If custom action returns true, execution must continue
				return binfo.RunCustomBreakpointAction (bp.CustomActionId);
			}

			if ((bp.HitAction & HitAction.PrintTrace) != HitAction.None) {
				OnTargetDebug (0, "", "Breakpoint reached: " + binfo.FileName + ":" + binfo.Location.LineNumber + Environment.NewLine);
			}

			if ((bp.HitAction & HitAction.PrintExpression) != HitAction.None) {
				string exp = EvaluateTrace (thread, bp.TraceExpression);
				binfo.UpdateLastTraceValue (exp);
			}

			// Continue execution if we don't have break action.
			return (bp.HitAction & HitAction.Break) == HitAction.None;
		}
		
		string EvaluateTrace (ThreadMirror thread, string exp)
		{
			var sb = new StringBuilder ();
			int last = 0;
			int i = exp.IndexOf ('{');
			while (i != -1) {
				if (i < exp.Length - 1 && exp [i+1] == '{') {
					sb.Append (exp, last, i - last + 1);
					last = i + 2;
					i = exp.IndexOf ('{', i + 2);
					continue;
				}
				int j = exp.IndexOf ('}', i + 1);
				if (j == -1)
					break;
				string se = exp.Substring (i + 1, j - i - 1);
				se = EvaluateExpression (thread, se, null);
				sb.Append (exp, last, i - last);
				sb.Append (se);
				last = j + 1;
				i = exp.IndexOf ('{', last);
			}
			sb.Append (exp, last, exp.Length - last);
			return sb.ToString ();
		}

		static SourceLocation GetSourceLocation (StackFrame frame)
		{
			return new SourceLocation (frame.Method.Name, frame.FileName, frame.LineNumber, frame.ColumnNumber, frame.EndLineNumber, frame.EndColumnNumber);
		}

		static string FormatSourceLocation (BreakEvent breakEvent)
		{
			var bp = breakEvent as Breakpoint;
			if (bp == null || string.IsNullOrEmpty (bp.FileName))
				return null;

			var location = Path.GetFileName (bp.FileName);
			if (bp.OriginalLine > 0) {
				location += ":" + bp.OriginalLine;
				if (bp.OriginalColumn > 0)
					location += "," + bp.OriginalColumn;
			}

			return location;
		}

		static bool IsBoolean (ValueReference vr)
		{
			if (vr.Type is Type && ((Type) vr.Type) == typeof (bool))
				return true;

			if (vr.Type is TypeMirror && ((TypeMirror) vr.Type).FullName == "System.Boolean")
				return true;

			return false;
		}
		
		string EvaluateExpression (ThreadMirror thread, string expression, BreakEvent bp)
		{
			try {
				var frames = thread.GetFrames ();
				if (frames.Length == 0)
					return string.Empty;

				EvaluationOptions ops = Options.EvaluationOptions.Clone ();
				ops.AllowTargetInvoke = true;
				ops.EllipsizedLength = 1000;

				var ctx = new SoftEvaluationContext (this, frames[0], ops);

				if (bp != null) {
					// validate conditional breakpoint expressions so that we can provide error reporting to the user
					var vr = ctx.Evaluator.ValidateExpression (ctx, expression);
					if (!vr.IsValid) {
						string message = string.Format ("Invalid expression in conditional breakpoint. {0}", vr.Message);
						string location = FormatSourceLocation (bp);

						if (!string.IsNullOrEmpty (location))
							message = location + ": " + message;

						OnDebuggerOutput (true, message);
						return string.Empty;
					}

					// resolve types...
					if (ctx.SourceCodeAvailable)
						expression = ctx.Evaluator.Resolve (this, GetSourceLocation (frames[0]), expression);
				}

				ValueReference val = ctx.Evaluator.Evaluate (ctx, expression);
				if (bp != null && !bp.BreakIfConditionChanges && !IsBoolean (val)) {
					string message = string.Format ("Expression in conditional breakpoint did not evaluate to a boolean value: {0}", bp.ConditionExpression);
					string location = FormatSourceLocation (bp);

					if (!string.IsNullOrEmpty (location))
						message = location + ": " + message;

					OnDebuggerOutput (true, message);
					return string.Empty;
				}

				return val.CreateObjectValue (false).Value;
			} catch (EvaluatorException ex) {
				string message;

				if (bp != null) {
					message = string.Format ("Failed to evaluate expression in conditional breakpoint. {0}", ex.Message);
					string location = FormatSourceLocation (bp);

					if (!string.IsNullOrEmpty (location))
						message = location + ": " + message;
				} else {
					message = ex.ToString ();
				}

				OnDebuggerOutput (true, message);
				return string.Empty;
			} catch (Exception ex) {
				OnDebuggerOutput (true, ex.ToString ());
				return string.Empty;
			}
		}

		static string NestedTypeNameToAlias (string typeName)
		{
			int index = typeName.IndexOfAny (new [] { '[', ',' });

			if (index == -1)
				return typeName.Replace ('+', '.');

			var prefix = typeName.Substring (0, index).Replace ('+', '.');
			var suffix = typeName.Substring (index);

			return prefix + suffix;
		}
		
		void ProcessType (TypeMirror t)
		{
			string typeName = t.FullName;

			List<TypeMirror> typesList;
			if (types.TryGetValue (typeName, out typesList) && typesList.Contains (t))
				return;

			RegisterAssembly (t.Assembly);

			if (t.IsNested) {
				var alias = NestedTypeNameToAlias (typeName);
				List<TypeMirror> aliasesList;
				if (aliases.TryGetValue (alias, out aliasesList)) {
					aliasesList.Add (t);
				} else {
					aliases [alias] = new List<TypeMirror> (new [] { t });
				}
			}
			types [typeName] = typesList ?? new List<TypeMirror> ();
			types [typeName].Add (t);

			//get the source file paths
			//full paths, from GetSourceFiles (true), are only supported by sdb protocol 2.2 and later
			string[] sourceFiles;
			if (vm.Version.AtLeast (2, 2)) {
				sourceFiles = t.GetSourceFiles ().Select ((fullPath) => Path.GetFileName (fullPath)).ToArray ();
			} else {
				sourceFiles = t.GetSourceFiles ();
				
				//HACK: if mdb paths are windows paths but the sdb agent is on unix, it won't map paths to filenames correctly
				if (IsWindows) {
					for (int i = 0; i < sourceFiles.Length; i++) {
						string s = sourceFiles[i];
						if (s != null && !s.StartsWith ("/", StringComparison.Ordinal))
							sourceFiles[i] = Path.GetFileName (s);
					}
				}
			}
			
			for (int n = 0; n < sourceFiles.Length; n++)
				sourceFiles[n] = NormalizePath (sourceFiles[n]);

			foreach (string s in sourceFiles) {
				lock (source_to_type) {
					if (source_to_type.TryGetValue (s, out typesList)) {
						typesList.Add (t);
					} else {
						typesList = new List<TypeMirror> ();
						typesList.Add (t);
						source_to_type[s] = typesList;
					}
				}
			}

			type_to_source [t] = sourceFiles;
		}
		
		static string[] GetParamTypes (MethodMirror method)
		{
			var paramTypes = new List<string> ();
			
			foreach (var param in method.GetParameters ())
				paramTypes.Add (param.ParameterType.CSharpName);
			
			return paramTypes.ToArray ();
		}

		string GetPrettyMethodName (MethodMirror method)
		{
			var name = new StringBuilder ();

			name.Append (Adaptor.GetDisplayTypeName (method.ReturnType.FullName));
			name.Append (" ");
			name.Append (Adaptor.GetDisplayTypeName (method.DeclaringType.FullName));
			name.Append (".");
			name.Append (method.Name);

			if (method.VirtualMachine.Version.AtLeast (2, 12)) {
				if (method.IsGenericMethodDefinition || method.IsGenericMethod) {
					name.Append ("<");
					if (method.VirtualMachine.Version.AtLeast (2, 15)) {
						var argTypes = method.GetGenericArguments ();
						for (int i = 0; i < argTypes.Length; i++) {
							if (i != 0)
								name.Append (", ");
							name.Append (Adaptor.GetDisplayTypeName (argTypes[i].FullName));
						}
					}
					name.Append (">");
				}
			}

			name.Append (" (");
			var @params = method.GetParameters ();
			for (int i = 0; i < @params.Length; i++) {
				if (i != 0)
					name.Append (", ");
				if (@params[i].Attributes.HasFlag (ParameterAttributes.Out)) {
					if (@params[i].Attributes.HasFlag (ParameterAttributes.In))
						name.Append ("ref ");
					else
						name.Append ("out ");
				}
				name.Append (Adaptor.GetDisplayTypeName (@params[i].ParameterType.FullName));
				name.Append (" ");
				name.Append (@params[i].Name);
			}
			name.Append (")");

			return name.ToString ();
		}

		void ResolveBreakpoints (TypeMirror type)
		{
			Location loc;
			
			ProcessType (type);

			// First, resolve FunctionBreakpoints
			BreakInfo [] tempPendingBes;
			lock (pending_bes) {
				tempPendingBes = pending_bes.Where (b => b.BreakEvent is FunctionBreakpoint).ToArray ();
			}
			foreach (var bi in tempPendingBes) {
				if (CheckTypeName (type, bi.TypeName)) {
					var bp = (FunctionBreakpoint)bi.BreakEvent;
					foreach (var method in FindMethodsByName (bp.FunctionName, bp.ParamTypes)) {
						ResolveFunctionBreakpoint (bi, bp, method);
					}
				}
			}

			// Now resolve normal Breakpoints
			foreach (string s in type_to_source [type]) {
				lock (pending_bes) {
					tempPendingBes = pending_bes.Where (b => (b.BreakEvent is Breakpoint) && !(b.BreakEvent is FunctionBreakpoint)).ToArray ();
				}
				foreach (var bi in tempPendingBes) {
					var bp = (Breakpoint) bi.BreakEvent;
					if (PathComparer.Compare (Path.GetFileName (bp.FileName), s) == 0) {
						bool insideLoadedRange;
						bool genericMethod;

						if (bi.BreakEvent is InstructionBreakpoint) {
							loc = FindLocationByILOffset ((InstructionBreakpoint)bi.BreakEvent, bp.FileName, out genericMethod, out insideLoadedRange);
						} else {
							loc = FindLocationByType (type, bp.FileName, bp.Line, bp.Column, out genericMethod, out insideLoadedRange);
						}
						if (loc != null) {
							OnDebuggerOutput (false, string.Format ("Resolved pending breakpoint at '{0}:{1},{2}' to {3} [0x{4:x5}].\n",
							                                        s, bp.Line, bp.Column, GetPrettyMethodName (loc.Method), loc.ILOffset));
							ResolvePendingBreakpoint (bi, loc);
						} else {
							if (insideLoadedRange) {
								bi.SetStatus (BreakEventStatus.Invalid, null);
							}
						}
					}
				}
			}

			// Thirdly, resolve pending catchpoints
			lock (pending_bes) {
				tempPendingBes = pending_bes.Where (b => b.BreakEvent is Catchpoint).ToArray ();
			}
			foreach (var bi in tempPendingBes) {
				var cp = (Catchpoint) bi.BreakEvent;
				if (cp.ExceptionName == type.FullName) {
					ResolvePendingCatchpoint (bi, type);
				}
			}
		}

		bool ResolveFunctionBreakpoint (BreakInfo bi, FunctionBreakpoint bp, MethodMirror method)
		{
			var loc = method.Locations.FirstOrDefault ();
			string paramList = "(" + string.Join (", ", bp.ParamTypes ?? GetParamTypes (method)) + ")";
			if (loc != null) {
				bi.Location = loc;
				InsertBreakpoint (bp, bi);
				OnDebuggerOutput (false, string.Format ("Resolved pending breakpoint for '{0}{1}' to {2}:{3} [0x{4:x5}].\n",
														bp.FunctionName, paramList, loc.SourceFile, loc.LineNumber, loc.ILOffset));
			} else {
				InsertBreakpoint (bp, bi, method, 0);
				OnDebuggerOutput (false, string.Format ("Resolved pending breakpoint for '{0}{1}' to [0x0](no debug symbols).\n",
														bp.FunctionName, paramList));
			}
			bi.SetStatus (BreakEventStatus.Bound, null);
			// Note: if the type or method is generic, there may be more instances so don't assume we are done resolving the breakpoint
			return bp.ParamTypes != null && !method.DeclaringType.IsGenericType && !IsGenericMethod (method);
		}

		internal static string NormalizePath (string path)
		{
			if (!IsWindows && (path.StartsWith ("\\", StringComparison.Ordinal) || (path.Length > 3 && path [1] == ':' && path [2] == '\\')))
				return path.Replace ('\\', '/');

			return path;
		}

		[DllImport ("libc")]
		static extern IntPtr realpath (string path, IntPtr buffer);
		
		static string ResolveFullPath (string path)
		{
			if (IsWindows)
				return Path.GetFullPath (path);

			const int PATHMAX = 4096 + 1;
			IntPtr buffer = IntPtr.Zero;

			try {
				buffer = Marshal.AllocHGlobal (PATHMAX);
				var result = realpath (path, buffer);
				var realPath = result == IntPtr.Zero ? "" : Marshal.PtrToStringAuto (buffer);

				if (string.IsNullOrEmpty(realPath) && !File.Exists(path)) {
					// if the file does not exist then `realpath` will return empty string
					// default to what we would do if calling this on windows
					realPath = Path.GetFullPath (path);
				}

				return realPath;
			} finally {
				if (buffer != IntPtr.Zero)
					Marshal.FreeHGlobal (buffer);
			}
		}

		static string ResolveSymbolicLink (string path)
		{
			if (path.Length == 0)
				return path;

			if (IsWindows)
				return ResolveWindowsSymbolicLink (path);

            return ResolveUnixSymbolicLink (path);
		}

        static string ResolveWindowsSymbolicLink (string path)
        {
            return Path.GetFullPath (path);
        }

        static string ResolveUnixSymbolicLink (string path)
        {
   			try {
				var alreadyVisted = new HashSet<string> ();

				while (true) {
					if (alreadyVisted.Contains (path))
						return string.Empty;

					alreadyVisted.Add (path);

					var linkInfo = new Mono.Unix.UnixSymbolicLinkInfo (path);
					if (linkInfo.IsSymbolicLink && linkInfo.HasContents) {
						string contentsPath = linkInfo.ContentsPath;

						if (!Path.IsPathRooted (contentsPath))
							path = Path.Combine (Path.GetDirectoryName (path), contentsPath);
						else
							path = contentsPath;

						path = ResolveFullPath (path);
						continue;
					}

					path = Path.Combine (ResolveSymbolicLink (Path.GetDirectoryName (path)), Path.GetFileName (path));

					return ResolveFullPath (path);
				}
			} catch {
				return path;
			}
        }
		
		static bool PathsAreEqual (string p1, string p2)
		{
			if (string.IsNullOrWhiteSpace (p1) || string.IsNullOrWhiteSpace (p2))
				return false;

			if (PathComparer.Compare (p1, p2) == 0)
				return true;

			var rp1 = ResolveSymbolicLink (p1);
			var rp2 = ResolveSymbolicLink (p2);

			return PathComparer.Compare (rp1, rp2) == 0;
		}

		Location FindLocationByMethod (MethodMirror method, string file, int line, int column, ref bool insideTypeRange)
		{
			int rangeFirstLine = int.MaxValue;
			int rangeLastLine = -1;
			Location target = null;

			//Console.WriteLine ("FindLocationByMethod: method = {0}, file = {1}, line = {2}, column = {3}", method.Name, Path.GetFileName (file), line, column);

			foreach (var location in method.Locations) {
				var srcFile = location.SourceFile;

				//Console.WriteLine ("\tChecking location {0}:{1},{2}...", Path.GetFileName(srcFile), location.LineNumber, location.ColumnNumber);

				//Check if file names match
				if (srcFile != null && PathComparer.Compare (Path.GetFileName (NormalizePath (srcFile)), Path.GetFileName (file)) == 0) {
					//Check if full path match(we don't care about md5 if full path match):
					//1. For backward compatibility
					//2. If full path matches user himself probably modified code and is aware of modifications
					//OR if md5 match, useful for alternative location files with breakpoints
					if (!PathsAreEqual (NormalizePath (srcFile), file) && !SourceLocation.CheckFileHash (file, location.SourceFileHash))
						continue;

					if (location.LineNumber < rangeFirstLine)
						rangeFirstLine = location.LineNumber;

					if (location.LineNumber > rangeLastLine)
						rangeLastLine = location.LineNumber;

					if (line >= rangeFirstLine && line <= rangeLastLine)
						insideTypeRange = true;

					if (line == location.LineNumber && (column <= 1 || column == location.ColumnNumber)) {
						if (target != null) {
							if (location.ILOffset < target.ILOffset)
								target = location;
						} else {
							target = location;
						}
					}
				} else {
					rangeFirstLine = int.MaxValue;
					rangeLastLine = -1;
				}
			}

			return target;
		}

		Location FindLocationByType (TypeMirror type, string file, int line, int column, out bool genericMethod, out bool insideTypeRange)
		{
			var methodInsideTypeRange = false;
			Location target = null;

			insideTypeRange = false;
			genericMethod = false;

			foreach (var method in type.GetMethods ()) {
				Location location = null;

				if ((location = FindLocationByMethod (method, file, line, column, ref methodInsideTypeRange)) != null) {
					insideTypeRange |= methodInsideTypeRange;//If any method returns true return true

					if (target != null) {
						// Use the location with the lowest ILOffset
						if (location.ILOffset < target.ILOffset) {
							genericMethod = IsGenericMethod (method);
							target = location;
						}
					} else {
						genericMethod = IsGenericMethod (method);
						target = location;
					}
				}
			}
			
			return target;
		}

		void ResolvePendingBreakpoint (BreakInfo bi, Location l)
		{
			bi.Location = l;
			InsertBreakpoint ((Breakpoint) bi.BreakEvent, bi);
			bi.SetStatus (BreakEventStatus.Bound, null);
		}
				
		void ResolvePendingCatchpoint (BreakInfo bi, TypeMirror type)
		{
			InsertCatchpoint ((Catchpoint) bi.BreakEvent, bi, type);
			bi.SetStatus (BreakEventStatus.Bound, null);
		}
		
		bool UpdateAssemblyFilters (AssemblyMirror asm)
		{
			var name = asm.GetName ().FullName;
			bool found = false;
			if (userAssemblyNames != null) {
				//HACK: not sure how else to handle xsp-compiled pages
				if (name.StartsWith ("App_", StringComparison.Ordinal)) {
					found = true;
				} else {
					foreach (var n in userAssemblyNames) {
						if (n == name) {
							found = true;
							break;
						}
					}
				}
			}

			if (found) {
				assemblyFilters.Add (asm);
				return true;
			}

			return false;
		}
		
		internal void WriteDebuggerOutput (bool isError, string msg)
		{
			OnDebuggerOutput (isError, msg);
		}
		
		protected override void OnSetActiveThread (long processId, long threadId)
		{
		}

		protected override void OnStepInstruction ()
		{
			Step (StepDepth.Into, StepSize.Min);
		}

		protected override void OnStepLine ()
		{
			Step (StepDepth.Into, StepSize.Line);
		}

		protected override void OnStop ()
		{
			vm.Suspend ();
			
			//emit a stop event at the current position of the most recent thread
			//we use "getprocesses" instead of "ongetprocesses" because it attaches the process to the session
			//using private Mono.Debugging API, so our thread/backtrace calls will cache stuff that will get used later
			var process = GetProcesses () [0];				
			EnsureRecentThreadIsValid (process);
			current_thread = recent_thread;
			OnTargetEvent (new TargetEventArgs (TargetEventType.TargetStopped) {
				Process = process,
				Thread = GetThread (process, recent_thread),
				Backtrace = GetThreadBacktrace (recent_thread)});
		}
		
		void EnsureRecentThreadIsValid (ProcessInfo process)
		{
			var infos = process.GetThreads ();
			
			if (ThreadIsAlive (recent_thread) && HasUserFrame (GetId (recent_thread), infos))
				return;

			var threads = vm.GetThreads ();
			foreach (var thread in threads) {
				if (ThreadIsAlive (thread) && HasUserFrame (GetId (thread), infos)) {
					recent_thread = thread;
					return;
				}
			}
			recent_thread = threads[0];	
		}
		
		long GetId (ThreadMirror thread)
		{
			long id;
			if (!localThreadIds.TryGetValue (thread.ThreadId, out id)) {
				id = localThreadIds.Count + 1;
				localThreadIds [thread.ThreadId] = id;
			}
			return id;
		}
		
		static bool ThreadIsAlive (ThreadMirror thread)
		{
			if (thread == null)
				return false;
			ThreadState state;
			try {
				state = thread.ThreadState;
			} catch (ObjectCollectedException) {
				return false;//Thread was already collected by garbage collector, hence it's not alive
			}
			return state != ThreadState.Stopped && state != ThreadState.Aborted;
		}
		
		//we use the Mono.Debugging classes because they are cached
		static bool HasUserFrame (long tid, ThreadInfo[] threads)
		{
			foreach (var thread in threads) {
				if (thread.Id != tid)
					continue;

				var bt = thread.Backtrace;
				for (int i = 0; i < bt.FrameCount; i++) {
					var frame = bt.GetFrame (i);
					if (frame != null && !frame.IsExternalCode)
						return true;
				}

				return false;
			}

			return false;
		}
		
		public bool IsExternalCode (StackFrame frame)
		{
			return frame.Method == null || string.IsNullOrEmpty (frame.FileName)
				|| (assemblyFilters != null && !assemblyFilters.Contains (frame.Method.DeclaringType.Assembly));
		}
		
		public bool IsExternalCode (TypeMirror type)
		{
			return assemblyFilters != null && !assemblyFilters.Contains (type.Assembly);
		}
		
		protected override AssemblyLine[] OnDisassembleFile (string file)
		{
			List<TypeMirror> mirrors;

			if (!source_to_type.TryGetValue (file, out mirrors))
				return new AssemblyLine [0];
			
			var lines = new List<AssemblyLine> ();
			foreach (var type in mirrors) {
				foreach (var method in type.GetMethods ()) {
					string srcFile = method.SourceFile != null ? NormalizePath (method.SourceFile) : null;
					
					if (srcFile == null || !PathsAreEqual (srcFile, file))
						continue;
					
					var body = method.GetMethodBody ();
					int lastLine = -1;
					int firstPos = lines.Count;
					string addrSpace = method.FullName;
					
					foreach (var ins in body.Instructions) {
						var loc = method.LocationAtILOffset (ins.Offset);

						if (loc != null && lastLine == -1) {
							lastLine = loc.LineNumber;
							for (int n = firstPos; n < lines.Count; n++) {
								AssemblyLine old = lines [n];
								lines [n] = new AssemblyLine (old.Address, old.AddressSpace, old.Code, loc.LineNumber);
							}
						}

						lines.Add (new AssemblyLine (ins.Offset, addrSpace, Disassemble (ins), loc != null ? loc.LineNumber : lastLine));
					}
				}
			}

			lines.Sort (delegate (AssemblyLine a1, AssemblyLine a2) {
				int res = a1.SourceLine.CompareTo (a2.SourceLine);

				return res != 0 ? res : a1.Address.CompareTo (a2.Address);
			});

			return lines.ToArray ();
		}

		public AssemblyLine[] Disassemble (StackFrame frame)
		{
			var body = frame.Method.GetMethodBody ();
			var instructions = body.Instructions;
			var lines = new List<AssemblyLine> ();

			foreach (var instruction in instructions) {
				var location = frame.Method.LocationAtILOffset (instruction.Offset);
				int lineNumber = location != null ? location.LineNumber : -1;
				var code = Disassemble (instruction);

				lines.Add (new AssemblyLine (instruction.Offset, frame.Method.FullName, code, lineNumber));
			}

			return lines.ToArray ();
		}
		
		public AssemblyLine[] Disassemble (StackFrame frame, int firstLine, int count)
		{
			var body = frame.Method.GetMethodBody ();
			var instructions = body.Instructions;
			ILInstruction current = null;

			foreach (var instruction in instructions) {
				if (instruction.Offset >= frame.ILOffset) {
					current = instruction;
					break;
				}
			}

			if (current == null)
				return new AssemblyLine [0];
			
			var lines = new List<AssemblyLine> ();
			
			while (firstLine < 0 && count > 0) {
				if (current.Previous == null) {
					lines.Add (AssemblyLine.OutOfRange);
					firstLine = 0;
					break;
				}

				current = current.Previous;
				firstLine++;
			}
			
			while (current != null && firstLine > 0) {
				current = current.Next;
				firstLine--;
			}
			
			while (count > 0) {
				if (current != null) {
					var location = frame.Method.LocationAtILOffset (current.Offset);
					int lineNumber = location != null ? location.LineNumber : -1;
					var code = Disassemble (current);

					lines.Add (new AssemblyLine (current.Offset, frame.Method.FullName, code, lineNumber));
					current = current.Next;
				} else {
					lines.Add (AssemblyLine.OutOfRange);
				}

				count--;
			}

			return lines.ToArray ();
		}

		public void AddSourceUpdate (string fileName)
		{
			sourceUpdates.Add (new SourceUpdate(fileName));
		}
		public void AddLineUpdate (int oldLine, int newLine)
		{
			sourceUpdates.Last().LineUpdates.Add (new Tuple<int, int>(oldLine, newLine));
		}
		public void ApplyChanges (ModuleMirror module, byte[] metadataDelta, byte[] ilDelta, byte[] pdbDelta = null)
		{
			var rootDomain = VirtualMachine.RootDomain;
			var metadataArray = rootDomain.CreateByteArray (metadataDelta);
			var ilArray = rootDomain.CreateByteArray (ilDelta);
			Value pdbArray;
			if (pdbDelta == null)
				pdbArray = VirtualMachine.CreateValue (null);
			else
				pdbArray = rootDomain.CreateByteArray (pdbDelta);

			module.Assembly.ApplyChanges_DebugInformation (metadataDelta, pdbDelta);
			module.ApplyChanges (metadataArray, ilArray, pdbArray);
			foreach (var sourceUpdate in sourceUpdates)
			{
				var types = VirtualMachine.GetTypesForSourceFile (sourceUpdate.FileName, false);
				foreach (var type in types)
				{
					type.ApplySourceChanges (sourceUpdate);
				}
			}
			sourceUpdates.Clear ();
		}

		public string GetEnCCapabilities()
		{
			return vm.GetEnCCapabilities ();
		}
		static string EscapeString (string text)
		{
			var escaped = new StringBuilder ();
			
			escaped.Append ('"');
			for (int i = 0; i < text.Length; i++) {
				char c = text[i];
				string txt;
				switch (c) {
				case '"': txt = "\\\""; break;
				case '\0': txt = @"\0"; break;
				case '\\': txt = @"\\"; break;
				case '\a': txt = @"\a"; break;
				case '\b': txt = @"\b"; break;
				case '\f': txt = @"\f"; break;
				case '\v': txt = @"\v"; break;
				case '\n': txt = @"\n"; break;
				case '\r': txt = @"\r"; break;
				case '\t': txt = @"\t"; break;
				default:
					if (char.GetUnicodeCategory (c) == UnicodeCategory.OtherNotAssigned) {
						escaped.AppendFormat ("\\u{0:X4}", c);
					} else {
						escaped.Append (c);
					}
					continue;
				}
				escaped.Append (txt);
			}
			escaped.Append ('"');
			
			return escaped.ToString ();
		}
		
		static string Disassemble (ILInstruction ins)
		{
			string oper;
			if (ins.Operand is MethodMirror)
				oper = ((MethodMirror)ins.Operand).FullName;
			else if (ins.Operand is FieldInfoMirror)
				oper = ((FieldInfoMirror)ins.Operand).FullName;
			else if (ins.Operand is TypeMirror)
				oper = ((TypeMirror)ins.Operand).FullName;
			else if (ins.Operand is ILInstruction)
				oper = ((ILInstruction)ins.Operand).Offset.ToString ("x8");
			else if (ins.Operand is string)
				oper = EscapeString ((string) ins.Operand);
			else if (ins.Operand == null)
				oper = string.Empty;
			else
				oper = ins.Operand.ToString ();
			
			return ins.OpCode + " " + oper;
		}
		
		readonly static bool IsWindows;
		readonly static bool IsMac;
		readonly static StringComparer PathComparer;
		
		static bool IgnoreFilenameCase {
			get { return IsMac || IsWindows; }
		}
		
		static SoftDebuggerSession ()
		{
			IsWindows = Path.DirectorySeparatorChar == '\\';
			IsMac = !IsWindows && IsRunningOnMac ();
			PathComparer = IgnoreFilenameCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
			ThreadMirror.NativeTransitions = true;
		}
		
		//From Managed.Windows.Forms/XplatUI
		static bool IsRunningOnMac ()
		{
			IntPtr buf = IntPtr.Zero;
			try {
				buf = Marshal.AllocHGlobal (8192);
				// This is a hacktastic way of getting sysname from uname ()
				if (uname (buf) == 0) {
					string os = Marshal.PtrToStringAnsi (buf);
					if (os == "Darwin")
						return true;
				}
			} catch {
				return false;
			} finally {
				if (buf != IntPtr.Zero)
					Marshal.FreeHGlobal (buf);
			}
			return false;
		}
		
		[System.Runtime.InteropServices.DllImport ("libc")]
		static extern int uname (IntPtr buf);
	}

	class LocationComparer : IComparer<Location>
	{
		public int Compare (Location loc0, Location loc1)
		{
			if (loc0.LineNumber < loc1.LineNumber)
				return -1;
			if (loc0.LineNumber > loc1.LineNumber)
				return 1;

			if (loc0.ColumnNumber < loc1.ColumnNumber)
				return -1;
			if (loc0.ColumnNumber > loc1.ColumnNumber)
				return 1;

			return loc0.ILOffset - loc1.ILOffset;
		}
	}
	
	class BreakInfo: BreakEventInfo
	{
		public Location Location;
		public Dictionary<EventRequest, AssemblyMirror> Requests = new Dictionary<EventRequest, AssemblyMirror> ();
		public string LastConditionValue;
		public string FileName;
		public string TypeName;
	}
	
	class DisconnectedException: DebuggerException
	{
		public DisconnectedException (Exception ex):
			base ("The connection with the debugger has been lost. The target application may have exited.", ex)
		{
		}
	}
	
	class DebugSocketException: DebuggerException
	{
		public DebugSocketException (Exception ex):
			base ("Could not open port for debugger. Another process may be using the port.", ex)
		{
		}
	}
	
	class ConnectionException : DebuggerException
	{
		public ConnectionException (Exception ex):
			base ("Could not connect to the debugger.", ex)
		{
		}
	}
}