~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

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
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Mono.Cecil.Metadata;

namespace Mono.Debugger.Soft
{
	public class VersionInfo {
		public string VMVersion {
			get; set;
		}

		public int MajorVersion {
			get; set;
		}

		public int MinorVersion {
			get; set;
		}

		/*
		 * Check that this version is at least major:minor
		 */
		public bool AtLeast (int major, int minor) {
			if ((MajorVersion > major) || ((MajorVersion == major && MinorVersion >= minor)))
				return true;
			else
				return false;
		}
	}

	struct SourceInfo {
		public string source_file;
		public byte[] guid, hash;
	}

	class DebugInfo {
		public int max_il_offset;
		public int[] il_offsets;
		public int[] line_numbers;
		public int[] column_numbers;
		public SourceInfo[] source_files;
	}

	struct FrameInfo {
		public long id;
		public long method;
		public int il_offset;
		public StackFrameFlags flags;
	}

	class TypeInfo {
		public string ns, name, full_name;
		public long assembly, module, base_type, element_type;
		public int token, rank, attributes;
		public bool is_byref, is_pointer, is_primitive, is_valuetype, is_enum;
		public bool is_gtd, is_generic_type;
		public long[] nested;
		public long gtd;
		public long[] type_args;
	}

	struct IfaceMapInfo {
		public long iface_id;
		public long[] iface_methods;
		public long[] target_methods;
	}

	class MethodInfo {
		public int attributes, iattributes, token;
		public bool is_gmd, is_generic_method;
		public long gmd;
		public long[] type_args;
	}

	class MethodBodyInfo {
		public byte[] il;
		public ExceptionClauseInfo[] clauses;
	}

	struct ExceptionClauseInfo {
		public ExceptionClauseFlags flags;
		public int try_offset;
		public int try_length;
		public int handler_offset;
		public int handler_length;
		public int filter_offset;
		public long catch_type_id;
	}

	enum ExceptionClauseFlags {
		None = 0x0,
		Filter = 0x1,
		Finally = 0x2,
		Fault = 0x4,
	}

	struct ParamInfo {
		public int call_conv;
		public int param_count;
		public int generic_param_count;
		public long ret_type;
		public long[] param_types;
		public string[] param_names;
	}

	struct LocalsInfo {
		public long[] types;
		public string[] names;
		public int[] live_range_start;
		public int[] live_range_end;
	}

	struct PropInfo {
		public long id;
		public string name;
		public long get_method, set_method;
		public int attrs;
	}

	class CattrNamedArgInfo {
		public bool is_property;
		public long id;
		public ValueImpl value;
	}

	class CattrInfo {
		public long ctor_id;
		public ValueImpl[] ctor_args;
		public CattrNamedArgInfo[] named_args;
	}

	class ThreadInfo {
		public bool is_thread_pool;
	}

	struct ObjectRefInfo {
		public long type_id;
		public long domain_id;
	}

	enum ValueTypeId {
		VALUE_TYPE_ID_NULL = 0xf0,
		VALUE_TYPE_ID_TYPE = 0xf1
	}

	enum InvokeFlags {
		NONE = 0x0,
		DISABLE_BREAKPOINTS = 0x1,
		SINGLE_THREADED = 0x2
	}

	enum ElementType {
		End		 = 0x00,
		Void		= 0x01,
		Boolean	 = 0x02,
		Char		= 0x03,
		I1		  = 0x04,
		U1		  = 0x05,
		I2		  = 0x06,
		U2		  = 0x07,
		I4		  = 0x08,
		U4		  = 0x09,
		I8		  = 0x0a,
		U8		  = 0x0b,
		R4		  = 0x0c,
		R8		  = 0x0d,
		String	  = 0x0e,
		Ptr		 = 0x0f,
		ByRef	   = 0x10,
		ValueType   = 0x11,
		Class	   = 0x12,
		Var        = 0x13,
		Array	   = 0x14,
		GenericInst = 0x15,
		TypedByRef  = 0x16,
		I		   = 0x18,
		U		   = 0x19,
		FnPtr	   = 0x1b,
		Object	  = 0x1c,
		SzArray	 = 0x1d,
		MVar       = 0x1e,
		CModReqD	= 0x1f,
		CModOpt	 = 0x20,
		Internal	= 0x21,
		Modifier	= 0x40,
		Sentinel	= 0x41,
		Pinned	  = 0x45,

		Type		= 0x50,
		Boxed	   = 0x51,
		Enum		= 0x55
	}

	class ValueImpl {
		public ElementType Type; /* or one of the VALUE_TYPE_ID constants */
		public long Objid;
		public object Value;
		public long Klass; // For ElementType.ValueType
		public ValueImpl[] Fields; // for ElementType.ValueType
		public bool IsEnum; // For ElementType.ValueType
		public long Id; /* For VALUE_TYPE_ID_TYPE */
	}

	class ModuleInfo {
		public string Name, ScopeName, FQName, Guid;
		public long Assembly;
	}		

	enum TokenType {
		STRING = 0,
		TYPE = 1,
		FIELD = 2,
		METHOD = 3,
		UNKNOWN = 4
	}

	enum StackFrameFlags {
		NONE = 0,
		DEBUGGER_INVOKE = 1,
		NATIVE_TRANSITION = 2
	}

	class ResolvedToken {
		public TokenType Type;
		public string Str;
		public long Id;
	}

	class Modifier {
	}

	class CountModifier : Modifier {
		public int Count {
			get; set;
		}
	}

	class LocationModifier : Modifier {
		public long Method {
			get; set;
		}

		public long Location {
			get; set;
		}
	}

	class StepModifier : Modifier {
		public long Thread {
			get; set;
		}

		public int Depth {
			get; set;
		}

		public int Size {
			get; set;
		}

		public int Filter {
			get; set;
		}
	}

	class ThreadModifier : Modifier {
		public long Thread {
			get; set;
		}
	}

	class ExceptionModifier : Modifier {
		public long Type {
			get; set;
		}
		public bool Caught {
			get; set;
		}
		public bool Uncaught {
			get; set;
		}
	}

	class AssemblyModifier : Modifier {
		public long[] Assemblies {
			get; set;
		}
	}

	class SourceFileModifier : Modifier {
		public string[] SourceFiles {
			get; set;
		}
	}

	class TypeNameModifier : Modifier {
		public string[] TypeNames {
			get; set;
		}
	}

	class EventInfo {
		public EventType EventType {
			get; set;
		}

		public int ReqId {
			get; set;
		}

		public SuspendPolicy SuspendPolicy {
			get; set;
		}

		public long ThreadId {
			get; set;
		}

		public long Id {
			get; set;
		}

		public long Location {
			get; set;
		}

		public int Level {
			get; set;
		}

		public string Category {
			get; set;
		}

		public string Message {
			get; set;
		}

		public EventInfo (EventType type, int req_id) {
			EventType = type;
			ReqId = req_id;
		}
	}

	public enum ErrorCode {
		NONE = 0,
		INVALID_OBJECT = 20,
		INVALID_FIELDID = 25,
		INVALID_FRAMEID = 30,
		NOT_IMPLEMENTED = 100,
		NOT_SUSPENDED = 101,
		INVALID_ARGUMENT = 102,
		ERR_UNLOADED = 103,
		ERR_NO_INVOCATION = 104,
		ABSENT_INFORMATION = 105,
		NO_SEQ_POINT_AT_IL_OFFSET = 106
	}

	public class ErrorHandlerEventArgs : EventArgs {

		public ErrorCode ErrorCode {
			get; set;
		}
	}

	/*
	 * Represents the connection to the debuggee
	 */
	public abstract class Connection
	{
		/*
		 * The protocol and the packet format is based on JDWP, the differences 
		 * are in the set of supported events, and the commands.
		 */
		internal const string HANDSHAKE_STRING = "DWP-Handshake";

		internal const int HEADER_LENGTH = 11;

		static readonly bool EnableConnectionLogging = !String.IsNullOrEmpty (Environment.GetEnvironmentVariable ("MONO_SDB_LOG"));
		static int ConnectionId;
		readonly StreamWriter LoggingStream = EnableConnectionLogging ? 
			new StreamWriter (string.Format ("/tmp/sdb_conn_log_{0}", ConnectionId++), false) : null;

		/*
		 * Th version of the wire-protocol implemented by the library. The library
		 * and the debuggee can communicate if they implement the same major version.
		 * If they implement a different minor version, they can communicate, but some
		 * features might not be available. This allows older clients to communicate
		 * with newer runtimes, and vice versa.
		 */
		internal const int MAJOR_VERSION = 2;
		internal const int MINOR_VERSION = 23;

		enum WPSuspendPolicy {
			NONE = 0,
			EVENT_THREAD = 1,
			ALL = 2
		}

		enum CommandSet {
			VM = 1,
			OBJECT_REF = 9,
			STRING_REF = 10,
			THREAD = 11,
			ARRAY_REF = 13,
			EVENT_REQUEST = 15,
			STACK_FRAME = 16,
			APPDOMAIN = 20,
			ASSEMBLY = 21,
			METHOD = 22,
			TYPE = 23,
			MODULE = 24,
			EVENT = 64
		}

