Added tests for Task.WhenAll w/ empty list
[mono.git] / mcs / class / Mono.Debugger.Soft / Mono.Debugger.Soft / Connection.cs
1 using System;
2 using System.IO;
3 using System.Net;
4 using System.Net.Sockets;
5 using System.Threading;
6 using System.Collections.Generic;
7 using System.Text;
8 using System.Diagnostics;
9 using Mono.Cecil.Metadata;
10
11 namespace Mono.Debugger.Soft
12 {
13         public class VersionInfo {
14                 public string VMVersion {
15                         get; set;
16                 }
17
18                 public int MajorVersion {
19                         get; set;
20                 }
21
22                 public int MinorVersion {
23                         get; set;
24                 }
25
26                 /*
27                  * Check that this version is at least major:minor
28                  */
29                 public bool AtLeast (int major, int minor) {
30                         if ((MajorVersion > major) || ((MajorVersion == major && MinorVersion >= minor)))
31                                 return true;
32                         else
33                                 return false;
34                 }
35         }
36
37         struct SourceInfo {
38                 public string source_file;
39                 public byte[] guid, hash;
40         }
41
42         class DebugInfo {
43                 public int max_il_offset;
44                 public int[] il_offsets;
45                 public int[] line_numbers;
46                 public int[] column_numbers;
47                 public SourceInfo[] source_files;
48         }
49
50         struct FrameInfo {
51                 public long id;
52                 public long method;
53                 public int il_offset;
54                 public StackFrameFlags flags;
55         }
56
57         class TypeInfo {
58                 public string ns, name, full_name;
59                 public long assembly, module, base_type, element_type;
60                 public int token, rank, attributes;
61                 public bool is_byref, is_pointer, is_primitive, is_valuetype, is_enum;
62                 public bool is_gtd, is_generic_type;
63                 public long[] nested;
64                 public long gtd;
65                 public long[] type_args;
66         }
67
68         struct IfaceMapInfo {
69                 public long iface_id;
70                 public long[] iface_methods;
71                 public long[] target_methods;
72         }
73
74         class MethodInfo {
75                 public int attributes, iattributes, token;
76                 public bool is_gmd, is_generic_method;
77                 public long gmd;
78                 public long[] type_args;
79         }
80
81         class MethodBodyInfo {
82                 public byte[] il;
83                 public ExceptionClauseInfo[] clauses;
84         }
85
86         struct ExceptionClauseInfo {
87                 public ExceptionClauseFlags flags;
88                 public int try_offset;
89                 public int try_length;
90                 public int handler_offset;
91                 public int handler_length;
92                 public int filter_offset;
93                 public long catch_type_id;
94         }
95
96         enum ExceptionClauseFlags {
97                 None = 0x0,
98                 Filter = 0x1,
99                 Finally = 0x2,
100                 Fault = 0x4,
101         }
102
103         struct ParamInfo {
104                 public int call_conv;
105                 public int param_count;
106                 public int generic_param_count;
107                 public long ret_type;
108                 public long[] param_types;
109                 public string[] param_names;
110         }
111
112         struct LocalsInfo {
113                 public long[] types;
114                 public string[] names;
115                 public int[] live_range_start;
116                 public int[] live_range_end;
117         }
118
119         struct PropInfo {
120                 public long id;
121                 public string name;
122                 public long get_method, set_method;
123                 public int attrs;
124         }
125
126         class CattrNamedArgInfo {
127                 public bool is_property;
128                 public long id;
129                 public ValueImpl value;
130         }
131
132         class CattrInfo {
133                 public long ctor_id;
134                 public ValueImpl[] ctor_args;
135                 public CattrNamedArgInfo[] named_args;
136         }
137
138         class ThreadInfo {
139                 public bool is_thread_pool;
140         }
141
142         struct ObjectRefInfo {
143                 public long type_id;
144                 public long domain_id;
145         }
146
147         enum ValueTypeId {
148                 VALUE_TYPE_ID_NULL = 0xf0,
149                 VALUE_TYPE_ID_TYPE = 0xf1
150         }
151
152         enum InvokeFlags {
153                 NONE = 0x0,
154                 DISABLE_BREAKPOINTS = 0x1,
155                 SINGLE_THREADED = 0x2
156         }
157
158         enum ElementType {
159                 End              = 0x00,
160                 Void            = 0x01,
161                 Boolean  = 0x02,
162                 Char            = 0x03,
163                 I1                = 0x04,
164                 U1                = 0x05,
165                 I2                = 0x06,
166                 U2                = 0x07,
167                 I4                = 0x08,
168                 U4                = 0x09,
169                 I8                = 0x0a,
170                 U8                = 0x0b,
171                 R4                = 0x0c,
172                 R8                = 0x0d,
173                 String    = 0x0e,
174                 Ptr              = 0x0f,
175                 ByRef      = 0x10,
176                 ValueType   = 0x11,
177                 Class      = 0x12,
178                 Var        = 0x13,
179                 Array      = 0x14,
180                 GenericInst = 0x15,
181                 TypedByRef  = 0x16,
182                 I                  = 0x18,
183                 U                  = 0x19,
184                 FnPtr      = 0x1b,
185                 Object    = 0x1c,
186                 SzArray  = 0x1d,
187                 MVar       = 0x1e,
188                 CModReqD        = 0x1f,
189                 CModOpt  = 0x20,
190                 Internal        = 0x21,
191                 Modifier        = 0x40,
192                 Sentinel        = 0x41,
193                 Pinned    = 0x45,
194
195                 Type            = 0x50,
196                 Boxed      = 0x51,
197                 Enum            = 0x55
198         }
199
200         class ValueImpl {
201                 public ElementType Type; /* or one of the VALUE_TYPE_ID constants */
202                 public long Objid;
203                 public object Value;
204                 public long Klass; // For ElementType.ValueType
205                 public ValueImpl[] Fields; // for ElementType.ValueType
206                 public bool IsEnum; // For ElementType.ValueType
207                 public long Id; /* For VALUE_TYPE_ID_TYPE */
208         }
209
210         class ModuleInfo {
211                 public string Name, ScopeName, FQName, Guid;
212                 public long Assembly;
213         }               
214
215         enum TokenType {
216                 STRING = 0,
217                 TYPE = 1,
218                 FIELD = 2,
219                 METHOD = 3,
220                 UNKNOWN = 4
221         }
222
223         enum StackFrameFlags {
224                 NONE = 0,
225                 DEBUGGER_INVOKE = 1,
226                 NATIVE_TRANSITION = 2
227         }
228
229         class ResolvedToken {
230                 public TokenType Type;
231                 public string Str;
232                 public long Id;
233         }
234
235         class Modifier {
236         }
237
238         class CountModifier : Modifier {
239                 public int Count {
240                         get; set;
241                 }
242         }
243
244         class LocationModifier : Modifier {
245                 public long Method {
246                         get; set;
247                 }
248
249                 public long Location {
250                         get; set;
251                 }
252         }
253
254         class StepModifier : Modifier {
255                 public long Thread {
256                         get; set;
257                 }
258
259                 public int Depth {
260                         get; set;
261                 }
262
263                 public int Size {
264                         get; set;
265                 }
266
267                 public int Filter {
268                         get; set;
269                 }
270         }
271
272         class ThreadModifier : Modifier {
273                 public long Thread {
274                         get; set;
275                 }
276         }
277
278         class ExceptionModifier : Modifier {
279                 public long Type {
280                         get; set;
281                 }
282                 public bool Caught {
283                         get; set;
284                 }
285                 public bool Uncaught {
286                         get; set;
287                 }
288         }
289
290         class AssemblyModifier : Modifier {
291                 public long[] Assemblies {
292                         get; set;
293                 }
294         }
295
296         class SourceFileModifier : Modifier {
297                 public string[] SourceFiles {
298                         get; set;
299                 }
300         }
301
302         class TypeNameModifier : Modifier {
303                 public string[] TypeNames {
304                         get; set;
305                 }
306         }
307
308         class EventInfo {
309                 public EventType EventType {
310                         get; set;
311                 }
312
313                 public int ReqId {
314                         get; set;
315                 }
316
317                 public SuspendPolicy SuspendPolicy {
318                         get; set;
319                 }
320
321                 public long ThreadId {
322                         get; set;
323                 }
324
325                 public long Id {
326                         get; set;
327                 }
328
329                 public long Location {
330                         get; set;
331                 }
332
333                 public int Level {
334                         get; set;
335                 }
336
337                 public string Category {
338                         get; set;
339                 }
340
341                 public string Message {
342                         get; set;
343                 }
344
345                 public EventInfo (EventType type, int req_id) {
346                         EventType = type;
347                         ReqId = req_id;
348                 }
349         }
350
351         public enum ErrorCode {
352                 NONE = 0,
353                 INVALID_OBJECT = 20,
354                 INVALID_FIELDID = 25,
355                 INVALID_FRAMEID = 30,
356                 NOT_IMPLEMENTED = 100,
357                 NOT_SUSPENDED = 101,
358                 INVALID_ARGUMENT = 102,
359                 ERR_UNLOADED = 103,
360                 ERR_NO_INVOCATION = 104,
361                 ABSENT_INFORMATION = 105,
362                 NO_SEQ_POINT_AT_IL_OFFSET = 106
363         }
364
365         public class ErrorHandlerEventArgs : EventArgs {
366
367                 public ErrorCode ErrorCode {
368                         get; set;
369                 }
370         }
371
372         /*
373          * Represents the connection to the debuggee
374          */
375         public abstract class Connection
376         {
377                 /*
378                  * The protocol and the packet format is based on JDWP, the differences 
379                  * are in the set of supported events, and the commands.
380                  */
381                 internal const string HANDSHAKE_STRING = "DWP-Handshake";
382
383                 internal const int HEADER_LENGTH = 11;
384
385                 static readonly bool EnableConnectionLogging = !String.IsNullOrEmpty (Environment.GetEnvironmentVariable ("MONO_SDB_LOG"));
386                 static int ConnectionId;
387                 readonly StreamWriter LoggingStream = EnableConnectionLogging ? 
388                         new StreamWriter (string.Format ("/tmp/sdb_conn_log_{0}", ConnectionId++), false) : null;
389
390                 /*
391                  * Th version of the wire-protocol implemented by the library. The library
392                  * and the debuggee can communicate if they implement the same major version.
393                  * If they implement a different minor version, they can communicate, but some
394                  * features might not be available. This allows older clients to communicate
395                  * with newer runtimes, and vice versa.
396                  */
397                 internal const int MAJOR_VERSION = 2;
398                 internal const int MINOR_VERSION = 23;
399
400                 enum WPSuspendPolicy {
401                         NONE = 0,
402                         EVENT_THREAD = 1,
403                         ALL = 2
404                 }
405
406                 enum CommandSet {
407                         VM = 1,
408                         OBJECT_REF = 9,
409                         STRING_REF = 10,
410                         THREAD = 11,
411                         ARRAY_REF = 13,
412                         EVENT_REQUEST = 15,
413                         STACK_FRAME = 16,
414                         APPDOMAIN = 20,
415                         ASSEMBLY = 21,
416                         METHOD = 22,
417                         TYPE = 23,
418                         MODULE = 24,
419                         EVENT = 64
420                 }
421
422                 enum EventKind {
423                         VM_START = 0,
424                         VM_DEATH = 1,
425                         THREAD_START = 2,
426                         THREAD_DEATH = 3,
427                         APPDOMAIN_CREATE = 4, // Not in JDI
428                         APPDOMAIN_UNLOAD = 5, // Not in JDI
429                         METHOD_ENTRY = 6,
430                         METHOD_EXIT = 7,
431                         ASSEMBLY_LOAD = 8,
432                         ASSEMBLY_UNLOAD = 9,
433                         BREAKPOINT = 10,
434                         STEP = 11,
435                         TYPE_LOAD = 12,
436                         EXCEPTION = 13,
437                         KEEPALIVE = 14,
438                         USER_BREAK = 15,
439                         USER_LOG = 16
440                 }
441
442                 enum ModifierKind {
443                         COUNT = 1,
444                         THREAD_ONLY = 3,
445                         LOCATION_ONLY = 7,
446                         EXCEPTION_ONLY = 8,
447                         STEP = 10,
448                         ASSEMBLY_ONLY = 11,
449                         SOURCE_FILE_ONLY = 12,
450                         TYPE_NAME_ONLY = 13
451                 }
452
453                 enum CmdVM {
454                         VERSION = 1,
455                         ALL_THREADS = 2,
456                         SUSPEND = 3,
457                         RESUME = 4,
458                         EXIT = 5,
459                         DISPOSE = 6,
460                         INVOKE_METHOD = 7,
461                         SET_PROTOCOL_VERSION = 8,
462                         ABORT_INVOKE = 9,
463                         SET_KEEPALIVE = 10,
464                         GET_TYPES_FOR_SOURCE_FILE = 11,
465                         GET_TYPES = 12,
466                         INVOKE_METHODS = 13
467                 }
468
469                 enum CmdEvent {
470                         COMPOSITE = 100
471                 }
472
473                 enum CmdThread {
474                         GET_FRAME_INFO = 1,
475                         GET_NAME = 2,
476                         GET_STATE = 3,
477                         GET_INFO = 4,
478                         /* FIXME: Merge into GET_INFO when the major protocol version is increased */
479                         GET_ID = 5,
480                         /* Ditto */
481                         GET_TID = 6
482                 }
483
484                 enum CmdEventRequest {
485                         SET = 1,
486                         CLEAR = 2,
487                         CLEAR_ALL_BREAKPOINTS = 3
488                 }
489
490                 enum CmdAppDomain {
491                         GET_ROOT_DOMAIN = 1,
492                         GET_FRIENDLY_NAME = 2,
493                         GET_ASSEMBLIES = 3,
494                         GET_ENTRY_ASSEMBLY = 4,
495                         CREATE_STRING = 5,
496                         GET_CORLIB = 6,
497                         CREATE_BOXED_VALUE = 7
498                 }
499
500                 enum CmdAssembly {
501                         GET_LOCATION = 1,
502                         GET_ENTRY_POINT = 2,
503                         GET_MANIFEST_MODULE = 3,
504                         GET_OBJECT = 4,
505                         GET_TYPE = 5,
506                         GET_NAME = 6
507                 }
508
509                 enum CmdModule {
510                         GET_INFO = 1,
511                 }
512
513                 enum CmdMethod {
514                         GET_NAME = 1,
515                         GET_DECLARING_TYPE = 2,
516                         GET_DEBUG_INFO = 3,
517                         GET_PARAM_INFO = 4,
518                         GET_LOCALS_INFO = 5,
519                         GET_INFO = 6,
520                         GET_BODY = 7,
521                         RESOLVE_TOKEN = 8,
522                         GET_CATTRS = 9
523                 }
524
525                 enum CmdType {
526                         GET_INFO = 1,
527                         GET_METHODS = 2,
528                         GET_FIELDS = 3,
529                         GET_VALUES = 4,
530                         GET_OBJECT = 5,
531                         GET_SOURCE_FILES = 6,
532                         SET_VALUES = 7,
533                         IS_ASSIGNABLE_FROM = 8,
534                         GET_PROPERTIES = 9,
535                         GET_CATTRS = 10,
536                         GET_FIELD_CATTRS = 11,
537                         GET_PROPERTY_CATTRS = 12,
538                         /* FIXME: Merge into GET_SOURCE_FILES when the major protocol version is increased */
539                         GET_SOURCE_FILES_2 = 13,
540                         /* FIXME: Merge into GET_VALUES when the major protocol version is increased */
541                         GET_VALUES_2 = 14,
542                         CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
543                         GET_INTERFACES = 16,
544                         GET_INTERFACE_MAP = 17,
545                         IS_INITIALIZED = 18
546                 }
547
548                 enum BindingFlagsExtensions {
549                         BINDING_FLAGS_IGNORE_CASE = 0x70000000,
550                 }
551
552                 enum CmdStackFrame {
553                         GET_VALUES = 1,
554                         GET_THIS = 2,
555                         SET_VALUES = 3
556                 }
557
558                 enum CmdArrayRef {
559                         GET_LENGTH = 1,
560                         GET_VALUES = 2,
561                         SET_VALUES = 3
562                 }
563
564                 enum CmdStringRef {
565                         GET_VALUE = 1,
566                         GET_LENGTH = 2,
567                         GET_CHARS = 3
568                 }
569
570                 enum CmdObjectRef {
571                         GET_TYPE = 1,
572                         GET_VALUES = 2,
573                         IS_COLLECTED = 3,
574                         GET_ADDRESS = 4,
575                         GET_DOMAIN = 5,
576                         SET_VALUES = 6,
577                         GET_INFO = 7,
578                 }
579
580                 class Header {
581                         public int id;
582                         public int command_set;
583                         public int command;
584                         public int flags;
585                 }                       
586
587                 internal static int GetPacketLength (byte[] header) {
588                         int offset = 0;
589                         return decode_int (header, ref offset);
590                 }
591
592                 internal static bool IsReplyPacket (byte[] packet) {
593                         int offset = 8;
594                         return decode_byte (packet, ref offset) == 0x80;
595                 }
596
597                 internal static int GetPacketId (byte[] packet) {
598                         int offset = 4;
599                         return decode_int (packet, ref offset);
600                 }
601
602                 static int decode_byte (byte[] packet, ref int offset) {
603                         return packet [offset++];
604                 }
605
606                 static int decode_short (byte[] packet, ref int offset) {
607                         int res = ((int)packet [offset] << 8) | (int)packet [offset + 1];
608                         offset += 2;
609                         return res;
610                 }
611
612                 static int decode_int (byte[] packet, ref int offset) {
613                         int res = ((int)packet [offset] << 24) | ((int)packet [offset + 1] << 16) | ((int)packet [offset + 2] << 8) | (int)packet [offset + 3];
614                         offset += 4;
615                         return res;
616                 }
617
618                 static long decode_id (byte[] packet, ref int offset) {
619                         return decode_int (packet, ref offset);
620                 }
621
622                 static long decode_long (byte[] packet, ref int offset) {
623                         uint high = (uint)decode_int (packet, ref offset);
624                         uint low = (uint)decode_int (packet, ref offset);
625
626                         return (long)(((ulong)high << 32) | (ulong)low);
627                 }
628
629                 internal static SuspendPolicy decode_suspend_policy (int suspend_policy) {
630                         switch ((WPSuspendPolicy)suspend_policy) {
631                         case WPSuspendPolicy.NONE:
632                                 return SuspendPolicy.None;
633                         case WPSuspendPolicy.EVENT_THREAD:
634                                 return SuspendPolicy.EventThread;
635                         case WPSuspendPolicy.ALL:
636                                 return SuspendPolicy.All;
637                         default:
638                                 throw new NotImplementedException ();
639                         }
640                 }
641
642                 static Header decode_command_header (byte[] packet) {
643                         int offset = 0;
644                         Header res = new Header ();
645
646                         decode_int (packet, ref offset);
647                         res.id = decode_int (packet, ref offset);
648                         res.flags = decode_byte (packet, ref offset);
649                         res.command_set = decode_byte (packet, ref offset);
650                         res.command = decode_byte (packet, ref offset);
651
652                         return res;
653                 }
654
655                 static void encode_byte (byte[] buf, int b, ref int offset) {
656                         buf [offset] = (byte)b;
657                         offset ++;
658                 }
659
660                 static void encode_int (byte[] buf, int i, ref int offset) {
661                         buf [offset] = (byte)((i >> 24) & 0xff);
662                         buf [offset + 1] = (byte)((i >> 16) & 0xff);
663                         buf [offset + 2] = (byte)((i >> 8) & 0xff);
664                         buf [offset + 3] = (byte)((i >> 0) & 0xff);
665                         offset += 4;
666                 }
667
668                 static void encode_id (byte[] buf, long id, ref int offset) {
669                         encode_int (buf, (int)id, ref offset);
670                 }
671
672                 static void encode_long (byte[] buf, long l, ref int offset) {
673                         encode_int (buf, (int)((l >> 32) & 0xffffffff), ref offset);
674                         encode_int (buf, (int)(l & 0xffffffff), ref offset);
675                 }
676
677                 internal static byte[] EncodePacket (int id, int commandSet, int command, byte[] data, int dataLen) {
678                         byte[] buf = new byte [dataLen + 11];
679                         int offset = 0;
680                         
681                         encode_int (buf, buf.Length, ref offset);
682                         encode_int (buf, id, ref offset);
683                         encode_byte (buf, 0, ref offset);
684                         encode_byte (buf, commandSet, ref offset);
685                         encode_byte (buf, command, ref offset);
686
687                         for (int i = 0; i < dataLen; ++i)
688                                 buf [offset + i] = data [i];
689
690                         return buf;
691                 }
692
693                 class PacketReader {
694                         byte[] packet;
695                         int offset;
696
697                         public PacketReader (byte[] packet) {
698                                 this.packet = packet;
699
700                                 // For event packets
701                                 Header header = decode_command_header (packet);
702                                 CommandSet = (CommandSet)header.command_set;
703                                 Command = header.command;
704
705                                 // For reply packets
706                                 offset = 0;
707                                 ReadInt (); // length
708                                 ReadInt (); // id
709                                 ReadByte (); // flags
710                                 ErrorCode = ReadShort ();
711                         }
712
713                         public CommandSet CommandSet {
714                                 get; set;
715                         }
716
717                         public int Command {
718                                 get; set;
719                         }
720
721                         public int ErrorCode {
722                                 get; set;
723                         }
724
725                         public int Offset {
726                                 get {
727                                         return offset;
728                                 }
729                         }
730
731                         public int ReadByte () {
732                                 return decode_byte (packet, ref offset);
733                         }
734
735                         public int ReadShort () {
736                                 return decode_short (packet, ref offset);
737                         }
738
739                         public int ReadInt () {
740                                 return decode_int (packet, ref offset);
741                         }
742
743                         public long ReadId () {
744                                 return decode_id (packet, ref offset);
745                         }
746
747                         public long ReadLong () {
748                                 return decode_long (packet, ref offset);
749                         }
750
751                         public float ReadFloat () {
752                                 float f = DataConverter.FloatFromBE (packet, offset);
753                                 offset += 4;
754                                 return f;
755                         }
756
757                         public double ReadDouble () {
758                                 double d = DataConverter.DoubleFromBE (packet, offset);
759                                 offset += 8;
760                                 return d;
761                         }
762
763                         public string ReadString () {
764                                 int len = decode_int (packet, ref offset);
765                                 string res = new String (Encoding.UTF8.GetChars (packet, offset, len));
766                                 offset += len;
767                                 return res;
768                         }
769
770                         public ValueImpl ReadValue () {
771                                 ElementType etype = (ElementType)ReadByte ();
772
773                                 switch (etype) {
774                                 case ElementType.Void:
775                                         return new ValueImpl { Type = etype };
776                                 case ElementType.I1:
777                                         return new ValueImpl { Type = etype, Value = (sbyte)ReadInt () };
778                                 case ElementType.U1:
779                                         return new ValueImpl { Type = etype, Value = (byte)ReadInt () };
780                                 case ElementType.Boolean:
781                                         return new ValueImpl { Type = etype, Value = ReadInt () != 0 };
782                                 case ElementType.I2:
783                                         return new ValueImpl { Type = etype, Value = (short)ReadInt () };
784                                 case ElementType.U2:
785                                         return new ValueImpl { Type = etype, Value = (ushort)ReadInt () };
786                                 case ElementType.Char:
787                                         return new ValueImpl { Type = etype, Value = (char)ReadInt () };
788                                 case ElementType.I4:
789                                         return new ValueImpl { Type = etype, Value = ReadInt () };
790                                 case ElementType.U4:
791                                         return new ValueImpl { Type = etype, Value = (uint)ReadInt () };
792                                 case ElementType.I8:
793                                         return new ValueImpl { Type = etype, Value = ReadLong () };
794                                 case ElementType.U8:
795                                         return new ValueImpl { Type = etype, Value = (ulong)ReadLong () };
796                                 case ElementType.R4:
797                                         return new ValueImpl { Type = etype, Value = ReadFloat () };
798                                 case ElementType.R8:
799                                         return new ValueImpl { Type = etype, Value = ReadDouble () };
800                                 case ElementType.I:
801                                 case ElementType.U:
802                                 case ElementType.Ptr:
803                                         // FIXME: The client and the debuggee might have different word sizes
804                                         return new ValueImpl { Type = etype, Value = ReadLong () };
805                                 case ElementType.String:
806                                 case ElementType.SzArray:
807                                 case ElementType.Class:
808                                 case ElementType.Array:
809                                 case ElementType.Object:
810                                         long objid = ReadId ();
811                                         return new ValueImpl () { Type = etype, Objid = objid };
812                                 case ElementType.ValueType:
813                                         bool is_enum = ReadByte () == 1;
814                                         long klass = ReadId ();
815                                         long nfields = ReadInt ();
816                                         ValueImpl[] fields = new ValueImpl [nfields];
817                                         for (int i = 0; i < nfields; ++i)
818                                                 fields [i] = ReadValue ();
819                                         return new ValueImpl () { Type = etype, Klass = klass, Fields = fields, IsEnum = is_enum };
820                                 case (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL:
821                                         return new ValueImpl { Type = etype };
822                                 case (ElementType)ValueTypeId.VALUE_TYPE_ID_TYPE:
823                                         return new ValueImpl () { Type = etype, Id = ReadId () };
824                                 default:
825                                         throw new NotImplementedException ("Unable to handle type " + etype);
826                                 }
827                         }
828
829                         public long[] ReadIds (int n) {
830                                 long[] res = new long [n];
831                                 for (int i = 0; i < n; ++i)
832                                         res [i] = ReadId ();
833                                 return res;
834                         }
835                 }
836
837                 class PacketWriter {
838
839                         byte[] data;
840                         int offset;
841
842                         public PacketWriter () {
843                                 data = new byte [1024];
844                                 offset = 0;
845                         }
846
847                         void MakeRoom (int size) {
848                                 if (offset + size >= data.Length) {
849                                         int new_len = data.Length * 2;
850                                         while (new_len < offset + size) {
851                                                 new_len *= 2;
852                                         }
853                                         byte[] new_data = new byte [new_len];
854                                         Array.Copy (data, new_data, data.Length);
855                                         data = new_data;
856                                 }
857                         }
858
859                         public PacketWriter WriteByte (byte val) {
860                                 MakeRoom (1);
861                                 encode_byte (data, val, ref offset);
862                                 return this;
863                         }
864
865                         public PacketWriter WriteInt (int val) {
866                                 MakeRoom (4);
867                                 encode_int (data, val, ref offset);
868                                 return this;
869                         }
870
871                         public PacketWriter WriteId (long id) {
872                                 MakeRoom (8);
873                                 encode_id (data, id, ref offset);
874                                 return this;
875                         }
876
877                         public PacketWriter WriteLong (long val) {
878                                 MakeRoom (8);
879                                 encode_long (data, val, ref offset);
880                                 return this;
881                         }
882
883                         public PacketWriter WriteFloat (float f) {
884                                 MakeRoom (8);
885                                 byte[] b = DataConverter.GetBytesBE (f);
886                                 for (int i = 0; i < 4; ++i)
887                                         data [offset + i] = b [i];
888                                 offset += 4;
889                                 return this;
890                         }
891
892                         public PacketWriter WriteDouble (double d) {
893                                 MakeRoom (8);
894                                 byte[] b = DataConverter.GetBytesBE (d);
895                                 for (int i = 0; i < 8; ++i)
896                                         data [offset + i] = b [i];
897                                 offset += 8;
898                                 return this;
899                         }
900
901                         public PacketWriter WriteInts (int[] ids) {
902                                 for (int i = 0; i < ids.Length; ++i)
903                                         WriteInt (ids [i]);
904                                 return this;
905                         }
906
907                         public PacketWriter WriteIds (long[] ids) {
908                                 for (int i = 0; i < ids.Length; ++i)
909                                         WriteId (ids [i]);
910                                 return this;
911                         }
912
913                         public PacketWriter WriteString (string s) {
914                                 if (s == null)
915                                         return WriteInt (-1);
916
917                                 byte[] b = Encoding.UTF8.GetBytes (s);
918                                 MakeRoom (4);
919                                 encode_int (data, b.Length, ref offset);
920                                 MakeRoom (b.Length);
921                                 Buffer.BlockCopy (b, 0, data, offset, b.Length);
922                                 offset += b.Length;
923                                 return this;
924                         }
925
926                         public PacketWriter WriteBool (bool val) {
927                                 WriteByte (val ? (byte)1 : (byte)0);
928                                 return this;
929                         }
930
931                         public PacketWriter WriteValue (ValueImpl v) {
932                                 ElementType t;
933
934                                 if (v.Value != null)
935                                         t = TypeCodeToElementType (Type.GetTypeCode (v.Value.GetType ()));
936                                 else
937                                         t = v.Type;
938                                 WriteByte ((byte)t);
939                                 switch (t) {
940                                 case ElementType.Boolean:
941                                         WriteInt ((bool)v.Value ? 1 : 0);
942                                         break;
943                                 case ElementType.Char:
944                                         WriteInt ((int)(char)v.Value);
945                                         break;
946                                 case ElementType.I1:
947                                         WriteInt ((int)(sbyte)v.Value);
948                                         break;
949                                 case ElementType.U1:
950                                         WriteInt ((int)(byte)v.Value);
951                                         break;
952                                 case ElementType.I2:
953                                         WriteInt ((int)(short)v.Value);
954                                         break;
955                                 case ElementType.U2:
956                                         WriteInt ((int)(ushort)v.Value);
957                                         break;
958                                 case ElementType.I4:
959                                         WriteInt ((int)(int)v.Value);
960                                         break;
961                                 case ElementType.U4:
962                                         WriteInt ((int)(uint)v.Value);
963                                         break;
964                                 case ElementType.I8:
965                                         WriteLong ((long)(long)v.Value);
966                                         break;
967                                 case ElementType.U8:
968                                         WriteLong ((long)(ulong)v.Value);
969                                         break;
970                                 case ElementType.R4:
971                                         WriteFloat ((float)v.Value);
972                                         break;
973                                 case ElementType.R8:
974                                         WriteDouble ((double)v.Value);
975                                         break;
976                                 case ElementType.String:
977                                 case ElementType.SzArray:
978                                 case ElementType.Class:
979                                 case ElementType.Array:
980                                 case ElementType.Object:
981                                         WriteId (v.Objid);
982                                         break;
983                                 case ElementType.ValueType:
984                                         // FIXME: 
985                                         if (v.IsEnum)
986                                                 throw new NotImplementedException ();
987                                         WriteByte (0);
988                                         WriteId (v.Klass);
989                                         WriteInt (v.Fields.Length);
990                                         for (int i = 0; i < v.Fields.Length; ++i)
991                                                 WriteValue (v.Fields [i]);
992                                         break;
993                                 case (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL:
994                                         break;
995                                 default:
996                                         throw new NotImplementedException ();
997                                 }
998
999                                 return this;
1000                         }
1001
1002                         public PacketWriter WriteValues (ValueImpl[] values) {
1003                                 for (int i = 0; i < values.Length; ++i)
1004                                         WriteValue (values [i]);
1005                                 return this;
1006                         }
1007
1008                         public byte[] Data {
1009                                 get {
1010                                         return data;
1011                                 }
1012                         }
1013
1014                         public int Offset {
1015                                 get {
1016                                         return offset;
1017                                 }
1018                         }
1019                 }
1020
1021                 delegate void ReplyCallback (int packet_id, byte[] packet);
1022
1023                 bool closed;
1024                 Thread receiver_thread;
1025                 Dictionary<int, byte[]> reply_packets;
1026                 Dictionary<int, ReplyCallback> reply_cbs;
1027                 Dictionary<int, int> reply_cb_counts;
1028                 object reply_packets_monitor;
1029
1030                 internal event EventHandler<ErrorHandlerEventArgs> ErrorHandler;
1031
1032                 protected Connection () {
1033                         closed = false;
1034                         reply_packets = new Dictionary<int, byte[]> ();
1035                         reply_cbs = new Dictionary<int, ReplyCallback> ();
1036                         reply_cb_counts = new Dictionary<int, int> ();
1037                         reply_packets_monitor = new Object ();
1038                 }
1039                 
1040                 protected abstract int TransportReceive (byte[] buf, int buf_offset, int len);
1041                 protected abstract int TransportSend (byte[] buf, int buf_offset, int len);
1042                 protected abstract void TransportSetTimeouts (int send_timeout, int receive_timeout);
1043                 protected abstract void TransportClose ();
1044
1045                 internal VersionInfo Version;
1046                 
1047                 int Receive (byte[] buf, int buf_offset, int len) {
1048                         int offset = 0;
1049
1050                         while (offset < len) {
1051                                 int n = TransportReceive (buf, buf_offset + offset, len - offset);
1052
1053                                 if (n == 0)
1054                                         return offset;
1055                                 offset += n;
1056                         }
1057
1058                         return offset;
1059                 }
1060                 
1061                 // Do the wire protocol handshake
1062                 internal void Connect () {
1063                         byte[] buf = new byte [HANDSHAKE_STRING.Length];
1064                         char[] cbuf = new char [buf.Length];
1065
1066                         // FIXME: Add a timeout
1067                         int n = Receive (buf, 0, buf.Length);
1068                         if (n == 0)
1069                                 throw new IOException ("DWP Handshake failed.");
1070                         for (int i = 0; i < buf.Length; ++i)
1071                                 cbuf [i] = (char)buf [i];
1072
1073                         if (new String (cbuf) != HANDSHAKE_STRING)
1074                                 throw new IOException ("DWP Handshake failed.");
1075                         
1076                         TransportSend (buf, 0, buf.Length);
1077
1078                         receiver_thread = new Thread (new ThreadStart (receiver_thread_main));
1079                         receiver_thread.Name = "SDB Receiver";
1080                         receiver_thread.IsBackground = true;
1081                         receiver_thread.Start ();
1082
1083                         Version = VM_GetVersion ();
1084
1085                         //
1086                         // Tell the debuggee our protocol version, so newer debuggees can work
1087                         // with older clients
1088                         //
1089
1090                         //
1091                         // Older debuggees might not support this request
1092                         EventHandler<ErrorHandlerEventArgs> OrigErrorHandler = ErrorHandler;
1093                         ErrorHandler = null;
1094                         ErrorHandler += delegate (object sender, ErrorHandlerEventArgs args) {
1095                                 throw new NotSupportedException ();
1096                         };
1097                         try {
1098                                 VM_SetProtocolVersion (MAJOR_VERSION, MINOR_VERSION);
1099                         } catch (NotSupportedException) {
1100                         }
1101                         ErrorHandler = OrigErrorHandler;
1102                 }
1103
1104                 internal byte[] ReadPacket () {
1105                         // FIXME: Throw ClosedConnectionException () if the connection is closed
1106                         // FIXME: Throw ClosedConnectionException () if another thread closes the connection
1107                         // FIXME: Locking
1108                         byte[] header = new byte [HEADER_LENGTH];
1109
1110                         int len = Receive (header, 0, header.Length);
1111                         if (len == 0)
1112                                 return new byte [0];
1113                         if (len != HEADER_LENGTH) {
1114                                 // FIXME:
1115                                 throw new IOException ("Packet of length " + len + " is read.");
1116                         }
1117
1118                         int packetLength = GetPacketLength (header);
1119                         if (packetLength < 11)
1120                                 throw new IOException ("Invalid packet length.");
1121
1122                         if (packetLength == 11) {
1123                                 return header;
1124                         } else {
1125                                 byte[] buf = new byte [packetLength];
1126                                 for (int i = 0; i < header.Length; ++i)
1127                                         buf [i] = header [i];
1128                                 len = Receive (buf, header.Length, packetLength - header.Length);
1129                                 if (len != packetLength - header.Length)
1130                                         throw new IOException ();
1131                                 return buf;
1132                         }
1133                 }
1134
1135                 internal void WritePacket (byte[] packet) {
1136                         // FIXME: Throw ClosedConnectionException () if the connection is closed
1137                         // FIXME: Throw ClosedConnectionException () if another thread closes the connection
1138                         // FIXME: Locking
1139                         TransportSend (packet, 0, packet.Length);
1140                 }
1141
1142                 internal void Close () {
1143                         closed = true;
1144                 }
1145
1146                 internal bool IsClosed {
1147                         get {
1148                                 return closed;
1149                         }
1150                 }
1151
1152                 bool disconnected;
1153
1154                 void receiver_thread_main () {
1155                         while (!closed) {
1156                                 try {
1157                                         bool res = ReceivePacket ();
1158                                         if (!res)
1159                                                 break;
1160                                 } catch (Exception ex) {
1161                                         if (!closed) {
1162                                                 Console.WriteLine (ex);
1163                                         }
1164                                         break;
1165                                 }
1166                         }
1167
1168                         lock (reply_packets_monitor) {
1169                                 disconnected = true;
1170                                 Monitor.PulseAll (reply_packets_monitor);
1171                                 TransportClose ();
1172                         }
1173                         EventHandler.VMDisconnect (0, 0, null);
1174                 }
1175
1176                 bool ReceivePacket () {
1177                                 byte[] packet = ReadPacket ();
1178
1179                                 if (packet.Length == 0) {
1180                                         return false;
1181                                 }
1182
1183                                 if (IsReplyPacket (packet)) {
1184                                         int id = GetPacketId (packet);
1185                                         ReplyCallback cb = null;
1186                                         lock (reply_packets_monitor) {
1187                                                 reply_cbs.TryGetValue (id, out cb);
1188                                                 if (cb == null) {
1189                                                         reply_packets [id] = packet;
1190                                                         Monitor.PulseAll (reply_packets_monitor);
1191                                                 } else {
1192                                                         int c = reply_cb_counts [id];
1193                                                         c --;
1194                                                         if (c == 0) {
1195                                                                 reply_cbs.Remove (id);
1196                                                                 reply_cb_counts.Remove (id);
1197                                                         }
1198                                                 }
1199                                         }
1200
1201                                         if (cb != null)
1202                                                 cb.Invoke (id, packet);
1203                                 } else {
1204                                         PacketReader r = new PacketReader (packet);
1205
1206                                         if (r.CommandSet == CommandSet.EVENT && r.Command == (int)CmdEvent.COMPOSITE) {
1207                                                 int spolicy = r.ReadByte ();
1208                                                 int nevents = r.ReadInt ();
1209
1210                                                 SuspendPolicy suspend_policy = decode_suspend_policy (spolicy);
1211
1212                                                 EventInfo[] events = new EventInfo [nevents];
1213
1214                                                 for (int i = 0; i < nevents; ++i) {
1215                                                         EventKind kind = (EventKind)r.ReadByte ();
1216                                                         int req_id = r.ReadInt ();
1217
1218                                                         EventType etype = (EventType)kind;
1219
1220                                                         if (kind == EventKind.VM_START) {
1221                                                                 long thread_id = r.ReadId ();
1222                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id };
1223                                                                 //EventHandler.VMStart (req_id, thread_id, null);
1224                                                         } else if (kind == EventKind.VM_DEATH) {
1225                                                                 //EventHandler.VMDeath (req_id, 0, null);
1226                                                                 events [i] = new EventInfo (etype, req_id) { };
1227                                                         } else if (kind == EventKind.THREAD_START) {
1228                                                                 long thread_id = r.ReadId ();
1229                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = thread_id };
1230                                                                 //EventHandler.ThreadStart (req_id, thread_id, thread_id);
1231                                                         } else if (kind == EventKind.THREAD_DEATH) {
1232                                                                 long thread_id = r.ReadId ();
1233                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = thread_id };
1234                                                                 //EventHandler.ThreadDeath (req_id, thread_id, thread_id);
1235                                                         } else if (kind == EventKind.ASSEMBLY_LOAD) {
1236                                                                 long thread_id = r.ReadId ();
1237                                                                 long id = r.ReadId ();
1238                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1239                                                                 //EventHandler.AssemblyLoad (req_id, thread_id, id);
1240                                                         } else if (kind == EventKind.ASSEMBLY_UNLOAD) {
1241                                                                 long thread_id = r.ReadId ();
1242                                                                 long id = r.ReadId ();
1243                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1244                                                                 //EventHandler.AssemblyUnload (req_id, thread_id, id);
1245                                                         } else if (kind == EventKind.TYPE_LOAD) {
1246                                                                 long thread_id = r.ReadId ();
1247                                                                 long id = r.ReadId ();
1248                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1249                                                                 //EventHandler.TypeLoad (req_id, thread_id, id);
1250                                                         } else if (kind == EventKind.METHOD_ENTRY) {
1251                                                                 long thread_id = r.ReadId ();
1252                                                                 long id = r.ReadId ();
1253                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1254                                                                 //EventHandler.MethodEntry (req_id, thread_id, id);
1255                                                         } else if (kind == EventKind.METHOD_EXIT) {
1256                                                                 long thread_id = r.ReadId ();
1257                                                                 long id = r.ReadId ();
1258                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1259                                                                 //EventHandler.MethodExit (req_id, thread_id, id);
1260                                                         } else if (kind == EventKind.BREAKPOINT) {
1261                                                                 long thread_id = r.ReadId ();
1262                                                                 long id = r.ReadId ();
1263                                                                 long loc = r.ReadLong ();
1264                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
1265                                                                 //EventHandler.Breakpoint (req_id, thread_id, id, loc);
1266                                                         } else if (kind == EventKind.STEP) {
1267                                                                 long thread_id = r.ReadId ();
1268                                                                 long id = r.ReadId ();
1269                                                                 long loc = r.ReadLong ();
1270                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
1271                                                                 //EventHandler.Step (req_id, thread_id, id, loc);
1272                                                         } else if (kind == EventKind.EXCEPTION) {
1273                                                                 long thread_id = r.ReadId ();
1274                                                                 long id = r.ReadId ();
1275                                                                 long loc = 0; // FIXME
1276                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
1277                                                                 //EventHandler.Exception (req_id, thread_id, id, loc);
1278                                                         } else if (kind == EventKind.APPDOMAIN_CREATE) {
1279                                                                 long thread_id = r.ReadId ();
1280                                                                 long id = r.ReadId ();
1281                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1282                                                                 //EventHandler.AppDomainCreate (req_id, thread_id, id);
1283                                                         } else if (kind == EventKind.APPDOMAIN_UNLOAD) {
1284                                                                 long thread_id = r.ReadId ();
1285                                                                 long id = r.ReadId ();
1286                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1287                                                                 //EventHandler.AppDomainUnload (req_id, thread_id, id);
1288                                                         } else if (kind == EventKind.USER_BREAK) {
1289                                                                 long thread_id = r.ReadId ();
1290                                                                 long id = 0;
1291                                                                 long loc = 0;
1292                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
1293                                                                 //EventHandler.Exception (req_id, thread_id, id, loc);
1294                                                         } else if (kind == EventKind.USER_LOG) {
1295                                                                 long thread_id = r.ReadId ();
1296                                                                 int level = r.ReadInt ();
1297                                                                 string category = r.ReadString ();
1298                                                                 string message = r.ReadString ();
1299                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Level = level, Category = category, Message = message };
1300                                                                 //EventHandler.Exception (req_id, thread_id, id, loc);
1301                                                         } else if (kind == EventKind.KEEPALIVE) {
1302                                                                 events [i] = new EventInfo (etype, req_id) { };
1303                                                         } else {
1304                                                                 throw new NotImplementedException ("Unknown event kind: " + kind);
1305                                                         }
1306                                                 }
1307
1308                                                 EventHandler.Events (suspend_policy, events);
1309                                         }
1310                                 }
1311
1312                                 return true;
1313                 }
1314
1315                 internal IEventHandler EventHandler {
1316                         get; set;
1317                 }
1318
1319                 static String CommandString (CommandSet command_set, int command)
1320                 {
1321                         string cmd;
1322                         switch (command_set) {
1323                         case CommandSet.VM:
1324                                 cmd = ((CmdVM)command).ToString ();
1325                                 break;
1326                         case CommandSet.OBJECT_REF:
1327                                 cmd = ((CmdObjectRef)command).ToString ();
1328                                 break;
1329                         case CommandSet.STRING_REF:
1330                                 cmd = ((CmdStringRef)command).ToString ();
1331                                 break;
1332                         case CommandSet.THREAD:
1333                                 cmd = ((CmdThread)command).ToString ();
1334                                 break;
1335                         case CommandSet.ARRAY_REF:
1336                                 cmd = ((CmdArrayRef)command).ToString ();
1337                                 break;
1338                         case CommandSet.EVENT_REQUEST:
1339                                 cmd = ((CmdEventRequest)command).ToString ();
1340                                 break;
1341                         case CommandSet.STACK_FRAME:
1342                                 cmd = ((CmdStackFrame)command).ToString ();
1343                                 break;
1344                         case CommandSet.APPDOMAIN:
1345                                 cmd = ((CmdAppDomain)command).ToString ();
1346                                 break;
1347                         case CommandSet.ASSEMBLY:
1348                                 cmd = ((CmdAssembly)command).ToString ();
1349                                 break;
1350                         case CommandSet.METHOD:
1351                                 cmd = ((CmdMethod)command).ToString ();
1352                                 break;
1353                         case CommandSet.TYPE:
1354                                 cmd = ((CmdType)command).ToString ();
1355                                 break;
1356                         case CommandSet.MODULE:
1357                                 cmd = ((CmdModule)command).ToString ();
1358                                 break;
1359                         case CommandSet.EVENT:
1360                                 cmd = ((CmdEvent)command).ToString ();
1361                                 break;
1362                         default:
1363                                 cmd = command.ToString ();
1364                                 break;
1365                         }
1366                         return string.Format ("[{0} {1}]", command_set, cmd);
1367                 }
1368
1369                 long total_protocol_ticks;
1370
1371                 void LogPacket (int packet_id, byte[] encoded_packet, byte[] reply_packet, CommandSet command_set, int command, Stopwatch watch) {
1372                         watch.Stop ();
1373                         total_protocol_ticks += watch.ElapsedTicks;
1374                         var ts = TimeSpan.FromTicks (total_protocol_ticks);
1375                         string msg = string.Format ("Packet: {0} sent: {1} received: {2} ms: {3} total ms: {4} {5}",
1376                            packet_id, encoded_packet.Length, reply_packet.Length, watch.ElapsedMilliseconds,
1377                            (ts.Seconds * 1000) + ts.Milliseconds,
1378                            CommandString (command_set, command));
1379
1380                         LoggingStream.WriteLine (msg);
1381                         LoggingStream.Flush ();
1382                 }
1383
1384                 /* Send a request and call cb when a result is received */
1385                 int Send (CommandSet command_set, int command, PacketWriter packet, Action<PacketReader> cb, int count) {
1386                         int id = IdGenerator;
1387
1388                         Stopwatch watch = null;
1389                         if (EnableConnectionLogging)
1390                                 watch = Stopwatch.StartNew ();
1391
1392                         byte[] encoded_packet;
1393                         if (packet == null)
1394                                 encoded_packet = EncodePacket (id, (int)command_set, command, null, 0);
1395                         else
1396                                 encoded_packet = EncodePacket (id, (int)command_set, command, packet.Data, packet.Offset);
1397
1398                         lock (reply_packets_monitor) {
1399                                 reply_cbs [id] = delegate (int packet_id, byte[] p) {
1400                                         if (EnableConnectionLogging)
1401                                                 LogPacket (packet_id, encoded_packet, p, command_set, command, watch);
1402                                         /* Run the callback on a tp thread to avoid blocking the receive thread */
1403                                         PacketReader r = new PacketReader (p);
1404                                         cb.BeginInvoke (r, null, null);
1405                                 };
1406                                 reply_cb_counts [id] = count;
1407                         }
1408
1409                         WritePacket (encoded_packet);
1410
1411                         return id;
1412                 }
1413
1414                 PacketReader SendReceive (CommandSet command_set, int command, PacketWriter packet) {
1415                         int id = IdGenerator;
1416                         Stopwatch watch = null;
1417
1418                         if (disconnected)
1419                                 throw new VMDisconnectedException ();
1420
1421                         if (EnableConnectionLogging)
1422                                 watch = Stopwatch.StartNew ();
1423
1424                         byte[] encoded_packet;
1425
1426                         if (packet == null)
1427                                 encoded_packet = EncodePacket (id, (int)command_set, command, null, 0);
1428                         else
1429                                 encoded_packet = EncodePacket (id, (int)command_set, command, packet.Data, packet.Offset);
1430
1431                         WritePacket (encoded_packet);
1432
1433                         int packetId = id;
1434
1435                         /* Wait for the reply packet */
1436                         while (true) {
1437                                 lock (reply_packets_monitor) {
1438                                         if (reply_packets.ContainsKey (packetId)) {
1439                                                 byte[] reply = reply_packets [packetId];
1440                                                 reply_packets.Remove (packetId);
1441                                                 PacketReader r = new PacketReader (reply);
1442
1443                                                 if (EnableConnectionLogging)
1444                                                         LogPacket (packetId, encoded_packet, reply, command_set, command, watch);
1445                                                 if (r.ErrorCode != 0) {
1446                                                         if (ErrorHandler != null)
1447                                                                 ErrorHandler (this, new ErrorHandlerEventArgs () { ErrorCode = (ErrorCode)r.ErrorCode });
1448                                                         throw new NotImplementedException ("No error handler set.");
1449                                                 } else {
1450                                                         return r;
1451                                                 }
1452                                         } else {
1453                                                 if (disconnected)
1454                                                         throw new VMDisconnectedException ();
1455                                                 Monitor.Wait (reply_packets_monitor);
1456                                         }
1457                                 }
1458                         }
1459                 }
1460
1461                 PacketReader SendReceive (CommandSet command_set, int command) {
1462                         return SendReceive (command_set, command, null);
1463                 }
1464
1465                 int packet_id_generator;
1466
1467                 int IdGenerator {
1468                         get {
1469                                 return Interlocked.Increment (ref packet_id_generator);
1470                         }
1471                 }
1472
1473                 CattrInfo[] ReadCattrs (PacketReader r) {
1474                         CattrInfo[] res = new CattrInfo [r.ReadInt ()];
1475                         for (int i = 0; i < res.Length; ++i) {
1476                                 CattrInfo info = new CattrInfo ();
1477                                 info.ctor_id = r.ReadId ();
1478                                 info.ctor_args = new ValueImpl [r.ReadInt ()];
1479                                 for (int j = 0; j < info.ctor_args.Length; ++j) {
1480                                         info.ctor_args [j] = r.ReadValue ();
1481                                 }
1482                                 info.named_args = new CattrNamedArgInfo [r.ReadInt ()];
1483                                 for (int j = 0; j < info.named_args.Length; ++j) {
1484                                         CattrNamedArgInfo arg = new CattrNamedArgInfo ();
1485                                         int arg_type = r.ReadByte ();
1486                                         arg.is_property = arg_type == 0x54;
1487                                         arg.id = r.ReadId ();
1488                                         arg.value = r.ReadValue ();
1489                                         info.named_args [j] = arg;
1490                                 }
1491                                 res [i] = info;
1492                         }
1493                         return res;
1494                 }
1495
1496                 static ElementType TypeCodeToElementType (TypeCode c) {
1497                         switch (c) {
1498                         case TypeCode.Boolean:
1499                                 return ElementType.Boolean;
1500                         case TypeCode.Char:
1501                                 return ElementType.Char;
1502                         case TypeCode.SByte:
1503                                 return ElementType.I1;
1504                         case TypeCode.Byte:
1505                                 return ElementType.U1;
1506                         case TypeCode.Int16:
1507                                 return ElementType.I2;
1508                         case TypeCode.UInt16:
1509                                 return ElementType.U2;
1510                         case TypeCode.Int32:
1511                                 return ElementType.I4;
1512                         case TypeCode.UInt32:
1513                                 return ElementType.U4;
1514                         case TypeCode.Int64:
1515                                 return ElementType.I8;
1516                         case TypeCode.UInt64:
1517                                 return ElementType.U8;
1518                         case TypeCode.Single:
1519                                 return ElementType.R4;
1520                         case TypeCode.Double:
1521                                 return ElementType.R8;
1522                         default:
1523                                 throw new NotImplementedException ();
1524                         }
1525                 }
1526
1527                 /*
1528                  * Implementation of debugger commands
1529                  */
1530
1531                 internal VersionInfo VM_GetVersion () {
1532                         var res = SendReceive (CommandSet.VM, (int)CmdVM.VERSION, null);
1533                         VersionInfo info = new VersionInfo ();
1534                         info.VMVersion = res.ReadString ();
1535                         info.MajorVersion = res.ReadInt ();
1536                         info.MinorVersion = res.ReadInt ();
1537                         return info;
1538                 }
1539
1540                 internal void VM_SetProtocolVersion (int major, int minor) {
1541                         SendReceive (CommandSet.VM, (int)CmdVM.SET_PROTOCOL_VERSION, new PacketWriter ().WriteInt (major).WriteInt (minor));
1542                 }
1543
1544                 internal long[] VM_GetThreads () {
1545                         var res = SendReceive (CommandSet.VM, (int)CmdVM.ALL_THREADS, null);
1546                         int len = res.ReadInt ();
1547                         long[] arr = new long [len];
1548                         for (int i = 0; i < len; ++i)
1549                                 arr [i] = res.ReadId ();
1550                         return arr;
1551                 }
1552
1553                 internal void VM_Suspend () {
1554                         SendReceive (CommandSet.VM, (int)CmdVM.SUSPEND);
1555                 }
1556
1557                 internal void VM_Resume () {
1558                         SendReceive (CommandSet.VM, (int)CmdVM.RESUME);
1559                 }
1560
1561                 internal void VM_Exit (int exitCode) {
1562                         SendReceive (CommandSet.VM, (int)CmdVM.EXIT, new PacketWriter ().WriteInt (exitCode));
1563                 }
1564
1565                 internal void VM_Dispose () {
1566                         SendReceive (CommandSet.VM, (int)CmdVM.DISPOSE);
1567                 }
1568
1569                 internal ValueImpl VM_InvokeMethod (long thread, long method, ValueImpl this_arg, ValueImpl[] arguments, InvokeFlags flags, out ValueImpl exc) {
1570                         exc = null;
1571                         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));
1572                         if (r.ReadByte () == 0) {
1573                                 exc = r.ReadValue ();
1574                                 return null;
1575                         } else {
1576                                 return r.ReadValue ();
1577                         }
1578                 }
1579
1580                 internal delegate void InvokeMethodCallback (ValueImpl v, ValueImpl exc, ErrorCode error, object state);
1581
1582                 internal int VM_BeginInvokeMethod (long thread, long method, ValueImpl this_arg, ValueImpl[] arguments, InvokeFlags flags, InvokeMethodCallback callback, object state) {
1583                         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) {
1584                                         ValueImpl v, exc;
1585
1586                                         if (r.ErrorCode != 0) {
1587                                                 callback (null, null, (ErrorCode)r.ErrorCode, state);
1588                                         } else {
1589                                                 if (r.ReadByte () == 0) {
1590                                                         exc = r.ReadValue ();
1591                                                         v = null;
1592                                                 } else {
1593                                                         v = r.ReadValue ();
1594                                                         exc = null;
1595                                                 }
1596
1597                                                 callback (v, exc, 0, state);
1598                                         }
1599                                 }, 1);
1600                 }
1601
1602                 internal int VM_BeginInvokeMethods (long thread, long[] methods, ValueImpl this_arg, List<ValueImpl[]> arguments, InvokeFlags flags, InvokeMethodCallback callback, object state) {
1603                         // FIXME: Merge this with INVOKE_METHOD
1604                         var w = new PacketWriter ();
1605                         w.WriteId (thread);
1606                         w.WriteInt ((int)flags);
1607                         w.WriteInt (methods.Length);
1608                         for (int i = 0; i < methods.Length; ++i) {
1609                                 w.WriteId (methods [i]);
1610                                 w.WriteValue (this_arg);
1611                                 w.WriteInt (arguments [i].Length);
1612                                 w.WriteValues (arguments [i]);
1613                         }
1614                         return Send (CommandSet.VM, (int)CmdVM.INVOKE_METHODS, w, delegate (PacketReader r) {
1615                                         ValueImpl v, exc;
1616
1617                                         if (r.ErrorCode != 0) {
1618                                                 callback (null, null, (ErrorCode)r.ErrorCode, state);
1619                                         } else {
1620                                                 if (r.ReadByte () == 0) {
1621                                                         exc = r.ReadValue ();
1622                                                         v = null;
1623                                                 } else {
1624                                                         v = r.ReadValue ();
1625                                                         exc = null;
1626                                                 }
1627
1628                                                 callback (v, exc, 0, state);
1629                                         }
1630                                 }, methods.Length);
1631                 }
1632
1633                 internal void VM_AbortInvoke (long thread, int id)
1634                 {
1635                         SendReceive (CommandSet.VM, (int)CmdVM.ABORT_INVOKE, new PacketWriter ().WriteId (thread).WriteInt (id));
1636                 }
1637
1638                 internal void SetSocketTimeouts (int send_timeout, int receive_timeout, int keepalive_interval)
1639                 {
1640                         TransportSetTimeouts (send_timeout, receive_timeout);
1641                         SendReceive (CommandSet.VM, (int)CmdVM.SET_KEEPALIVE, new PacketWriter ().WriteId (keepalive_interval));
1642                 }
1643
1644                 internal long[] VM_GetTypesForSourceFile (string fname, bool ignoreCase) {
1645                         var res = SendReceive (CommandSet.VM, (int)CmdVM.GET_TYPES_FOR_SOURCE_FILE, new PacketWriter ().WriteString (fname).WriteBool (ignoreCase));
1646                         int count = res.ReadInt ();
1647                         long[] types = new long [count];
1648                         for (int i = 0; i < count; ++i)
1649                                 types [i] = res.ReadId ();
1650                         return types;
1651                 }
1652
1653                 internal long[] VM_GetTypes (string name, bool ignoreCase) {
1654                         var res = SendReceive (CommandSet.VM, (int)CmdVM.GET_TYPES, new PacketWriter ().WriteString (name).WriteBool (ignoreCase));
1655                         int count = res.ReadInt ();
1656                         long[] types = new long [count];
1657                         for (int i = 0; i < count; ++i)
1658                                 types [i] = res.ReadId ();
1659                         return types;
1660                 }
1661
1662                 /*
1663                  * DOMAIN
1664                  */
1665
1666                 internal long RootDomain {
1667                         get {
1668                                 return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_ROOT_DOMAIN, null).ReadId ();
1669                         }
1670                 }
1671
1672                 internal string Domain_GetName (long id) {
1673                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_FRIENDLY_NAME, new PacketWriter ().WriteId (id)).ReadString ();
1674                 }
1675
1676                 internal long[] Domain_GetAssemblies (long id) {
1677                         var res = SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_ASSEMBLIES, new PacketWriter ().WriteId (id));
1678                         int count = res.ReadInt ();
1679                         long[] assemblies = new long [count];
1680                         for (int i = 0; i < count; ++i)
1681                                 assemblies [i] = res.ReadId ();
1682                         return assemblies;
1683                 }
1684
1685                 internal long Domain_GetEntryAssembly (long id) {
1686                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_ENTRY_ASSEMBLY, new PacketWriter ().WriteId (id)).ReadId ();
1687                 }
1688
1689                 internal long Domain_GetCorlib (long id) {
1690                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_CORLIB, new PacketWriter ().WriteId (id)).ReadId ();
1691                 }
1692
1693                 internal long Domain_CreateString (long id, string s) {
1694                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.CREATE_STRING, new PacketWriter ().WriteId (id).WriteString (s)).ReadId ();
1695                 }
1696
1697                 internal long Domain_CreateBoxedValue (long id, long type_id, ValueImpl v) {
1698                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.CREATE_BOXED_VALUE, new PacketWriter ().WriteId (id).WriteId (type_id).WriteValue (v)).ReadId ();
1699                 }
1700
1701                 /*
1702                  * METHOD
1703                  */
1704
1705                 internal string Method_GetName (long id) {
1706                         return SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_NAME, new PacketWriter ().WriteId (id)).ReadString ();
1707                 }
1708
1709                 internal long Method_GetDeclaringType (long id) {
1710                         return SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_DECLARING_TYPE, new PacketWriter ().WriteId (id)).ReadId ();
1711                 }
1712
1713                 internal DebugInfo Method_GetDebugInfo (long id) {
1714                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_DEBUG_INFO, new PacketWriter ().WriteId (id));
1715
1716                         DebugInfo info = new DebugInfo ();
1717                         info.max_il_offset = res.ReadInt ();
1718
1719                         SourceInfo[] sources = null;
1720                         if (Version.AtLeast (2, 13)) {
1721                                 int n = res.ReadInt ();
1722                                 sources = new SourceInfo [n];
1723                                 for (int i = 0; i < n; ++i) {
1724                                         sources [i].source_file = res.ReadString ();
1725                                         if (Version.AtLeast (2, 14)) {
1726                                                 sources [i].hash = new byte [16];
1727                                                 for (int j = 0; j < 16; ++j)
1728                                                         sources [i].hash [j] = (byte)res.ReadByte ();
1729                                         }
1730                                 }
1731                         } else {
1732                                 sources = new SourceInfo [1];
1733                                 sources [0].source_file = res.ReadString ();
1734                         }
1735
1736                         int n_il_offsets = res.ReadInt ();
1737                         info.il_offsets = new int [n_il_offsets];
1738                         info.line_numbers = new int [n_il_offsets];
1739                         info.source_files = new SourceInfo [n_il_offsets];
1740                         info.column_numbers = new int [n_il_offsets];
1741                         for (int i = 0; i < n_il_offsets; ++i) {
1742                                 info.il_offsets [i] = res.ReadInt ();
1743                                 info.line_numbers [i] = res.ReadInt ();
1744                                 if (Version.AtLeast (2, 12)) {
1745                                         int idx = res.ReadInt ();
1746                                         info.source_files [i] = idx >= 0 ? sources [idx] : default (SourceInfo);
1747                                 } else {
1748                                         info.source_files [i] = sources [0];
1749                                 }
1750                                 if (Version.AtLeast (2, 19))
1751                                         info.column_numbers [i] = res.ReadInt ();
1752                                 else
1753                                         info.column_numbers [i] = 0;
1754                         }
1755
1756                         return info;
1757                 }
1758
1759                 internal ParamInfo Method_GetParamInfo (long id) {
1760                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_PARAM_INFO, new PacketWriter ().WriteId (id));
1761
1762                         ParamInfo info = new ParamInfo ();
1763                         info.call_conv = res.ReadInt ();
1764                         info.param_count = res.ReadInt ();
1765                         info.generic_param_count = res.ReadInt ();
1766                         info.ret_type = res.ReadId ();
1767                         info.param_types = new long [info.param_count];
1768                         for (int i = 0; i < info.param_count; ++i)
1769                                 info.param_types [i] = res.ReadId ();
1770                         info.param_names = new string [info.param_count];                       
1771                         for (int i = 0; i < info.param_count; ++i)
1772                                 info.param_names [i] = res.ReadString ();
1773
1774                         return info;
1775                 }
1776
1777                 internal LocalsInfo Method_GetLocalsInfo (long id) {
1778                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_LOCALS_INFO, new PacketWriter ().WriteId (id));
1779
1780                         LocalsInfo info = new LocalsInfo ();
1781                         int nlocals = res.ReadInt ();
1782                         info.types = new long [nlocals];
1783                         for (int i = 0; i < nlocals; ++i)
1784                                 info.types [i] = res.ReadId ();
1785                         info.names = new string [nlocals];
1786                         for (int i = 0; i < nlocals; ++i)
1787                                 info.names [i] = res.ReadString ();
1788                         info.live_range_start = new int [nlocals];
1789                         info.live_range_end = new int [nlocals];
1790                         for (int i = 0; i < nlocals; ++i) {
1791                                 info.live_range_start [i] = res.ReadInt ();
1792                                 info.live_range_end [i] = res.ReadInt ();
1793                         }
1794
1795                         return info;
1796                 }
1797
1798                 internal MethodInfo Method_GetInfo (long id) {
1799                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_INFO, new PacketWriter ().WriteId (id));
1800
1801                         MethodInfo info = new MethodInfo ();
1802                         info.attributes = res.ReadInt ();
1803                         info.iattributes = res.ReadInt ();
1804                         info.token = res.ReadInt ();
1805                         if (Version.AtLeast (2, 12)) {
1806                                 int attrs = res.ReadByte ();
1807                                 if ((attrs & (1 << 0)) != 0)
1808                                         info.is_gmd = true;
1809                                 if ((attrs & (1 << 1)) != 0)
1810                                         info.is_generic_method = true;
1811                                 info.gmd = res.ReadId ();
1812                                 if (Version.AtLeast (2, 15)) {
1813                                         if (info.is_generic_method) {
1814                                                 int n = res.ReadInt ();
1815                                                 info.type_args = res.ReadIds (n);
1816                                         }
1817                                 }
1818                         }
1819                         return info;
1820                 }
1821
1822                 internal MethodBodyInfo Method_GetBody (long id) {
1823                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_BODY, new PacketWriter ().WriteId (id));
1824
1825                         MethodBodyInfo info = new MethodBodyInfo ();
1826                         info.il = new byte [res.ReadInt ()];
1827                         for (int i = 0; i < info.il.Length; ++i)
1828                                 info.il [i] = (byte)res.ReadByte ();
1829
1830                         if (Version.AtLeast (2, 18)) {
1831                                 info.clauses = new ExceptionClauseInfo [res.ReadInt ()];
1832
1833                                 for (int i = 0; i < info.clauses.Length; ++i) {
1834                                         var clause = new ExceptionClauseInfo {
1835                                                 flags = (ExceptionClauseFlags) res.ReadInt (),
1836                                                 try_offset = res.ReadInt (),
1837                                                 try_length = res.ReadInt (),
1838                                                 handler_offset = res.ReadInt (),
1839                                                 handler_length = res.ReadInt (),
1840                                         };
1841
1842                                         if (clause.flags == ExceptionClauseFlags.None)
1843                                                 clause.catch_type_id = res.ReadId ();
1844                                         else if (clause.flags == ExceptionClauseFlags.Filter)
1845                                                 clause.filter_offset = res.ReadInt ();
1846
1847                                         info.clauses [i] = clause;
1848                                 }
1849                         } else
1850                                 info.clauses = new ExceptionClauseInfo [0];
1851
1852                         return info;
1853                 }
1854
1855                 internal ResolvedToken Method_ResolveToken (long id, int token) {
1856                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.RESOLVE_TOKEN, new PacketWriter ().WriteId (id).WriteInt (token));
1857
1858                         TokenType type = (TokenType)res.ReadByte ();
1859                         switch (type) {
1860                         case TokenType.STRING:
1861                                 return new ResolvedToken () { Type = type, Str = res.ReadString () };
1862                         case TokenType.TYPE:
1863                         case TokenType.METHOD:
1864                         case TokenType.FIELD:
1865                                 return new ResolvedToken () { Type = type, Id = res.ReadId () };
1866                         case TokenType.UNKNOWN:
1867                                 return new ResolvedToken () { Type = type };
1868                         default:
1869                                 throw new NotImplementedException ();
1870                         }
1871                 }
1872
1873                 internal CattrInfo[] Method_GetCustomAttributes (long id, long attr_type_id, bool inherit) {
1874                         PacketReader r = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_CATTRS, new PacketWriter ().WriteId (id).WriteId (attr_type_id));
1875                         return ReadCattrs (r);
1876                 }
1877
1878                 /*
1879                  * THREAD
1880                  */
1881
1882                 internal string Thread_GetName (long id) {
1883                         return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_NAME, new PacketWriter ().WriteId (id)).ReadString ();
1884                 }
1885
1886                 internal FrameInfo[] Thread_GetFrameInfo (long id, int start_frame, int length) {
1887                         var res = SendReceive (CommandSet.THREAD, (int)CmdThread.GET_FRAME_INFO, new PacketWriter ().WriteId (id).WriteInt (start_frame).WriteInt (length));
1888                         int count = res.ReadInt ();
1889
1890                         var frames = new FrameInfo [count];
1891                         for (int i = 0; i < count; ++i) {
1892                                 var f = new FrameInfo ();
1893                                 f.id = res.ReadInt ();
1894                                 f.method = res.ReadId ();
1895                                 f.il_offset = res.ReadInt ();
1896                                 f.flags = (StackFrameFlags)res.ReadByte ();
1897                                 frames [i] = f;
1898                         }
1899
1900                         return frames;
1901                 }
1902
1903                 internal int Thread_GetState (long id) {
1904                         return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_STATE, new PacketWriter ().WriteId (id)).ReadInt ();
1905                 }
1906
1907                 internal ThreadInfo Thread_GetInfo (long id) {
1908                         PacketReader r = SendReceive (CommandSet.THREAD, (int)CmdThread.GET_INFO, new PacketWriter ().WriteId (id));
1909
1910                         ThreadInfo res = new ThreadInfo () { is_thread_pool = r.ReadByte () > 0 ? true : false };
1911
1912                         return res;
1913                 }
1914
1915                 internal long Thread_GetId (long id) {
1916                         return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_ID, new PacketWriter ().WriteId (id)).ReadLong ();
1917                 }
1918
1919                 internal long Thread_GetTID (long id) {
1920                         return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_TID, new PacketWriter ().WriteId (id)).ReadLong ();
1921                 }
1922
1923                 /*
1924                  * MODULE
1925                  */
1926
1927                 internal ModuleInfo Module_GetInfo (long id) {
1928                         PacketReader r = SendReceive (CommandSet.MODULE, (int)CmdModule.GET_INFO, new PacketWriter ().WriteId (id));
1929                         ModuleInfo info = new ModuleInfo { Name = r.ReadString (), ScopeName = r.ReadString (), FQName = r.ReadString (), Guid = r.ReadString (), Assembly = r.ReadId () };
1930                         return info;
1931                 }
1932
1933                 /*
1934                  * ASSEMBLY
1935                  */
1936
1937                 internal string Assembly_GetLocation (long id) {
1938                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_LOCATION, new PacketWriter ().WriteId (id)).ReadString ();
1939                 }
1940
1941                 internal long Assembly_GetEntryPoint (long id) {
1942                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_ENTRY_POINT, new PacketWriter ().WriteId (id)).ReadId ();
1943                 }
1944
1945                 internal long Assembly_GetManifestModule (long id) {
1946                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_MANIFEST_MODULE, new PacketWriter ().WriteId (id)).ReadId ();
1947                 }
1948
1949                 internal long Assembly_GetObject (long id) {
1950                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_OBJECT, new PacketWriter ().WriteId (id)).ReadId ();
1951                 }
1952
1953                 internal long Assembly_GetType (long id, string name, bool ignoreCase) {
1954                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_TYPE, new PacketWriter ().WriteId (id).WriteString (name).WriteBool (ignoreCase)).ReadId ();
1955                 }
1956
1957                 internal string Assembly_GetName (long id) {
1958                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_NAME, new PacketWriter ().WriteId (id)).ReadString ();
1959                 }
1960
1961                 /*
1962                  * TYPE
1963                  */
1964
1965                 internal TypeInfo Type_GetInfo (long id) {
1966                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_INFO, new PacketWriter ().WriteId (id));
1967                         TypeInfo res = new TypeInfo ();
1968
1969                         res.ns = r.ReadString ();
1970                         res.name = r.ReadString ();
1971                         res.full_name = r.ReadString ();
1972                         res.assembly = r.ReadId ();
1973                         res.module = r.ReadId ();
1974                         res.base_type = r.ReadId ();
1975                         res.element_type = r.ReadId ();
1976                         res.token = r.ReadInt ();
1977                         res.rank = r.ReadByte ();
1978                         res.attributes = r.ReadInt ();
1979                         int b = r.ReadByte ();
1980                         res.is_byref = (b & 1) != 0;
1981                         res.is_pointer = (b & 2) != 0;
1982                         res.is_primitive = (b & 4) != 0;
1983                         res.is_valuetype = (b & 8) != 0;
1984                         res.is_enum = (b & 16) != 0;
1985                         res.is_gtd = (b & 32) != 0;
1986                         res.is_generic_type = (b & 64) != 0;
1987
1988                         int nested_len = r.ReadInt ();
1989                         res.nested = new long [nested_len];
1990                         for (int i = 0; i < nested_len; ++i)
1991                                 res.nested [i] = r.ReadId ();
1992
1993                         if (Version.AtLeast (2, 12))
1994                                 res.gtd = r.ReadId ();
1995                         if (Version.AtLeast (2, 15) && res.is_generic_type) {
1996                                 int n = r.ReadInt ();
1997                                 res.type_args = r.ReadIds (n);
1998                         }
1999
2000                         return res;
2001                 }
2002
2003                 internal long[] Type_GetMethods (long id) {
2004                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_METHODS, new PacketWriter ().WriteId (id));
2005
2006                         int n = r.ReadInt ();
2007                         long[] res = new long [n];
2008                         for (int i = 0; i < n; ++i)
2009                                 res [i] = r.ReadId ();
2010                         return res;
2011                 }
2012
2013                 internal long[] Type_GetFields (long id, out string[] names, out long[] types, out int[] attrs) {
2014                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_FIELDS, new PacketWriter ().WriteId (id));
2015
2016                         int n = r.ReadInt ();
2017                         long[] res = new long [n];
2018                         names = new string [n];
2019                         types = new long [n];
2020                         attrs = new int [n];
2021                         for (int i = 0; i < n; ++i) {
2022                                 res [i] = r.ReadId ();
2023                                 names [i] = r.ReadString ();
2024                                 types [i] = r.ReadId ();
2025                                 attrs [i] = r.ReadInt ();
2026                         }
2027                         return res;
2028                 }
2029
2030                 internal PropInfo[] Type_GetProperties (long id) {
2031                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_PROPERTIES, new PacketWriter ().WriteId (id));
2032
2033                         int n = r.ReadInt ();
2034                         PropInfo[] res = new PropInfo [n];
2035                         for (int i = 0; i < n; ++i) {
2036                                 res [i] = new PropInfo ();
2037                                 res [i].id = r.ReadId ();
2038                                 res [i].name = r.ReadString ();
2039                                 res [i].get_method = r.ReadId ();
2040                                 res [i].set_method = r.ReadId ();
2041                                 res [i].attrs = r.ReadInt ();
2042                         }
2043
2044                         return res;
2045                 }
2046
2047                 internal long Type_GetObject (long id) {
2048                         return SendReceive (CommandSet.TYPE, (int)CmdType.GET_OBJECT, new PacketWriter ().WriteId (id)).ReadId ();
2049                 }
2050
2051                 internal ValueImpl[] Type_GetValues (long id, long[] fields, long thread_id) {
2052                         int len = fields.Length;
2053                         PacketReader r;
2054                         if (thread_id != 0)
2055                                 r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_VALUES_2, new PacketWriter ().WriteId (id).WriteId (thread_id).WriteInt (len).WriteIds (fields));
2056                         else
2057                                 r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_VALUES, new PacketWriter ().WriteId (id).WriteInt (len).WriteIds (fields));
2058
2059                         ValueImpl[] res = new ValueImpl [len];
2060                         for (int i = 0; i < len; ++i)
2061                                 res [i] = r.ReadValue ();
2062                         return res;
2063                 }                       
2064
2065                 internal void Type_SetValues (long id, long[] fields, ValueImpl[] values) {
2066                         SendReceive (CommandSet.TYPE, (int)CmdType.SET_VALUES, new PacketWriter ().WriteId (id).WriteInt (fields.Length).WriteIds (fields).WriteValues (values));
2067                 }
2068
2069                 internal string[] Type_GetSourceFiles (long id, bool return_full_paths) {
2070                         var r = SendReceive (CommandSet.TYPE, return_full_paths ? (int)CmdType.GET_SOURCE_FILES_2 : (int)CmdType.GET_SOURCE_FILES, new PacketWriter ().WriteId (id));
2071                         int len = r.ReadInt ();
2072                         string[] res = new string [len];
2073                         for (int i = 0; i < len; ++i)
2074                                 res [i] = r.ReadString ();
2075                         return res;
2076                 }
2077
2078                 internal bool Type_IsAssignableFrom (long id, long c_id) {
2079                         return SendReceive (CommandSet.TYPE, (int)CmdType.IS_ASSIGNABLE_FROM, new PacketWriter ().WriteId (id).WriteId (c_id)).ReadByte () > 0;
2080                 }
2081
2082                 internal CattrInfo[] Type_GetCustomAttributes (long id, long attr_type_id, bool inherit) {
2083                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_CATTRS, new PacketWriter ().WriteId (id).WriteId (attr_type_id));
2084                         return ReadCattrs (r);
2085                 }
2086
2087                 internal CattrInfo[] Type_GetFieldCustomAttributes (long id, long field_id, long attr_type_id, bool inherit) {
2088                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_FIELD_CATTRS, new PacketWriter ().WriteId (id).WriteId (field_id).WriteId (attr_type_id));
2089                         return ReadCattrs (r);
2090                 }
2091
2092                 internal CattrInfo[] Type_GetPropertyCustomAttributes (long id, long field_id, long attr_type_id, bool inherit) {
2093                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_PROPERTY_CATTRS, new PacketWriter ().WriteId (id).WriteId (field_id).WriteId (attr_type_id));
2094                         return ReadCattrs (r);
2095                 }
2096
2097                 public long[] Type_GetMethodsByNameFlags (long id, string name, int flags, bool ignoreCase) {
2098                         flags |= ignoreCase ? (int)BindingFlagsExtensions.BINDING_FLAGS_IGNORE_CASE : 0;
2099                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.CMD_TYPE_GET_METHODS_BY_NAME_FLAGS, new PacketWriter ().WriteId (id).WriteString (name).WriteInt (flags));
2100                         int len = r.ReadInt ();
2101                         long[] res = new long [len];
2102                         for (int i = 0; i < len; ++i)
2103                                 res [i] = r.ReadId ();
2104                         return res;
2105                 }
2106
2107                 internal long[] Type_GetInterfaces (long id) {
2108                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_INTERFACES, new PacketWriter ().WriteId (id));
2109                         int len = r.ReadInt ();
2110                         return r.ReadIds (len);
2111                 }
2112
2113                 internal IfaceMapInfo[] Type_GetInterfaceMap (long id, long[] ids) {
2114                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_INTERFACE_MAP, new PacketWriter ().WriteId (id).WriteInt (ids.Length).WriteIds (ids));
2115                         var res = new IfaceMapInfo [ids.Length];
2116                         for (int i = 0; i < ids.Length; ++i) {
2117                                 int n = r.ReadInt ();
2118
2119                                 res [i].iface_id = ids [i];
2120                                 res [i].iface_methods = r.ReadIds (n);
2121                                 res [i].target_methods = r.ReadIds (n);
2122                         }
2123
2124                         return res;
2125                 }
2126
2127                 internal bool Type_IsInitialized (long id) {
2128                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.IS_INITIALIZED, new PacketWriter ().WriteId (id));
2129                         return r.ReadInt () == 1;
2130                 }
2131
2132                 /*
2133                  * EVENTS
2134                  */
2135
2136                 internal int EnableEvent (EventType etype, SuspendPolicy suspend_policy, List<Modifier> mods) {
2137                         var w = new PacketWriter ().WriteByte ((byte)etype).WriteByte ((byte)suspend_policy);
2138                         if (mods != null) {
2139                                 if (mods.Count > 255)
2140                                         throw new NotImplementedException ();
2141                                 w.WriteByte ((byte)mods.Count);
2142                                 foreach (Modifier mod in mods) {
2143                                         if (mod is CountModifier) {
2144                                                 w.WriteByte ((byte)ModifierKind.COUNT);
2145                                                 w.WriteInt ((mod as CountModifier).Count);
2146                                         } else if (mod is LocationModifier) {
2147                                                 w.WriteByte ((byte)ModifierKind.LOCATION_ONLY);
2148                                                 w.WriteId ((mod as LocationModifier).Method);
2149                                                 w.WriteLong ((mod as LocationModifier).Location);
2150                                         } else if (mod is StepModifier) {
2151                                                 w.WriteByte ((byte)ModifierKind.STEP);
2152                                                 w.WriteId ((mod as StepModifier).Thread);
2153                                                 w.WriteInt ((mod as StepModifier).Size);
2154                                                 w.WriteInt ((mod as StepModifier).Depth);
2155                                                 if (Version.AtLeast (2, 16))
2156                                                         w.WriteInt ((mod as StepModifier).Filter);
2157                                         } else if (mod is ThreadModifier) {
2158                                                 w.WriteByte ((byte)ModifierKind.THREAD_ONLY);
2159                                                 w.WriteId ((mod as ThreadModifier).Thread);
2160                                         } else if (mod is ExceptionModifier) {
2161                                                 var em = mod as ExceptionModifier;
2162                                                 w.WriteByte ((byte)ModifierKind.EXCEPTION_ONLY);
2163                                                 w.WriteId (em.Type);
2164                                                 if (Version.MajorVersion > 2 || Version.MinorVersion > 0) {
2165                                                         /* This is only supported in protocol version 2.1 */
2166                                                         w.WriteBool (em.Caught);
2167                                                         w.WriteBool (em.Uncaught);
2168                                                 } else if (!em.Caught || !em.Uncaught) {
2169                                                         throw new NotSupportedException ("This request is not supported by the protocol version implemented by the debuggee.");
2170                                                 }
2171                                         } else if (mod is AssemblyModifier) {
2172                                                 w.WriteByte ((byte)ModifierKind.ASSEMBLY_ONLY);
2173                                                 var amod = (mod as AssemblyModifier);
2174                                                 w.WriteInt (amod.Assemblies.Length);
2175                                                 foreach (var id in amod.Assemblies)
2176                                                         w.WriteId (id);
2177                                         } else if (mod is SourceFileModifier) {
2178                                                 w.WriteByte ((byte)ModifierKind.SOURCE_FILE_ONLY);
2179                                                 var smod = (mod as SourceFileModifier);
2180                                                 w.WriteInt (smod.SourceFiles.Length);
2181                                                 foreach (var s in smod.SourceFiles)
2182                                                         w.WriteString (s);
2183                                         } else if (mod is TypeNameModifier) {
2184                                                 w.WriteByte ((byte)ModifierKind.TYPE_NAME_ONLY);
2185                                                 var tmod = (mod as TypeNameModifier);
2186                                                 w.WriteInt (tmod.TypeNames.Length);
2187                                                 foreach (var s in tmod.TypeNames)
2188                                                         w.WriteString (s);
2189                                         } else {
2190                                                 throw new NotImplementedException ();
2191                                         }
2192                                 }
2193                         } else {
2194                                 w.WriteByte (0);
2195                         }
2196                         return SendReceive (CommandSet.EVENT_REQUEST, (int)CmdEventRequest.SET, w).ReadInt ();
2197                 }
2198
2199                 internal void ClearEventRequest (EventType etype, int req_id) {
2200                         SendReceive (CommandSet.EVENT_REQUEST, (int)CmdEventRequest.CLEAR, new PacketWriter ().WriteByte ((byte)etype).WriteInt (req_id));
2201                 }                       
2202
2203                 internal void ClearAllBreakpoints () {
2204                         SendReceive (CommandSet.EVENT_REQUEST, (int)CmdEventRequest.CLEAR_ALL_BREAKPOINTS, new PacketWriter ());
2205                 }
2206                         
2207                 /*
2208                  * STACK FRAME
2209                  */
2210                 internal ValueImpl StackFrame_GetThis (long thread_id, long id) {
2211                         PacketReader r = SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.GET_THIS, new PacketWriter ().WriteId (thread_id).WriteId (id));
2212                         return r.ReadValue ();
2213                 }
2214
2215                 internal ValueImpl[] StackFrame_GetValues (long thread_id, long id, int[] pos) {
2216                         /* pos < 0 -> argument at pos (-pos) - 1 */
2217                         /* pos >= 0 -> local at pos */
2218                         int len = pos.Length;
2219                         PacketReader r = SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.GET_VALUES, new PacketWriter ().WriteId (thread_id).WriteId (id).WriteInt (len).WriteInts (pos));
2220
2221                         ValueImpl[] res = new ValueImpl [len];
2222                         for (int i = 0; i < len; ++i)
2223                                 res [i] = r.ReadValue ();
2224                         return res;
2225                 }
2226
2227                 internal void StackFrame_SetValues (long thread_id, long id, int[] pos, ValueImpl[] values) {
2228                         /* pos < 0 -> argument at pos (-pos) - 1 */
2229                         /* pos >= 0 -> local at pos */
2230                         int len = pos.Length;
2231                         SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.SET_VALUES, new PacketWriter ().WriteId (thread_id).WriteId (id).WriteInt (len).WriteInts (pos).WriteValues (values));
2232                 }
2233
2234                 /*
2235                  * ARRAYS
2236                  */
2237                 internal int[] Array_GetLength (long id, out int rank, out int[] lower_bounds) {
2238                         var r = SendReceive (CommandSet.ARRAY_REF, (int)CmdArrayRef.GET_LENGTH, new PacketWriter ().WriteId (id));
2239                         rank = r.ReadInt ();
2240                         int[] res = new int [rank];
2241                         lower_bounds = new int [rank];
2242                         for (int i = 0; i < rank; ++i) {
2243                                 res [i] = r.ReadInt ();
2244                                 lower_bounds [i] = r.ReadInt ();
2245                         }
2246                         return res;
2247                 }
2248
2249                 internal ValueImpl[] Array_GetValues (long id, int index, int len) {
2250                         var r = SendReceive (CommandSet.ARRAY_REF, (int)CmdArrayRef.GET_VALUES, new PacketWriter ().WriteId (id).WriteInt (index).WriteInt (len));
2251                         ValueImpl[] res = new ValueImpl [len];
2252                         for (int i = 0; i < len; ++i)
2253                                 res [i] = r.ReadValue ();
2254                         return res;
2255                 }
2256
2257                 internal void Array_SetValues (long id, int index, ValueImpl[] values) {
2258                         SendReceive (CommandSet.ARRAY_REF, (int)CmdArrayRef.SET_VALUES, new PacketWriter ().WriteId (id).WriteInt (index).WriteInt (values.Length).WriteValues (values));
2259                 }
2260
2261                 /*
2262                  * STRINGS
2263                  */
2264                 internal string String_GetValue (long id) {
2265                         return SendReceive (CommandSet.STRING_REF, (int)CmdStringRef.GET_VALUE, new PacketWriter ().WriteId (id)).ReadString ();
2266                 }                       
2267
2268                 internal int String_GetLength (long id) {
2269                         return (int)SendReceive (CommandSet.STRING_REF, (int)CmdStringRef.GET_LENGTH, new PacketWriter ().WriteId (id)).ReadLong ();
2270                 }                       
2271
2272                 internal char[] String_GetChars (long id, int index, int length) {
2273                         var r = SendReceive (CommandSet.STRING_REF, (int)CmdStringRef.GET_CHARS, new PacketWriter ().WriteId (id).WriteLong (index).WriteLong (length));
2274                         var res = new char [length];
2275                         for (int i = 0; i < length; ++i)
2276                                 res [i] = (char)r.ReadShort ();
2277                         return res;
2278                 }                       
2279
2280                 /*
2281                  * OBJECTS
2282                  */
2283                 internal long Object_GetType (long id) {
2284                         return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_TYPE, new PacketWriter ().WriteId (id)).ReadId ();
2285                 }                       
2286
2287                 internal long Object_GetDomain (long id) {
2288                         return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_DOMAIN, new PacketWriter ().WriteId (id)).ReadId ();
2289                 }                       
2290
2291                 internal ValueImpl[] Object_GetValues (long id, long[] fields) {
2292                         int len = fields.Length;
2293                         PacketReader r = SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_VALUES, new PacketWriter ().WriteId (id).WriteInt (len).WriteIds (fields));
2294
2295                         ValueImpl[] res = new ValueImpl [len];
2296                         for (int i = 0; i < len; ++i)
2297                                 res [i] = r.ReadValue ();
2298                         return res;
2299                 }
2300
2301                 internal void Object_SetValues (long id, long[] fields, ValueImpl[] values) {
2302                         SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.SET_VALUES, new PacketWriter ().WriteId (id).WriteInt (fields.Length).WriteIds (fields).WriteValues (values));
2303                 }
2304
2305                 internal bool Object_IsCollected (long id) {
2306                         return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.IS_COLLECTED, new PacketWriter ().WriteId (id)).ReadInt () == 1;
2307                 }                       
2308
2309                 internal long Object_GetAddress (long id) {
2310                         return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_ADDRESS, new PacketWriter ().WriteId (id)).ReadLong ();
2311                 }                       
2312
2313                 internal ObjectRefInfo Object_GetInfo (long id) {
2314                         ObjectRefInfo res = new ObjectRefInfo ();
2315                         PacketReader r = SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_INFO, new PacketWriter ().WriteId (id));
2316
2317                         res.type_id = r.ReadId ();
2318                         res.domain_id = r.ReadId ();
2319                         return res;
2320                 }
2321
2322                 public void ForceDisconnect ()
2323                 {
2324                         TransportClose ();
2325                 }
2326         }
2327         
2328         class TcpConnection : Connection
2329         {
2330                 Socket socket;
2331                 
2332                 internal TcpConnection (Socket socket)
2333                 {
2334                         this.socket = socket;
2335                         //socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.NoDelay, 1);
2336                 }
2337                 
2338                 internal EndPoint EndPoint {
2339                         get {
2340                                 return socket.RemoteEndPoint;
2341                         }
2342                 }
2343                 
2344                 protected override int TransportSend (byte[] buf, int buf_offset, int len)
2345                 {
2346                         return socket.Send (buf, buf_offset, len, SocketFlags.None);
2347                 }
2348                 
2349                 protected override int TransportReceive (byte[] buf, int buf_offset, int len)
2350                 {
2351                         return socket.Receive (buf, buf_offset, len, SocketFlags.None);
2352                 }
2353                 
2354                 protected override void TransportSetTimeouts (int send_timeout, int receive_timeout)
2355                 {
2356                         socket.SendTimeout = send_timeout;
2357                         socket.ReceiveTimeout = receive_timeout;
2358                 }
2359                 
2360                 protected override void TransportClose ()
2361                 {
2362                         socket.Close ();
2363                 }
2364         }
2365
2366         /* This is the interface exposed by the debugger towards the debugger agent */
2367         interface IEventHandler
2368         {
2369                 void Events (SuspendPolicy suspend_policy, EventInfo[] events);
2370
2371                 void VMDisconnect (int req_id, long thread_id, string vm_uri);
2372         }
2373 }