		enum EventKind {
			VM_START = 0,
			VM_DEATH = 1,
			THREAD_START = 2,
			THREAD_DEATH = 3,
			APPDOMAIN_CREATE = 4, // Not in JDI
			APPDOMAIN_UNLOAD = 5, // Not in JDI
			METHOD_ENTRY = 6,
			METHOD_EXIT = 7,
			ASSEMBLY_LOAD = 8,
			ASSEMBLY_UNLOAD = 9,
			BREAKPOINT = 10,
			STEP = 11,
			TYPE_LOAD = 12,
			EXCEPTION = 13,
			KEEPALIVE = 14,
			USER_BREAK = 15,
			USER_LOG = 16
		}

		enum ModifierKind {
			COUNT = 1,
			THREAD_ONLY = 3,
			LOCATION_ONLY = 7,
			EXCEPTION_ONLY = 8,
			STEP = 10,
			ASSEMBLY_ONLY = 11,
			SOURCE_FILE_ONLY = 12,
			TYPE_NAME_ONLY = 13
		}

		enum CmdVM {
			VERSION = 1,
			ALL_THREADS = 2,
			SUSPEND = 3,
			RESUME = 4,
			EXIT = 5,
			DISPOSE = 6,
			INVOKE_METHOD = 7,
			SET_PROTOCOL_VERSION = 8,
			ABORT_INVOKE = 9,
			SET_KEEPALIVE = 10,
			GET_TYPES_FOR_SOURCE_FILE = 11,
			GET_TYPES = 12,
			INVOKE_METHODS = 13
		}

		enum CmdEvent {
			COMPOSITE = 100
		}

		enum CmdThread {
			GET_FRAME_INFO = 1,
			GET_NAME = 2,
			GET_STATE = 3,
			GET_INFO = 4,
			/* FIXME: Merge into GET_INFO when the major protocol version is increased */
			GET_ID = 5,
			/* Ditto */
			GET_TID = 6
		}

		enum CmdEventRequest {
			SET = 1,
			CLEAR = 2,
			CLEAR_ALL_BREAKPOINTS = 3
		}

		enum CmdAppDomain {
			GET_ROOT_DOMAIN = 1,
			GET_FRIENDLY_NAME = 2,
			GET_ASSEMBLIES = 3,
			GET_ENTRY_ASSEMBLY = 4,
			CREATE_STRING = 5,
			GET_CORLIB = 6,
			CREATE_BOXED_VALUE = 7
		}

		enum CmdAssembly {
			GET_LOCATION = 1,
			GET_ENTRY_POINT = 2,
			GET_MANIFEST_MODULE = 3,
			GET_OBJECT = 4,
			GET_TYPE = 5,
			GET_NAME = 6
		}

		enum CmdModule {
			GET_INFO = 1,
		}

		enum CmdMethod {
			GET_NAME = 1,
			GET_DECLARING_TYPE = 2,
			GET_DEBUG_INFO = 3,
			GET_PARAM_INFO = 4,
			GET_LOCALS_INFO = 5,
			GET_INFO = 6,
			GET_BODY = 7,
			RESOLVE_TOKEN = 8,
			GET_CATTRS = 9
		}

		enum CmdType {
			GET_INFO = 1,
			GET_METHODS = 2,
			GET_FIELDS = 3,
			GET_VALUES = 4,
			GET_OBJECT = 5,
			GET_SOURCE_FILES = 6,
			SET_VALUES = 7,
			IS_ASSIGNABLE_FROM = 8,
			GET_PROPERTIES = 9,
			GET_CATTRS = 10,
			GET_FIELD_CATTRS = 11,
			GET_PROPERTY_CATTRS = 12,
			/* FIXME: Merge into GET_SOURCE_FILES when the major protocol version is increased */
			GET_SOURCE_FILES_2 = 13,
			/* FIXME: Merge into GET_VALUES when the major protocol version is increased */
			GET_VALUES_2 = 14,
			CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
			GET_INTERFACES = 16,
			GET_INTERFACE_MAP = 17,
			IS_INITIALIZED = 18
		}

		enum BindingFlagsExtensions {
			BINDING_FLAGS_IGNORE_CASE = 0x70000000,
		}

		enum CmdStackFrame {
			GET_VALUES = 1,
			GET_THIS = 2,
			SET_VALUES = 3
		}

		enum CmdArrayRef {
			GET_LENGTH = 1,
			GET_VALUES = 2,
			SET_VALUES = 3
		}

		enum CmdStringRef {
			GET_VALUE = 1,
			GET_LENGTH = 2,
			GET_CHARS = 3
		}

		enum CmdObjectRef {
			GET_TYPE = 1,
			GET_VALUES = 2,
			IS_COLLECTED = 3,
			GET_ADDRESS = 4,
			GET_DOMAIN = 5,
			SET_VALUES = 6,
			GET_INFO = 7,
		}

		class Header {
			public int id;
			public int command_set;
			public int command;
			public int flags;
		}			

		internal static int GetPacketLength (byte[] header) {
			int offset = 0;
			return decode_int (header, ref offset);
		}

		internal static bool IsReplyPacket (byte[] packet) {
			int offset = 8;
			return decode_byte (packet, ref offset) == 0x80;
		}

		internal static int GetPacketId (byte[] packet) {
			int offset = 4;
			return decode_int (packet, ref offset);
		}

		static int decode_byte (byte[] packet, ref int offset) {
			return packet [offset++];
		}

		static int decode_short (byte[] packet, ref int offset) {
			int res = ((int)packet [offset] << 8) | (int)packet [offset + 1];
			offset += 2;
			return res;
		}

		static int decode_int (byte[] packet, ref int offset) {
			int res = ((int)packet [offset] << 24) | ((int)packet [offset + 1] << 16) | ((int)packet [offset + 2] << 8) | (int)packet [offset + 3];
			offset += 4;
			return res;
		}

		static long decode_id (byte[] packet, ref int offset) {
			return decode_int (packet, ref offset);
		}

		static long decode_long (byte[] packet, ref int offset) {
			uint high = (uint)decode_int (packet, ref offset);
			uint low = (uint)decode_int (packet, ref offset);

			return (long)(((ulong)high << 32) | (ulong)low);
		}

		internal static SuspendPolicy decode_suspend_policy (int suspend_policy) {
			switch ((WPSuspendPolicy)suspend_policy) {
			case WPSuspendPolicy.NONE:
				return SuspendPolicy.None;
			case WPSuspendPolicy.EVENT_THREAD:
				return SuspendPolicy.EventThread;
			case WPSuspendPolicy.ALL:
				return SuspendPolicy.All;
			default:
				throw new NotImplementedException ();
			}
		}

		static Header decode_command_header (byte[] packet) {
			int offset = 0;
			Header res = new Header ();

			decode_int (packet, ref offset);
			res.id = decode_int (packet, ref offset);
			res.flags = decode_byte (packet, ref offset);
			res.command_set = decode_byte (packet, ref offset);
			res.command = decode_byte (packet, ref offset);

			return res;
		}

		static void encode_byte (byte[] buf, int b, ref int offset) {
			buf [offset] = (byte)b;
			offset ++;
		}

		static void encode_int (byte[] buf, int i, ref int offset) {
			buf [offset] = (byte)((i >> 24) & 0xff);
			buf [offset + 1] = (byte)((i >> 16) & 0xff);
			buf [offset + 2] = (byte)((i >> 8) & 0xff);
			buf [offset + 3] = (byte)((i >> 0) & 0xff);
			offset += 4;
		}

		static void encode_id (byte[] buf, long id, ref int offset) {
			encode_int (buf, (int)id, ref offset);
		}

		static void encode_long (byte[] buf, long l, ref int offset) {
			encode_int (buf, (int)((l >> 32) & 0xffffffff), ref offset);
			encode_int (buf, (int)(l & 0xffffffff), ref offset);
		}

		internal static byte[] EncodePacket (int id, int commandSet, int command, byte[] data, int dataLen) {
			byte[] buf = new byte [dataLen + 11];
			int offset = 0;
			
			encode_int (buf, buf.Length, ref offset);
			encode_int (buf, id, ref offset);
			encode_byte (buf, 0, ref offset);
			encode_byte (buf, commandSet, ref offset);
			encode_byte (buf, command, ref offset);

			for (int i = 0; i < dataLen; ++i)
				buf [offset + i] = data [i];

			return buf;
		}

		class PacketReader {
			byte[] packet;
			int offset;

			public PacketReader (byte[] packet) {
				this.packet = packet;

				// For event packets
				Header header = decode_command_header (packet);
				CommandSet = (CommandSet)header.command_set;
				Command = header.command;

				// For reply packets
				offset = 0;
				ReadInt (); // length
				ReadInt (); // id
				ReadByte (); // flags
				ErrorCode = ReadShort ();
			}

			public CommandSet CommandSet {
				get; set;
			}

			public int Command {
				get; set;
			}

			public int ErrorCode {
				get; set;
			}

			public int Offset {
				get {
					return offset;
				}
			}

			public int ReadByte () {
				return decode_byte (packet, ref offset);
			}

			public int ReadShort () {
				return decode_short (packet, ref offset);
			}

			public int ReadInt () {
				return decode_int (packet, ref offset);
			}

			public long ReadId () {
				return decode_id (packet, ref offset);
			}

			public long ReadLong () {
				return decode_long (packet, ref offset);
			}

			public float ReadFloat () {
				float f = DataConverter.FloatFromBE (packet, offset);
				offset += 4;
				return f;
			}

			public double ReadDouble () {
				double d = DataConverter.DoubleFromBE (packet, offset);
				offset += 8;
				return d;
			}

			public string ReadString () {
				int len = decode_int (packet, ref offset);
				string res = new String (Encoding.UTF8.GetChars (packet, offset, len));
				offset += len;
				return res;
			}

			public ValueImpl ReadValue () {
				ElementType etype = (ElementType)ReadByte ();

				switch (etype) {
				case ElementType.Void:
					return new ValueImpl { Type = etype };
				case ElementType.I1:
					return new ValueImpl { Type = etype, Value = (sbyte)ReadInt () };
				case ElementType.U1:
					return new ValueImpl { Type = etype, Value = (byte)ReadInt () };
				case ElementType.Boolean:
					return new ValueImpl { Type = etype, Value = ReadInt () != 0 };
				case ElementType.I2:
					return new ValueImpl { Type = etype, Value = (short)ReadInt () };
				case ElementType.U2:
					return new ValueImpl { Type = etype, Value = (ushort)ReadInt () };
				case ElementType.Char:
					return new ValueImpl { Type = etype, Value = (char)ReadInt () };
				case ElementType.I4:
					return new ValueImpl { Type = etype, Value = ReadInt () };
				case ElementType.U4:
					return new ValueImpl { Type = etype, Value = (uint)ReadInt () };
				case ElementType.I8:
					return new ValueImpl { Type = etype, Value = ReadLong () };
				case ElementType.U8:
					return new ValueImpl { Type = etype, Value = (ulong)ReadLong () };
				case ElementType.R4:
					return new ValueImpl { Type = etype, Value = ReadFloat () };
				case ElementType.R8:
					return new ValueImpl { Type = etype, Value = ReadDouble () };
				case ElementType.I:
				case ElementType.U:
				case ElementType.Ptr:
					// FIXME: The client and the debuggee might have different word sizes
					return new ValueImpl { Type = etype, Value = ReadLong () };
				case ElementType.String:
				case ElementType.SzArray:
				case ElementType.Class:
				case ElementType.Array:
				case ElementType.Object:
					long objid = ReadId ();
					return new ValueImpl () { Type = etype, Objid = objid };
				case ElementType.ValueType:
					bool is_enum = ReadByte () == 1;
					long klass = ReadId ();
					long nfields = ReadInt ();
					ValueImpl[] fields = new ValueImpl [nfields];
					for (int i = 0; i < nfields; ++i)
						fields [i] = ReadValue ();
					return new ValueImpl () { Type = etype, Klass = klass, Fields = fields, IsEnum = is_enum };
				case (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL:
					return new ValueImpl { Type = etype };
				case (ElementType)ValueTypeId.VALUE_TYPE_ID_TYPE:
					return new ValueImpl () { Type = etype, Id = ReadId () };
				default:
					throw new NotImplementedException ("Unable to handle type " + etype);
				}
			}

			public long[] ReadIds (int n) {
				long[] res = new long [n];
				for (int i = 0; i < n; ++i)
					res [i] = ReadId ();
				return res;
			}
		}

		class PacketWriter {

			byte[] data;
			int offset;

			public PacketWriter () {
				data = new byte [1024];
				offset = 0;
			}

			void MakeRoom (int size) {
				if (offset + size >= data.Length) {
					int new_len = data.Length * 2;
					while (new_len < offset + size) {
						new_len *= 2;
					}
					byte[] new_data = new byte [new_len];
					Array.Copy (data, new_data, data.Length);
					data = new_data;
				}
			}

			public PacketWriter WriteByte (byte val) {
				MakeRoom (1);
				encode_byte (data, val, ref offset);
				return this;
			}

			public PacketWriter WriteInt (int val) {
				MakeRoom (4);
				encode_int (data, val, ref offset);
				return this;
			}

			public PacketWriter WriteId (long id) {
				MakeRoom (8);
				encode_id (data, id, ref offset);
				return this;
			}

			public PacketWriter WriteLong (long val) {
				MakeRoom (8);
				encode_long (data, val, ref offset);
				return this;
			}

			public PacketWriter WriteFloat (float f) {
				MakeRoom (8);
				byte[] b = DataConverter.GetBytesBE (f);
				for (int i = 0; i < 4; ++i)
					data [offset + i] = b [i];
				offset += 4;
				return this;
			}

			public PacketWriter WriteDouble (double d) {
				MakeRoom (8);
				byte[] b = DataConverter.GetBytesBE (d);
				for (int i = 0; i < 8; ++i)
					data [offset + i] = b [i];
				offset += 8;
				return this;
			}

			public PacketWriter WriteInts (int[] ids) {
				for (int i = 0; i < ids.Length; ++i)
					WriteInt (ids [i]);
				return this;
			}

			public PacketWriter WriteIds (long[] ids) {
				for (int i = 0; i < ids.Length; ++i)
					WriteId (ids [i]);
				return this;
			}

			public PacketWriter WriteString (string s) {
				if (s == null)
					return WriteInt (-1);

				byte[] b = Encoding.UTF8.GetBytes (s);
				MakeRoom (4);
				encode_int (data, b.Length, ref offset);
				MakeRoom (b.Length);
				Buffer.BlockCopy (b, 0, data, offset, b.Length);
				offset += b.Length;
				return this;
			}

			public PacketWriter WriteBool (bool val) {
				WriteByte (val ? (byte)1 : (byte)0);
				return this;
			}

			public PacketWriter WriteValue (ValueImpl v) {
				ElementType t;

				if (v.Value != null)
					t = TypeCodeToElementType (Type.GetTypeCode (v.Value.GetType ()));
				else
					t = v.Type;
				WriteByte ((byte)t);
				switch (t) {
				case ElementType.Boolean:
					WriteInt ((bool)v.Value ? 1 : 0);
					break;
				case ElementType.Char:
					WriteInt ((int)(char)v.Value);
					break;
				case ElementType.I1:
					WriteInt ((int)(sbyte)v.Value);
					break;
				case ElementType.U1:
					WriteInt ((int)(byte)v.Value);
					break;
				case ElementType.I2:
					WriteInt ((int)(short)v.Value);
					break;
				case ElementType.U2:
					WriteInt ((int)(ushort)v.Value);
					break;
				case ElementType.I4:
					WriteInt ((int)(int)v.Value);
					break;
				case ElementType.U4:
					WriteInt ((int)(uint)v.Value);
					break;
				case ElementType.I8:
					WriteLong ((long)(long)v.Value);
					break;
				case ElementType.U8:
					WriteLong ((long)(ulong)v.Value);
					break;
				case ElementType.R4:
					WriteFloat ((float)v.Value);
					break;
				case ElementType.R8:
					WriteDouble ((double)v.Value);
					break;
				case ElementType.String:
				case ElementType.SzArray:
				case ElementType.Class:
				case ElementType.Array:
				case ElementType.Object:
					WriteId (v.Objid);
					break;
				case ElementType.ValueType:
					// FIXME: 
					if (v.IsEnum)
						throw new NotImplementedException ();
					WriteByte (0);
					WriteId (v.Klass);
					WriteInt (v.Fields.Length);
					for (int i = 0; i < v.Fields.Length; ++i)
						WriteValue (v.Fields [i]);
					break;
				case (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL:
					break;
				default:
					throw new NotImplementedException ();
				}

				return this;
			}

			public PacketWriter WriteValues (ValueImpl[] values) {
				for (int i = 0; i < values.Length; ++i)
					WriteValue (values [i]);
				return this;
			}

			public byte[] Data {
				get {
					return data;
				}
			}

			public int Offset {
				get {
					return offset;
				}
			}
		}

		delegate void ReplyCallback (int packet_id, byte[] packet);

		bool closed;
		Thread receiver_thread;
		Dictionary<int, byte[]> reply_packets;
		Dictionary<int, ReplyCallback> reply_cbs;
		Dictionary<int, int> reply_cb_counts;
		object reply_packets_monitor;

		internal event EventHandler<ErrorHandlerEventArgs> ErrorHandler;

		protected Connection () {
			closed = false;
			reply_packets = new Dictionary<int, byte[]> ();
			reply_cbs = new Dictionary<int, ReplyCallback> ();
			reply_cb_counts = new Dictionary<int, int> ();
			reply_packets_monitor = new Object ();
		}
		
		protected abstract int TransportReceive (byte[] buf, int buf_offset, int len);
		protected abstract int TransportSend (byte[] buf, int buf_offset, int len);
		protected abstract void TransportSetTimeouts (int send_timeout, int receive_timeout);
		protected abstract void TransportClose ();

		internal VersionInfo Version;
		
		int Receive (byte[] buf, int buf_offset, int len) {
			int offset = 0;

			while (offset < len) {
				int n = TransportReceive (buf, buf_offset + offset, len - offset);

				if (n == 0)
					return offset;
				offset += n;
			}

			return offset;
		}
		
		// Do the wire protocol handshake
		internal void Connect () {
			byte[] buf = new byte [HANDSHAKE_STRING.Length];
			char[] cbuf = new char [buf.Length];

			// FIXME: Add a timeout
			int n = Receive (buf, 0, buf.Length);
			if (n == 0)
				throw new IOException ("DWP Handshake failed.");
			for (int i = 0; i < buf.Length; ++i)
				cbuf [i] = (char)buf [i];

			if (new String (cbuf) != HANDSHAKE_STRING)
				throw new IOException ("DWP Handshake failed.");
			
			TransportSend (buf, 0, buf.Length);

			receiver_thread = new Thread (new ThreadStart (receiver_thread_main));
			receiver_thread.Name = "SDB Receiver";
			receiver_thread.IsBackground = true;
			receiver_thread.Start ();

			Version = VM_GetVersion ();

			//
			// Tell the debuggee our protocol version, so newer debuggees can work
			// with older clients
			//

			//
			// Older debuggees might not support this request
			EventHandler<ErrorHandlerEventArgs> OrigErrorHandler = ErrorHandler;
			ErrorHandler = null;
			ErrorHandler += delegate (object sender, ErrorHandlerEventArgs args) {
				throw new NotSupportedException ();
			};
			try {
				VM_SetProtocolVersion (MAJOR_VERSION, MINOR_VERSION);
			} catch (NotSupportedException) {
			}
			ErrorHandler = OrigErrorHandler;
		}

		internal byte[] ReadPacket () {
			// FIXME: Throw ClosedConnectionException () if the connection is closed
			// FIXME: Throw ClosedConnectionException () if another thread closes the connection
			// FIXME: Locking
			byte[] header = new byte [HEADER_LENGTH];

			int len = Receive (header, 0, header.Length);
			if (len == 0)
				return new byte [0];
			if (len != HEADER_LENGTH) {
				// FIXME:
				throw new IOException ("Packet of length " + len + " is read.");
			}

			int packetLength = GetPacketLength (header);
			if (packetLength < 11)
				throw new IOException ("Invalid packet length.");

			if (packetLength == 11) {
				return header;
			} else {
				byte[] buf = new byte [packetLength];
				for (int i = 0; i < header.Length; ++i)
					buf [i] = header [i];
				len = Receive (buf, header.Length, packetLength - header.Length);
				if (len != packetLength - header.Length)
					throw new IOException ();
				return buf;
			}
		}

		internal void WritePacket (byte[] packet) {
			// FIXME: Throw ClosedConnectionException () if the connection is closed
			// FIXME: Throw ClosedConnectionException () if another thread closes the connection
			// FIXME: Locking
			TransportSend (packet, 0, packet.Length);
		}

		internal void Close () {
			closed = true;
		}

		internal bool IsClosed {
			get {
				return closed;
			}
		}

		bool disconnected;

		void receiver_thread_main () {
			while (!closed) {
				try {
					bool res = ReceivePacket ();
					if (!res)
						break;
				} catch (Exception ex) {
					if (!closed) {
						Console.WriteLine (ex);
					}
					break;
				}
			}

			lock (reply_packets_monitor) {
				disconnected = true;
				Monitor.PulseAll (reply_packets_monitor);
				TransportClose ();
			}
			EventHandler.VMDisconnect (0, 0, null);
		}

		bool ReceivePacket () {
				byte[] packet = ReadPacket ();

				if (packet.Length == 0) {
					return false;
				}

				if (IsReplyPacket (packet)) {
					int id = GetPacketId (packet);
					ReplyCallback cb = null;
					lock (reply_packets_monitor) {
						reply_cbs.TryGetValue (id, out cb);
						if (cb == null) {
							reply_packets [id] = packet;
							Monitor.PulseAll (reply_packets_monitor);
						} else {
							int c = reply_cb_counts [id];
							c --;
							if (c == 0) {
								reply_cbs.Remove (id);
								reply_cb_counts.Remove (id);
							}
						}
					}

					if (cb != null)
						cb.Invoke (id, packet);
				} else {
					PacketReader r = new PacketReader (packet);

					if (r.CommandSet == CommandSet.EVENT && r.Command == (int)CmdEvent.COMPOSITE) {
						int spolicy = r.ReadByte ();
						int nevents = r.ReadInt ();

						SuspendPolicy suspend_policy = decode_suspend_policy (spolicy);

						EventInfo[] events = new EventInfo [nevents];

						for (int i = 0; i < nevents; ++i) {
							EventKind kind = (EventKind)r.ReadByte ();
							int req_id = r.ReadInt ();

							EventType etype = (EventType)kind;

							if (kind == EventKind.VM_START) {
								long thread_id = r.ReadId ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id };
								//EventHandler.VMStart (req_id, thread_id, null);
							} else if (kind == EventKind.VM_DEATH) {
								//EventHandler.VMDeath (req_id, 0, null);
								events [i] = new EventInfo (etype, req_id) { };
							} else if (kind == EventKind.THREAD_START) {
								long thread_id = r.ReadId ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = thread_id };
								//EventHandler.ThreadStart (req_id, thread_id, thread_id);
							} else if (kind == EventKind.THREAD_DEATH) {
								long thread_id = r.ReadId ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = thread_id };
								//EventHandler.ThreadDeath (req_id, thread_id, thread_id);
							} else if (kind == EventKind.ASSEMBLY_LOAD) {
								long thread_id = r.ReadId ();
								long id = r.ReadId ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
								//EventHandler.AssemblyLoad (req_id, thread_id, id);
							} else if (kind == EventKind.ASSEMBLY_UNLOAD) {
								long thread_id = r.ReadId ();
								long id = r.ReadId ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
								//EventHandler.AssemblyUnload (req_id, thread_id, id);
							} else if (kind == EventKind.TYPE_LOAD) {
								long thread_id = r.ReadId ();
								long id = r.ReadId ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
								//EventHandler.TypeLoad (req_id, thread_id, id);
							} else if (kind == EventKind.METHOD_ENTRY) {
								long thread_id = r.ReadId ();
								long id = r.ReadId ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
								//EventHandler.MethodEntry (req_id, thread_id, id);
							} else if (kind == EventKind.METHOD_EXIT) {
								long thread_id = r.ReadId ();
								long id = r.ReadId ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
								//EventHandler.MethodExit (req_id, thread_id, id);
							} else if (kind == EventKind.BREAKPOINT) {
								long thread_id = r.ReadId ();
								long id = r.ReadId ();
								long loc = r.ReadLong ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
								//EventHandler.Breakpoint (req_id, thread_id, id, loc);
							} else if (kind == EventKind.STEP) {
								long thread_id = r.ReadId ();
								long id = r.ReadId ();
								long loc = r.ReadLong ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
								//EventHandler.Step (req_id, thread_id, id, loc);
							} else if (kind == EventKind.EXCEPTION) {
								long thread_id = r.ReadId ();
								long id = r.ReadId ();
								long loc = 0; // FIXME
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
								//EventHandler.Exception (req_id, thread_id, id, loc);
							} else if (kind == EventKind.APPDOMAIN_CREATE) {
								long thread_id = r.ReadId ();
								long id = r.ReadId ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
								//EventHandler.AppDomainCreate (req_id, thread_id, id);
							} else if (kind == EventKind.APPDOMAIN_UNLOAD) {
								long thread_id = r.ReadId ();
								long id = r.ReadId ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
								//EventHandler.AppDomainUnload (req_id, thread_id, id);
							} else if (kind == EventKind.USER_BREAK) {
								long thread_id = r.ReadId ();
								long id = 0;
								long loc = 0;
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
								//EventHandler.Exception (req_id, thread_id, id, loc);
							} else if (kind == EventKind.USER_LOG) {
								long thread_id = r.ReadId ();
								int level = r.ReadInt ();
								string category = r.ReadString ();
								string message = r.ReadString ();
								events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Level = level, Category = category, Message = message };
								//EventHandler.Exception (req_id, thread_id, id, loc);
							} else if (kind == EventKind.KEEPALIVE) {
								events [i] = new EventInfo (etype, req_id) { };
							} else {
								throw new NotImplementedException ("Unknown event kind: " + kind);
							}
						}

						EventHandler.Events (suspend_policy, events);
					}
				}

				return true;
		}

		internal IEventHandler EventHandler {
			get; set;
		}

		static String CommandString (CommandSet command_set, int command)
		{
			string cmd;
			switch (command_set) {
			case CommandSet.VM:
				cmd = ((CmdVM)command).ToString ();
				break;
			case CommandSet.OBJECT_REF:
				cmd = ((CmdObjectRef)command).ToString ();
				break;
			case CommandSet.STRING_REF:
				cmd = ((CmdStringRef)command).ToString ();
				break;
			case CommandSet.THREAD:
				cmd = ((CmdThread)command).ToString ();
				break;
			case CommandSet.ARRAY_REF:
				cmd = ((CmdArrayRef)command).ToString ();
				break;
			case CommandSet.EVENT_REQUEST:
				cmd = ((CmdEventRequest)command).ToString ();
				break;
			case CommandSet.STACK_FRAME:
				cmd = ((CmdStackFrame)command).ToString ();
				break;
			case CommandSet.APPDOMAIN:
				cmd = ((CmdAppDomain)command).ToString ();
				break;
			case CommandSet.ASSEMBLY:
				cmd = ((CmdAssembly)command).ToString ();
				break;
			case CommandSet.METHOD:
				cmd = ((CmdMethod)command).ToString ();
				break;
			case CommandSet.TYPE:
				cmd = ((CmdType)command).ToString ();
				break;
			case CommandSet.MODULE:
				cmd = ((CmdModule)command).ToString ();
				break;
			case CommandSet.EVENT:
				cmd = ((CmdEvent)command).ToString ();
				break;
			default:
				cmd = command.ToString ();
				break;
			}
			return string.Format ("[{0} {1}]", command_set, cmd);
		}

		long total_protocol_ticks;

		void LogPacket (int packet_id, byte[] encoded_packet, byte[] reply_packet, CommandSet command_set, int command, Stopwatch watch) {
			watch.Stop ();
			total_protocol_ticks += watch.ElapsedTicks;
			var ts = TimeSpan.FromTicks (total_protocol_ticks);
			string msg = string.Format ("Packet: {0} sent: {1} received: {2} ms: {3} total ms: {4} {5}",
			   packet_id, encoded_packet.Length, reply_packet.Length, watch.ElapsedMilliseconds,
			   (ts.Seconds * 1000) + ts.Milliseconds,
			   CommandString (command_set, command));

			LoggingStream.WriteLine (msg);
			LoggingStream.Flush ();
		}

		/* Send a request and call cb when a result is received */
		int Send (CommandSet command_set, int command, PacketWriter packet, Action<PacketReader> cb, int count) {
			int id = IdGenerator;

			Stopwatch watch = null;
			if (EnableConnectionLogging)
				watch = Stopwatch.StartNew ();

			byte[] encoded_packet;
			if (packet == null)
				encoded_packet = EncodePacket (id, (int)command_set, command, null, 0);
			else
				encoded_packet = EncodePacket (id, (int)command_set, command, packet.Data, packet.Offset);

			lock (reply_packets_monitor) {
				reply_cbs [id] = delegate (int packet_id, byte[] p) {
					if (EnableConnectionLogging)
						LogPacket (packet_id, encoded_packet, p, command_set, command, watch);
					/* Run the callback on a tp thread to avoid blocking the receive thread */
					PacketReader r = new PacketReader (p);
					cb.BeginInvoke (r, null, null);
				};
				reply_cb_counts [id] = count;
			}

			WritePacket (encoded_packet);

			return id;
		}

		PacketReader SendReceive (CommandSet command_set, int command, PacketWriter packet) {
			int id = IdGenerator;
			Stopwatch watch = null;

			if (disconnected)
				throw new VMDisconnectedException ();

			if (EnableConnectionLogging)
				watch = Stopwatch.StartNew ();

			byte[] encoded_packet;

			if (packet == null)
				encoded_packet = EncodePacket (id, (int)command_set, command, null, 0);
			else
				encoded_packet = EncodePacket (id, (int)command_set, command, packet.Data, packet.Offset);

			WritePacket (encoded_packet);

			int packetId = id;

			/* Wait for the reply packet */
			while (true) {
				lock (reply_packets_monitor) {
					if (reply_packets.ContainsKey (packetId)) {
						byte[] reply = reply_packets [packetId];
						reply_packets.Remove (packetId);
						PacketReader r = new PacketReader (reply);

						if (EnableConnectionLogging)
							LogPacket (packetId, encoded_packet, reply, command_set, command, watch);
						if (r.ErrorCode != 0) {
							if (ErrorHandler != null)
								ErrorHandler (this, new ErrorHandlerEventArgs () { ErrorCode = (ErrorCode)r.ErrorCode });
							throw new NotImplementedException ("No error handler set.");
						} else {
							return r;
						}
					} else {
						if (disconnected)
							throw new VMDisconnectedException ();
						Monitor.Wait (reply_packets_monitor);
					}
				}
			}
		}

		PacketReader SendReceive (CommandSet command_set, int command) {
			return SendReceive (command_set, command, null);
		}

		int packet_id_generator;

		int IdGenerator {
			get {
				return Interlocked.Increment (ref packet_id_generator);
			}
		}

		CattrInfo[] ReadCattrs (PacketReader r) {
			CattrInfo[] res = new CattrInfo [r.ReadInt ()];
			for (int i = 0; i < res.Length; ++i) {
				CattrInfo info = new CattrInfo ();
				info.ctor_id = r.ReadId ();
				info.ctor_args = new ValueImpl [r.ReadInt ()];
				for (int j = 0; j < info.ctor_args.Length; ++j) {
					info.ctor_args [j] = r.ReadValue ();
				}
				info.named_args = new CattrNamedArgInfo [r.ReadInt ()];
				for (int j = 0; j < info.named_args.Length; ++j) {
					CattrNamedArgInfo arg = new CattrNamedArgInfo ();
					int arg_type = r.ReadByte ();
					arg.is_property = arg_type == 0x54;
					arg.id = r.ReadId ();
					arg.value = r.ReadValue ();
					info.named_args [j] = arg;
				}
				res [i] = info;
			}
			return res;
		}

		static ElementType TypeCodeToElementType (TypeCode c) {
			switch (c) {
			case TypeCode.Boolean:
				return ElementType.Boolean;
			case TypeCode.Char:
				return ElementType.Char;
			case TypeCode.SByte:
				return ElementType.I1;
			case TypeCode.Byte:
				return ElementType.U1;
			case TypeCode.Int16:
				return ElementType.I2;
			case TypeCode.UInt16:
				return ElementType.U2;
			case TypeCode.Int32:
				return ElementType.I4;
			case TypeCode.UInt32:
				return ElementType.U4;
			case TypeCode.Int64:
				return ElementType.I8;
			case TypeCode.UInt64:
				return ElementType.U8;
			case TypeCode.Single:
				return ElementType.R4;
			case TypeCode.Double:
				return ElementType.R8;
			default:
				throw new NotImplementedException ();
			}
		}

		/*
		 * Implementation of debugger commands
		 */

		internal VersionInfo VM_GetVersion () {
			var res = SendReceive (CommandSet.VM, (int)CmdVM.VERSION, null);
			VersionInfo info = new VersionInfo ();
			info.VMVersion = res.ReadString ();
			info.MajorVersion = res.ReadInt ();
			info.MinorVersion = res.ReadInt ();
			return info;
		}

		internal void VM_SetProtocolVersion (int major, int minor) {
			SendReceive (CommandSet.VM, (int)CmdVM.SET_PROTOCOL_VERSION, new PacketWriter ().WriteInt (major).WriteInt (minor));
		}

		internal long[] VM_GetThreads () {
			var res = SendReceive (CommandSet.VM, (int)CmdVM.ALL_THREADS, null);
			int len = res.ReadInt ();
			long[] arr = new long [len];
			for (int i = 0; i < len; ++i)
				arr [i] = res.ReadId ();
			return arr;
		}

		internal void VM_Suspend () {
			SendReceive (CommandSet.VM, (int)CmdVM.SUSPEND);
		}

		internal void VM_Resume () {
			SendReceive (CommandSet.VM, (int)CmdVM.RESUME);
		}

		internal void VM_Exit (int exitCode) {
			SendReceive (CommandSet.VM, (int)CmdVM.EXIT, new PacketWriter ().WriteInt (exitCode));
		}

		internal void VM_Dispose () {
			SendReceive (CommandSet.VM, (int)CmdVM.DISPOSE);
		}

		internal ValueImpl VM_InvokeMethod (long thread, long method, ValueImpl this_arg, ValueImpl[] arguments, InvokeFlags flags, out ValueImpl exc) {
			exc = null;
			PacketReader r = SendReceive (CommandSet.VM, (int)CmdVM.INVOKE_METHOD, new PacketWriter ().WriteId (thread).WriteInt ((int)flags).WriteId (method).WriteValue (this_arg).WriteInt (arguments.Length).WriteValues (arguments));
			if (r.ReadByte () == 0) {
				exc = r.ReadValue ();
				return null;
			} else {
				return r.ReadValue ();
			}
		}

		internal delegate void InvokeMethodCallback (ValueImpl v, ValueImpl exc, ErrorCode error, object state);

		internal int VM_BeginInvokeMethod (long thread, long method, ValueImpl this_arg, ValueImpl[] arguments, InvokeFlags flags, InvokeMethodCallback callback, object state) {
			return Send (CommandSet.VM, (int)CmdVM.INVOKE_METHOD, new PacketWriter ().WriteId (thread).WriteInt ((int)flags).WriteId (method).WriteValue (this_arg).WriteInt (arguments.Length).WriteValues (arguments), delegate (PacketReader r) {
					ValueImpl v, exc;

					if (r.ErrorCode != 0) {
						callback (null, null, (ErrorCode)r.ErrorCode, state);
					} else {
						if (r.ReadByte () == 0) {
							exc = r.ReadValue ();
							v = null;
						} else {
							v = r.ReadValue ();
							exc = null;
						}

						callback (v, exc, 0, state);
					}
				}, 1);
		}

		internal int VM_BeginInvokeMethods (long thread, long[] methods, ValueImpl this_arg, List<ValueImpl[]> arguments, InvokeFlags flags, InvokeMethodCallback callback, object state) {
			// FIXME: Merge this with INVOKE_METHOD
			var w = new PacketWriter ();
			w.WriteId (thread);
			w.WriteInt ((int)flags);
			w.WriteInt (methods.Length);
			for (int i = 0; i < methods.Length; ++i) {
				w.WriteId (methods [i]);
				w.WriteValue (this_arg);
				w.WriteInt (arguments [i].Length);
				w.WriteValues (arguments [i]);
			}
			return Send (CommandSet.VM, (int)CmdVM.INVOKE_METHODS, w, delegate (PacketReader r) {
					ValueImpl v, exc;

					if (r.ErrorCode != 0) {
						callback (null, null, (ErrorCode)r.ErrorCode, state);
					} else {
						if (r.ReadByte () == 0) {
							exc = r.ReadValue ();
							v = null;
						} else {
							v = r.ReadValue ();
							exc = null;
						}

						callback (v, exc, 0, state);
					}
				}, methods.Length);
		}

		internal void VM_AbortInvoke (long thread, int id)
		{
			SendReceive (CommandSet.VM, (int)CmdVM.ABORT_INVOKE, new PacketWriter ().WriteId (thread).WriteInt (id));
		}

		internal void SetSocketTimeouts (int send_timeout, int receive_timeout, int keepalive_interval)
		{
			TransportSetTimeouts (send_timeout, receive_timeout);
			SendReceive (CommandSet.VM, (int)CmdVM.SET_KEEPALIVE, new PacketWriter ().WriteId (keepalive_interval));
		}

		internal long[] VM_GetTypesForSourceFile (string fname, bool ignoreCase) {
			var res = SendReceive (CommandSet.VM, (int)CmdVM.GET_TYPES_FOR_SOURCE_FILE, new PacketWriter ().WriteString (fname).WriteBool (ignoreCase));
			int count = res.ReadInt ();
			long[] types = new long [count];
			for (int i = 0; i < count; ++i)
				types [i] = res.ReadId ();
			return types;
		}

		internal long[] VM_GetTypes (string name, bool ignoreCase) {
			var res = SendReceive (CommandSet.VM, (int)CmdVM.GET_TYPES, new PacketWriter ().WriteString (name).WriteBool (ignoreCase));
			int count = res.ReadInt ();
			long[] types = new long [count];
			for (int i = 0; i < count; ++i)
				types [i] = res.ReadId ();
			return types;
		}

		/*
		 * DOMAIN
		 */

		internal long RootDomain {
			get {
				return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_ROOT_DOMAIN, null).ReadId ();
			}
		}

		internal string Domain_GetName (long id) {
			return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_FRIENDLY_NAME, new PacketWriter ().WriteId (id)).ReadString ();
		}

		internal long[] Domain_GetAssemblies (long id) {
			var res = SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_ASSEMBLIES, new PacketWriter ().WriteId (id));
			int count = res.ReadInt ();
			long[] assemblies = new long [count];
			for (int i = 0; i < count; ++i)
				assemblies [i] = res.ReadId ();
			return assemblies;
		}

		internal long Domain_GetEntryAssembly (long id) {
			return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_ENTRY_ASSEMBLY, new PacketWriter ().WriteId (id)).ReadId ();
		}

		internal long Domain_GetCorlib (long id) {
			return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_CORLIB, new PacketWriter ().WriteId (id)).ReadId ();
		}

		internal long Domain_CreateString (long id, string s) {
			return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.CREATE_STRING, new PacketWriter ().WriteId (id).WriteString (s)).ReadId ();
		}

		internal long Domain_CreateBoxedValue (long id, long type_id, ValueImpl v) {
			return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.CREATE_BOXED_VALUE, new PacketWriter ().WriteId (id).WriteId (type_id).WriteValue (v)).ReadId ();
		}

		/*
		 * METHOD
		 */

		internal string Method_GetName (long id) {
			return SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_NAME, new PacketWriter ().WriteId (id)).ReadString ();
		}

		internal long Method_GetDeclaringType (long id) {
			return SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_DECLARING_TYPE, new PacketWriter ().WriteId (id)).ReadId ();
		}

		internal DebugInfo Method_GetDebugInfo (long id) {
			var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_DEBUG_INFO, new PacketWriter ().WriteId (id));

			DebugInfo info = new DebugInfo ();
			info.max_il_offset = res.ReadInt ();

			SourceInfo[] sources = null;
			if (Version.AtLeast (2, 13)) {
				int n = res.ReadInt ();
				sources = new SourceInfo [n];
				for (int i = 0; i < n; ++i) {
					sources [i].source_file = res.ReadString ();
					if (Version.AtLeast (2, 14)) {
						sources [i].hash = new byte [16];
						for (int j = 0; j < 16; ++j)
							sources [i].hash [j] = (byte)res.ReadByte ();
					}
				}
			} else {
				sources = new SourceInfo [1];
				sources [0].source_file = res.ReadString ();
			}

			int n_il_offsets = res.ReadInt ();
			info.il_offsets = new int [n_il_offsets];
			info.line_numbers = new int [n_il_offsets];
			info.source_files = new SourceInfo [n_il_offsets];
			info.column_numbers = new int [n_il_offsets];
			for (int i = 0; i < n_il_offsets; ++i) {
				info.il_offsets [i] = res.ReadInt ();
				info.line_numbers [i] = res.ReadInt ();
				if (Version.AtLeast (2, 12)) {
					int idx = res.ReadInt ();
					info.source_files [i] = idx >= 0 ? sources [idx] : default (SourceInfo);
				} else {
					info.source_files [i] = sources [0];
				}
				if (Version.AtLeast (2, 19))
					info.column_numbers [i] = res.ReadInt ();
				else
					info.column_numbers [i] = 0;
			}

			return info;
		}

		internal ParamInfo Method_GetParamInfo (long id) {
			var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_PARAM_INFO, new PacketWriter ().WriteId (id));

			ParamInfo info = new ParamInfo ();
			info.call_conv = res.ReadInt ();
			info.param_count = res.ReadInt ();
			info.generic_param_count = res.ReadInt ();
			info.ret_type = res.ReadId ();
			info.param_types = new long [info.param_count];
			for (int i = 0; i < info.param_count; ++i)
				info.param_types [i] = res.ReadId ();
			info.param_names = new string [info.param_count];			
			for (int i = 0; i < info.param_count; ++i)
				info.param_names [i] = res.ReadString ();

			return info;
		}

		internal LocalsInfo Method_GetLocalsInfo (long id) {
			var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_LOCALS_INFO, new PacketWriter ().WriteId (id));

			LocalsInfo info = new LocalsInfo ();
			int nlocals = res.ReadInt ();
			info.types = new long [nlocals];
			for (int i = 0; i < nlocals; ++i)
				info.types [i] = res.ReadId ();
			info.names = new string [nlocals];
			for (int i = 0; i < nlocals; ++i)
				info.names [i] = res.ReadString ();
			info.live_range_start = new int [nlocals];
			info.live_range_end = new int [nlocals];
			for (int i = 0; i < nlocals; ++i) {
				info.live_range_start [i] = res.ReadInt ();
				info.live_range_end [i] = res.ReadInt ();
			}

			return info;
		}

		internal MethodInfo Method_GetInfo (long id) {
			var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_INFO, new PacketWriter ().WriteId (id));

			MethodInfo info = new MethodInfo ();
			info.attributes = res.ReadInt ();
			info.iattributes = res.ReadInt ();
			info.token = res.ReadInt ();
			if (Version.AtLeast (2, 12)) {
				int attrs = res.ReadByte ();
				if ((attrs & (1 << 0)) != 0)
					info.is_gmd = true;
				if ((attrs & (1 << 1)) != 0)
					info.is_generic_method = true;
				info.gmd = res.ReadId ();
				if (Version.AtLeast (2, 15)) {
					if (info.is_generic_method) {
						int n = res.ReadInt ();
						info.type_args = res.ReadIds (n);
					}
				}
			}
			return info;
		}

		internal MethodBodyInfo Method_GetBody (long id) {
			var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_BODY, new PacketWriter ().WriteId (id));

			MethodBodyInfo info = new MethodBodyInfo ();
			info.il = new byte [res.ReadInt ()];
			for (int i = 0; i < info.il.Length; ++i)
				info.il [i] = (byte)res.ReadByte ();

			if (Version.AtLeast (2, 18)) {
				info.clauses = new ExceptionClauseInfo [res.ReadInt ()];

				for (int i = 0; i < info.clauses.Length; ++i) {
					var clause = new ExceptionClauseInfo {
						flags = (ExceptionClauseFlags) res.ReadInt (),
						try_offset = res.ReadInt (),
						try_length = res.ReadInt (),
						handler_offset = res.ReadInt (),
						handler_length = res.ReadInt (),
					};

					if (clause.flags == ExceptionClauseFlags.None)
						clause.catch_type_id = res.ReadId ();
					else if (clause.flags == ExceptionClauseFlags.Filter)
						clause.filter_offset = res.ReadInt ();

					info.clauses [i] = clause;
				}
			} else
				info.clauses = new ExceptionClauseInfo [0];

			return info;
		}

		internal ResolvedToken Method_ResolveToken (long id, int token) {
			var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.RESOLVE_TOKEN, new PacketWriter ().WriteId (id).WriteInt (token));

			TokenType type = (TokenType)res.ReadByte ();
			switch (type) {
			case TokenType.STRING:
				return new ResolvedToken () { Type = type, Str = res.ReadString () };
			case TokenType.TYPE:
			case TokenType.METHOD:
			case TokenType.FIELD:
				return new ResolvedToken () { Type = type, Id = res.ReadId () };
			case TokenType.UNKNOWN:
				return new ResolvedToken () { Type = type };
			default:
				throw new NotImplementedException ();
			}
		}

		internal CattrInfo[] Method_GetCustomAttributes (long id, long attr_type_id, bool inherit) {
			PacketReader r = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_CATTRS, new PacketWriter ().WriteId (id).WriteId (attr_type_id));
			return ReadCattrs (r);
		}

		/*
		 * THREAD
		 */

		internal string Thread_GetName (long id) {
			return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_NAME, new PacketWriter ().WriteId (id)).ReadString ();
		}

		internal FrameInfo[] Thread_GetFrameInfo (long id, int start_frame, int length) {
			var res = SendReceive (CommandSet.THREAD, (int)CmdThread.GET_FRAME_INFO, new PacketWriter ().WriteId (id).WriteInt (start_frame).WriteInt (length));
			int count = res.ReadInt ();

			var frames = new FrameInfo [count];
			for (int i = 0; i < count; ++i) {
				var f = new FrameInfo ();
				f.id = res.ReadInt ();
				f.method = res.ReadId ();
				f.il_offset = res.ReadInt ();
				f.flags = (StackFrameFlags)res.ReadByte ();
				frames [i] = f;
			}

			return frames;
		}

		internal int Thread_GetState (long id) {
			return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_STATE, new PacketWriter ().WriteId (id)).ReadInt ();
		}

		internal ThreadInfo Thread_GetInfo (long id) {
			PacketReader r = SendReceive (CommandSet.THREAD, (int)CmdThread.GET_INFO, new PacketWriter ().WriteId (id));

			ThreadInfo res = new ThreadInfo () { is_thread_pool = r.ReadByte () > 0 ? true : false };

			return res;
		}

		internal long Thread_GetId (long id) {
			return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_ID, new PacketWriter ().WriteId (id)).ReadLong ();
		}

		internal long Thread_GetTID (long id) {
			return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_TID, new PacketWriter ().WriteId (id)).ReadLong ();
		}

		/*
		 * MODULE
		 */

		internal ModuleInfo Module_GetInfo (long id) {
			PacketReader r = SendReceive (CommandSet.MODULE, (int)CmdModule.GET_INFO, new PacketWriter ().WriteId (id));
			ModuleInfo info = new ModuleInfo { Name = r.ReadString (), ScopeName = r.ReadString (), FQName = r.ReadString (), Guid = r.ReadString (), Assembly = r.ReadId () };
			return info;
		}

		/*
		 * ASSEMBLY
		 */

		internal string Assembly_GetLocation (long id) {
			return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_LOCATION, new PacketWriter ().WriteId (id)).ReadString ();
		}

		internal long Assembly_GetEntryPoint (long id) {
			return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_ENTRY_POINT, new PacketWriter ().WriteId (id)).ReadId ();
		}

		internal long Assembly_GetManifestModule (long id) {
			return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_MANIFEST_MODULE, new PacketWriter ().WriteId (id)).ReadId ();
		}

		internal long Assembly_GetObject (long id) {
			return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_OBJECT, new PacketWriter ().WriteId (id)).ReadId ();
		}

		internal long Assembly_GetType (long id, string name, bool ignoreCase) {
			return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_TYPE, new PacketWriter ().WriteId (id).WriteString (name).WriteBool (ignoreCase)).ReadId ();
		}

		internal string Assembly_GetName (long id) {
			return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_NAME, new PacketWriter ().WriteId (id)).ReadString ();
		}

		/*
		 * TYPE
		 */

		internal TypeInfo Type_GetInfo (long id) {
			PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_INFO, new PacketWriter ().WriteId (id));
			TypeInfo res = new TypeInfo ();

			res.ns = r.ReadString ();
			res.name = r.ReadString ();
			res.full_name = r.ReadString ();
			res.assembly = r.ReadId ();
			res.module = r.ReadId ();
			res.base_type = r.ReadId ();
			res.element_type = r.ReadId ();
			res.token = r.ReadInt ();
			res.rank = r.ReadByte ();
			res.attributes = r.ReadInt ();
			int b = r.ReadByte ();
			res.is_byref = (b & 1) != 0;
			res.is_pointer = (b & 2) != 0;
			res.is_primitive = (b & 4) != 0;
			res.is_valuetype = (b & 8) != 0;
			res.is_enum = (b & 16) != 0;
			res.is_gtd = (b & 32) != 0;
			res.is_generic_type = (b & 64) != 0;

			int nested_len = r.ReadInt ();
			res.nested = new long [nested_len];
			for (int i = 0; i < nested_len; ++i)
				res.nested [i] = r.ReadId ();

			if (Version.AtLeast (2, 12))
				res.gtd = r.ReadId ();
			if (Version.AtLeast (2, 15) && res.is_generic_type) {
				int n = r.ReadInt ();
				res.type_args = r.ReadIds (n);
			}

			return res;
		}

		internal long[] Type_GetMethods (long id) {
			PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_METHODS, new PacketWriter ().WriteId (id));

			int n = r.ReadInt ();
			long[] res = new long [n];
			for (int i = 0; i < n; ++i)
				res [i] = r.ReadId ();
			return res;
		}

		internal long[] Type_GetFields (long id, out string[] names, out long[] types, out int[] attrs) {
			PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_FIELDS, new PacketWriter ().WriteId (id));

			int n = r.ReadInt ();
			long[] res = new long [n];
			names = new string [n];
			types = new long [n];
			attrs = new int [n];
			for (int i = 0; i < n; ++i) {
				res [i] = r.ReadId ();
				names [i] = r.ReadString ();
				types [i] = r.ReadId ();
				attrs [i] = r.ReadInt ();
			}
			return res;
		}

		internal PropInfo[] Type_GetProperties (long id) {
			PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_PROPERTIES, new PacketWriter ().WriteId (id));

			int n = r.ReadInt ();
			PropInfo[] res = new PropInfo [n];
			for (int i = 0; i < n; ++i) {
				res [i] = new PropInfo ();
				res [i].id = r.ReadId ();
				res [i].name = r.ReadString ();
				res [i].get_method = r.ReadId ();
				res [i].set_method = r.ReadId ();
				res [i].attrs = r.ReadInt ();
			}

			return res;
		}

		internal long Type_GetObject (long id) {
			return SendReceive (CommandSet.TYPE, (int)CmdType.GET_OBJECT, new PacketWriter ().WriteId (id)).ReadId ();
		}

		internal ValueImpl[] Type_GetValues (long id, long[] fields, long thread_id) {
			int len = fields.Length;
			PacketReader r;
			if (thread_id != 0)
				r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_VALUES_2, new PacketWriter ().WriteId (id).WriteId (thread_id).WriteInt (len).WriteIds (fields));
			else
				r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_VALUES, new PacketWriter ().WriteId (id).WriteInt (len).WriteIds (fields));

			ValueImpl[] res = new ValueImpl [len];
			for (int i = 0; i < len; ++i)
				res [i] = r.ReadValue ();
			return res;
		}			

		internal void Type_SetValues (long id, long[] fields, ValueImpl[] values) {
			SendReceive (CommandSet.TYPE, (int)CmdType.SET_VALUES, new PacketWriter ().WriteId (id).WriteInt (fields.Length).WriteIds (fields).WriteValues (values));
		}

		internal string[] Type_GetSourceFiles (long id, bool return_full_paths) {
			var r = SendReceive (CommandSet.TYPE, return_full_paths ? (int)CmdType.GET_SOURCE_FILES_2 : (int)CmdType.GET_SOURCE_FILES, new PacketWriter ().WriteId (id));
			int len = r.ReadInt ();
			string[] res = new string [len];
			for (int i = 0; i < len; ++i)
				res [i] = r.ReadString ();
			return res;
		}

		internal bool Type_IsAssignableFrom (long id, long c_id) {
			return SendReceive (CommandSet.TYPE, (int)CmdType.IS_ASSIGNABLE_FROM, new PacketWriter ().WriteId (id).WriteId (c_id)).ReadByte () > 0;
		}

		internal CattrInfo[] Type_GetCustomAttributes (long id, long attr_type_id, bool inherit) {
			PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_CATTRS, new PacketWriter ().WriteId (id).WriteId (attr_type_id));
			return ReadCattrs (r);
		}

		internal CattrInfo[] Type_GetFieldCustomAttributes (long id, long field_id, long attr_type_id, bool inherit) {
			PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_FIELD_CATTRS, new PacketWriter ().WriteId (id).WriteId (field_id).WriteId (attr_type_id));
			return ReadCattrs (r);
		}

		internal CattrInfo[] Type_GetPropertyCustomAttributes (long id, long field_id, long attr_type_id, bool inherit) {
			PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_PROPERTY_CATTRS, new PacketWriter ().WriteId (id).WriteId (field_id).WriteId (attr_type_id));
			return ReadCattrs (r);
		}

		public long[] Type_GetMethodsByNameFlags (long id, string name, int flags, bool ignoreCase) {
			flags |= ignoreCase ? (int)BindingFlagsExtensions.BINDING_FLAGS_IGNORE_CASE : 0;
			PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.CMD_TYPE_GET_METHODS_BY_NAME_FLAGS, new PacketWriter ().WriteId (id).WriteString (name).WriteInt (flags));
			int len = r.ReadInt ();
			long[] res = new long [len];
			for (int i = 0; i < len; ++i)
				res [i] = r.ReadId ();
			return res;
		}

		internal long[] Type_GetInterfaces (long id) {
			PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_INTERFACES, new PacketWriter ().WriteId (id));
			int len = r.ReadInt ();
			return r.ReadIds (len);
		}

		internal IfaceMapInfo[] Type_GetInterfaceMap (long id, long[] ids) {
			PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_INTERFACE_MAP, new PacketWriter ().WriteId (id).WriteInt (ids.Length).WriteIds (ids));
			var res = new IfaceMapInfo [ids.Length];
			for (int i = 0; i < ids.Length; ++i) {
				int n = r.ReadInt ();

				res [i].iface_id = ids [i];
				res [i].iface_methods = r.ReadIds (n);
				res [i].target_methods = r.ReadIds (n);
			}

			return res;
		}

		internal bool Type_IsInitialized (long id) {
			PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.IS_INITIALIZED, new PacketWriter ().WriteId (id));
			return r.ReadInt () == 1;
		}

		/*
		 * EVENTS
		 */

		internal int EnableEvent (EventType etype, SuspendPolicy suspend_policy, List<Modifier> mods) {
			var w = new PacketWriter ().WriteByte ((byte)etype).WriteByte ((byte)suspend_policy);
			if (mods != null) {
				if (mods.Count > 255)
					throw new NotImplementedException ();
				w.WriteByte ((byte)mods.Count);
				foreach (Modifier mod in mods) {
					if (mod is CountModifier) {
						w.WriteByte ((byte)ModifierKind.COUNT);
						w.WriteInt ((mod as CountModifier).Count);
					} else if (mod is LocationModifier) {
						w.WriteByte ((byte)ModifierKind.LOCATION_ONLY);
						w.WriteId ((mod as LocationModifier).Method);
						w.WriteLong ((mod as LocationModifier).Location);
					} else if (mod is StepModifier) {
						w.WriteByte ((byte)ModifierKind.STEP);
						w.WriteId ((mod as StepModifier).Thread);
						w.WriteInt ((mod as StepModifier).Size);
						w.WriteInt ((mod as StepModifier).Depth);
						if (Version.AtLeast (2, 16))
							w.WriteInt ((mod as StepModifier).Filter);
					} else if (mod is ThreadModifier) {
						w.WriteByte ((byte)ModifierKind.THREAD_ONLY);
						w.WriteId ((mod as ThreadModifier).Thread);
					} else if (mod is ExceptionModifier) {
						var em = mod as ExceptionModifier;
						w.WriteByte ((byte)ModifierKind.EXCEPTION_ONLY);
						w.WriteId (em.Type);
						if (Version.MajorVersion > 2 || Version.MinorVersion > 0) {
							/* This is only supported in protocol version 2.1 */
							w.WriteBool (em.Caught);
							w.WriteBool (em.Uncaught);
						} else if (!em.Caught || !em.Uncaught) {
							throw new NotSupportedException ("This request is not supported by the protocol version implemented by the debuggee.");
						}
					} else if (mod is AssemblyModifier) {
						w.WriteByte ((byte)ModifierKind.ASSEMBLY_ONLY);
						var amod = (mod as AssemblyModifier);
						w.WriteInt (amod.Assemblies.Length);
						foreach (var id in amod.Assemblies)
							w.WriteId (id);
					} else if (mod is SourceFileModifier) {
						w.WriteByte ((byte)ModifierKind.SOURCE_FILE_ONLY);
						var smod = (mod as SourceFileModifier);
						w.WriteInt (smod.SourceFiles.Length);
						foreach (var s in smod.SourceFiles)
							w.WriteString (s);
					} else if (mod is TypeNameModifier) {
						w.WriteByte ((byte)ModifierKind.TYPE_NAME_ONLY);
						var tmod = (mod as TypeNameModifier);
						w.WriteInt (tmod.TypeNames.Length);
						foreach (var s in tmod.TypeNames)
							w.WriteString (s);
					} else {
						throw new NotImplementedException ();
					}
				}
			} else {
				w.WriteByte (0);
			}
			return SendReceive (CommandSet.EVENT_REQUEST, (int)CmdEventRequest.SET, w).ReadInt ();
		}

		internal void ClearEventRequest (EventType etype, int req_id) {
			SendReceive (CommandSet.EVENT_REQUEST, (int)CmdEventRequest.CLEAR, new PacketWriter ().WriteByte ((byte)etype).WriteInt (req_id));
		}			

		internal void ClearAllBreakpoints () {
			SendReceive (CommandSet.EVENT_REQUEST, (int)CmdEventRequest.CLEAR_ALL_BREAKPOINTS, new PacketWriter ());
		}
			
		/*
		 * STACK FRAME
		 */
		internal ValueImpl StackFrame_GetThis (long thread_id, long id) {
			PacketReader r = SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.GET_THIS, new PacketWriter ().WriteId (thread_id).WriteId (id));
			return r.ReadValue ();
		}

		internal ValueImpl[] StackFrame_GetValues (long thread_id, long id, int[] pos) {
			/* pos < 0 -> argument at pos (-pos) - 1 */
			/* pos >= 0 -> local at pos */
			int len = pos.Length;
			PacketReader r = SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.GET_VALUES, new PacketWriter ().WriteId (thread_id).WriteId (id).WriteInt (len).WriteInts (pos));

			ValueImpl[] res = new ValueImpl [len];
			for (int i = 0; i < len; ++i)
				res [i] = r.ReadValue ();
			return res;
		}

		internal void StackFrame_SetValues (long thread_id, long id, int[] pos, ValueImpl[] values) {
			/* pos < 0 -> argument at pos (-pos) - 1 */
			/* pos >= 0 -> local at pos */
			int len = pos.Length;
			SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.SET_VALUES, new PacketWriter ().WriteId (thread_id).WriteId (id).WriteInt (len).WriteInts (pos).WriteValues (values));
		}

		/*
		 * ARRAYS
		 */
		internal int[] Array_GetLength (long id, out int rank, out int[] lower_bounds) {
			var r = SendReceive (CommandSet.ARRAY_REF, (int)CmdArrayRef.GET_LENGTH, new PacketWriter ().WriteId (id));
			rank = r.ReadInt ();
			int[] res = new int [rank];
			lower_bounds = new int [rank];
			for (int i = 0; i < rank; ++i) {
				res [i] = r.ReadInt ();
				lower_bounds [i] = r.ReadInt ();
			}
			return res;
		}

		internal ValueImpl[] Array_GetValues (long id, int index, int len) {
			var r = SendReceive (CommandSet.ARRAY_REF, (int)CmdArrayRef.GET_VALUES, new PacketWriter ().WriteId (id).WriteInt (index).WriteInt (len));
			ValueImpl[] res = new ValueImpl [len];
			for (int i = 0; i < len; ++i)
				res [i] = r.ReadValue ();
			return res;
		}

		internal void Array_SetValues (long id, int index, ValueImpl[] values) {
			SendReceive (CommandSet.ARRAY_REF, (int)CmdArrayRef.SET_VALUES, new PacketWriter ().WriteId (id).WriteInt (index).WriteInt (values.Length).WriteValues (values));
		}

		/*
		 * STRINGS
		 */
		internal string String_GetValue (long id) {
			return SendReceive (CommandSet.STRING_REF, (int)CmdStringRef.GET_VALUE, new PacketWriter ().WriteId (id)).ReadString ();
		}			

		internal int String_GetLength (long id) {
			return (int)SendReceive (CommandSet.STRING_REF, (int)CmdStringRef.GET_LENGTH, new PacketWriter ().WriteId (id)).ReadLong ();
		}			

		internal char[] String_GetChars (long id, int index, int length) {
			var r = SendReceive (CommandSet.STRING_REF, (int)CmdStringRef.GET_CHARS, new PacketWriter ().WriteId (id).WriteLong (index).WriteLong (length));
			var res = new char [length];
			for (int i = 0; i < length; ++i)
				res [i] = (char)r.ReadShort ();
			return res;
		}			

		/*
		 * OBJECTS
		 */
		internal long Object_GetType (long id) {
			return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_TYPE, new PacketWriter ().WriteId (id)).ReadId ();
		}			

		internal long Object_GetDomain (long id) {
			return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_DOMAIN, new PacketWriter ().WriteId (id)).ReadId ();
		}			

		internal ValueImpl[] Object_GetValues (long id, long[] fields) {
			int len = fields.Length;
			PacketReader r = SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_VALUES, new PacketWriter ().WriteId (id).WriteInt (len).WriteIds (fields));

			ValueImpl[] res = new ValueImpl [len];
			for (int i = 0; i < len; ++i)
				res [i] = r.ReadValue ();
			return res;
		}

		internal void Object_SetValues (long id, long[] fields, ValueImpl[] values) {
			SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.SET_VALUES, new PacketWriter ().WriteId (id).WriteInt (fields.Length).WriteIds (fields).WriteValues (values));
		}

		internal bool Object_IsCollected (long id) {
			return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.IS_COLLECTED, new PacketWriter ().WriteId (id)).ReadInt () == 1;
		}			

		internal long Object_GetAddress (long id) {
			return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_ADDRESS, new PacketWriter ().WriteId (id)).ReadLong ();
		}			

		internal ObjectRefInfo Object_GetInfo (long id) {
			ObjectRefInfo res = new ObjectRefInfo ();
			PacketReader r = SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_INFO, new PacketWriter ().WriteId (id));

			res.type_id = r.ReadId ();
			res.domain_id = r.ReadId ();
			return res;
		}

		public void ForceDisconnect ()
		{
			TransportClose ();
		}
	}
	
	class TcpConnection : Connection
	{
		Socket socket;
		
		internal TcpConnection (Socket socket)
		{
			this.socket = socket;
			//socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.NoDelay, 1);
		}
		
		internal EndPoint EndPoint {
			get {
				return socket.RemoteEndPoint;
			}
		}
		
		protected override int TransportSend (byte[] buf, int buf_offset, int len)
		{
			return socket.Send (buf, buf_offset, len, SocketFlags.None);
		}
		
		protected override int TransportReceive (byte[] buf, int buf_offset, int len)
		{
			return socket.Receive (buf, buf_offset, len, SocketFlags.None);
		}
		
		protected override void TransportSetTimeouts (int send_timeout, int receive_timeout)
		{
			socket.SendTimeout = send_timeout;
			socket.ReceiveTimeout = receive_timeout;
		}
		
		protected override void TransportClose ()
		{
			socket.Close ();
		}
	}

	/* This is the interface exposed by the debugger towards the debugger agent */
	interface IEventHandler
	{
		void Events (SuspendPolicy suspend_policy, EventInfo[] events);

		void VMDisconnect (int req_id, long thread_id, string vm_uri);
	}
}