Merge pull request #409 from Alkarex/patch-1
[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 = 22;
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                 }
546
547                 enum BindingFlagsExtensions {
548                         BINDING_FLAGS_IGNORE_CASE = 0x70000000,
549                 }
550
551                 enum CmdStackFrame {
552                         GET_VALUES = 1,
553                         GET_THIS = 2,
554                         SET_VALUES = 3
555                 }
556
557                 enum CmdArrayRef {
558                         GET_LENGTH = 1,
559                         GET_VALUES = 2,
560                         SET_VALUES = 3
561                 }
562
563                 enum CmdStringRef {
564                         GET_VALUE = 1,
565                         GET_LENGTH = 2,
566                         GET_CHARS = 3
567                 }
568
569                 enum CmdObjectRef {
570                         GET_TYPE = 1,
571                         GET_VALUES = 2,
572                         IS_COLLECTED = 3,
573                         GET_ADDRESS = 4,
574                         GET_DOMAIN = 5,
575                         SET_VALUES = 6,
576                         GET_INFO = 7,
577                 }
578
579                 class Header {
580                         public int id;
581                         public int command_set;
582                         public int command;
583                         public int flags;
584                 }                       
585
586                 internal static int GetPacketLength (byte[] header) {
587                         int offset = 0;
588                         return decode_int (header, ref offset);
589                 }
590
591                 internal static bool IsReplyPacket (byte[] packet) {
592                         int offset = 8;
593                         return decode_byte (packet, ref offset) == 0x80;
594                 }
595
596                 internal static int GetPacketId (byte[] packet) {
597                         int offset = 4;
598                         return decode_int (packet, ref offset);
599                 }
600
601                 static int decode_byte (byte[] packet, ref int offset) {
602                         return packet [offset++];
603                 }
604
605                 static int decode_short (byte[] packet, ref int offset) {
606                         int res = ((int)packet [offset] << 8) | (int)packet [offset + 1];
607                         offset += 2;
608                         return res;
609                 }
610
611                 static int decode_int (byte[] packet, ref int offset) {
612                         int res = ((int)packet [offset] << 24) | ((int)packet [offset + 1] << 16) | ((int)packet [offset + 2] << 8) | (int)packet [offset + 3];
613                         offset += 4;
614                         return res;
615                 }
616
617                 static long decode_id (byte[] packet, ref int offset) {
618                         return decode_int (packet, ref offset);
619                 }
620
621                 static long decode_long (byte[] packet, ref int offset) {
622                         uint high = (uint)decode_int (packet, ref offset);
623                         uint low = (uint)decode_int (packet, ref offset);
624
625                         return (long)(((ulong)high << 32) | (ulong)low);
626                 }
627
628                 internal static SuspendPolicy decode_suspend_policy (int suspend_policy) {
629                         switch ((WPSuspendPolicy)suspend_policy) {
630                         case WPSuspendPolicy.NONE:
631                                 return SuspendPolicy.None;
632                         case WPSuspendPolicy.EVENT_THREAD:
633                                 return SuspendPolicy.EventThread;
634                         case WPSuspendPolicy.ALL:
635                                 return SuspendPolicy.All;
636                         default:
637                                 throw new NotImplementedException ();
638                         }
639                 }
640
641                 static Header decode_command_header (byte[] packet) {
642                         int offset = 0;
643                         Header res = new Header ();
644
645                         decode_int (packet, ref offset);
646                         res.id = decode_int (packet, ref offset);
647                         res.flags = decode_byte (packet, ref offset);
648                         res.command_set = decode_byte (packet, ref offset);
649                         res.command = decode_byte (packet, ref offset);
650
651                         return res;
652                 }
653
654                 static void encode_byte (byte[] buf, int b, ref int offset) {
655                         buf [offset] = (byte)b;
656                         offset ++;
657                 }
658
659                 static void encode_int (byte[] buf, int i, ref int offset) {
660                         buf [offset] = (byte)((i >> 24) & 0xff);
661                         buf [offset + 1] = (byte)((i >> 16) & 0xff);
662                         buf [offset + 2] = (byte)((i >> 8) & 0xff);
663                         buf [offset + 3] = (byte)((i >> 0) & 0xff);
664                         offset += 4;
665                 }
666
667                 static void encode_id (byte[] buf, long id, ref int offset) {
668                         encode_int (buf, (int)id, ref offset);
669                 }
670
671                 static void encode_long (byte[] buf, long l, ref int offset) {
672                         encode_int (buf, (int)((l >> 32) & 0xffffffff), ref offset);
673                         encode_int (buf, (int)(l & 0xffffffff), ref offset);
674                 }
675
676                 internal static byte[] EncodePacket (int id, int commandSet, int command, byte[] data, int dataLen) {
677                         byte[] buf = new byte [dataLen + 11];
678                         int offset = 0;
679                         
680                         encode_int (buf, buf.Length, ref offset);
681                         encode_int (buf, id, ref offset);
682                         encode_byte (buf, 0, ref offset);
683                         encode_byte (buf, commandSet, ref offset);
684                         encode_byte (buf, command, ref offset);
685
686                         for (int i = 0; i < dataLen; ++i)
687                                 buf [offset + i] = data [i];
688
689                         return buf;
690                 }
691
692                 class PacketReader {
693                         byte[] packet;
694                         int offset;
695
696                         public PacketReader (byte[] packet) {
697                                 this.packet = packet;
698
699                                 // For event packets
700                                 Header header = decode_command_header (packet);
701                                 CommandSet = (CommandSet)header.command_set;
702                                 Command = header.command;
703
704                                 // For reply packets
705                                 offset = 0;
706                                 ReadInt (); // length
707                                 ReadInt (); // id
708                                 ReadByte (); // flags
709                                 ErrorCode = ReadShort ();
710                         }
711
712                         public CommandSet CommandSet {
713                                 get; set;
714                         }
715
716                         public int Command {
717                                 get; set;
718                         }
719
720                         public int ErrorCode {
721                                 get; set;
722                         }
723
724                         public int Offset {
725                                 get {
726                                         return offset;
727                                 }
728                         }
729
730                         public int ReadByte () {
731                                 return decode_byte (packet, ref offset);
732                         }
733
734                         public int ReadShort () {
735                                 return decode_short (packet, ref offset);
736                         }
737
738                         public int ReadInt () {
739                                 return decode_int (packet, ref offset);
740                         }
741
742                         public long ReadId () {
743                                 return decode_id (packet, ref offset);
744                         }
745
746                         public long ReadLong () {
747                                 return decode_long (packet, ref offset);
748                         }
749
750                         public float ReadFloat () {
751                                 float f = DataConverter.FloatFromBE (packet, offset);
752                                 offset += 4;
753                                 return f;
754                         }
755
756                         public double ReadDouble () {
757                                 double d = DataConverter.DoubleFromBE (packet, offset);
758                                 offset += 8;
759                                 return d;
760                         }
761
762                         public string ReadString () {
763                                 int len = decode_int (packet, ref offset);
764                                 string res = new String (Encoding.UTF8.GetChars (packet, offset, len));
765                                 offset += len;
766                                 return res;
767                         }
768
769                         public ValueImpl ReadValue () {
770                                 ElementType etype = (ElementType)ReadByte ();
771
772                                 switch (etype) {
773                                 case ElementType.Void:
774                                         return new ValueImpl { Type = etype };
775                                 case ElementType.I1:
776                                         return new ValueImpl { Type = etype, Value = (sbyte)ReadInt () };
777                                 case ElementType.U1:
778                                         return new ValueImpl { Type = etype, Value = (byte)ReadInt () };
779                                 case ElementType.Boolean:
780                                         return new ValueImpl { Type = etype, Value = ReadInt () != 0 };
781                                 case ElementType.I2:
782                                         return new ValueImpl { Type = etype, Value = (short)ReadInt () };
783                                 case ElementType.U2:
784                                         return new ValueImpl { Type = etype, Value = (ushort)ReadInt () };
785                                 case ElementType.Char:
786                                         return new ValueImpl { Type = etype, Value = (char)ReadInt () };
787                                 case ElementType.I4:
788                                         return new ValueImpl { Type = etype, Value = ReadInt () };
789                                 case ElementType.U4:
790                                         return new ValueImpl { Type = etype, Value = (uint)ReadInt () };
791                                 case ElementType.I8:
792                                         return new ValueImpl { Type = etype, Value = ReadLong () };
793                                 case ElementType.U8:
794                                         return new ValueImpl { Type = etype, Value = (ulong)ReadLong () };
795                                 case ElementType.R4:
796                                         return new ValueImpl { Type = etype, Value = ReadFloat () };
797                                 case ElementType.R8:
798                                         return new ValueImpl { Type = etype, Value = ReadDouble () };
799                                 case ElementType.I:
800                                 case ElementType.U:
801                                 case ElementType.Ptr:
802                                         // FIXME: The client and the debuggee might have different word sizes
803                                         return new ValueImpl { Type = etype, Value = ReadLong () };
804                                 case ElementType.String:
805                                 case ElementType.SzArray:
806                                 case ElementType.Class:
807                                 case ElementType.Array:
808                                 case ElementType.Object:
809                                         long objid = ReadId ();
810                                         return new ValueImpl () { Type = etype, Objid = objid };
811                                 case ElementType.ValueType:
812                                         bool is_enum = ReadByte () == 1;
813                                         long klass = ReadId ();
814                                         long nfields = ReadInt ();
815                                         ValueImpl[] fields = new ValueImpl [nfields];
816                                         for (int i = 0; i < nfields; ++i)
817                                                 fields [i] = ReadValue ();
818                                         return new ValueImpl () { Type = etype, Klass = klass, Fields = fields, IsEnum = is_enum };
819                                 case (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL:
820                                         return new ValueImpl { Type = etype };
821                                 case (ElementType)ValueTypeId.VALUE_TYPE_ID_TYPE:
822                                         return new ValueImpl () { Type = etype, Id = ReadId () };
823                                 default:
824                                         throw new NotImplementedException ("Unable to handle type " + etype);
825                                 }
826                         }
827
828                         public long[] ReadIds (int n) {
829                                 long[] res = new long [n];
830                                 for (int i = 0; i < n; ++i)
831                                         res [i] = ReadId ();
832                                 return res;
833                         }
834                 }
835
836                 class PacketWriter {
837
838                         byte[] data;
839                         int offset;
840
841                         public PacketWriter () {
842                                 data = new byte [1024];
843                                 offset = 0;
844                         }
845
846                         void MakeRoom (int size) {
847                                 if (offset + size >= data.Length) {
848                                         int new_len = data.Length * 2;
849                                         while (new_len < offset + size) {
850                                                 new_len *= 2;
851                                         }
852                                         byte[] new_data = new byte [new_len];
853                                         Array.Copy (data, new_data, data.Length);
854                                         data = new_data;
855                                 }
856                         }
857
858                         public PacketWriter WriteByte (byte val) {
859                                 MakeRoom (1);
860                                 encode_byte (data, val, ref offset);
861                                 return this;
862                         }
863
864                         public PacketWriter WriteInt (int val) {
865                                 MakeRoom (4);
866                                 encode_int (data, val, ref offset);
867                                 return this;
868                         }
869
870                         public PacketWriter WriteId (long id) {
871                                 MakeRoom (8);
872                                 encode_id (data, id, ref offset);
873                                 return this;
874                         }
875
876                         public PacketWriter WriteLong (long val) {
877                                 MakeRoom (8);
878                                 encode_long (data, val, ref offset);
879                                 return this;
880                         }
881
882                         public PacketWriter WriteFloat (float f) {
883                                 MakeRoom (8);
884                                 byte[] b = DataConverter.GetBytesBE (f);
885                                 for (int i = 0; i < 4; ++i)
886                                         data [offset + i] = b [i];
887                                 offset += 4;
888                                 return this;
889                         }
890
891                         public PacketWriter WriteDouble (double d) {
892                                 MakeRoom (8);
893                                 byte[] b = DataConverter.GetBytesBE (d);
894                                 for (int i = 0; i < 8; ++i)
895                                         data [offset + i] = b [i];
896                                 offset += 8;
897                                 return this;
898                         }
899
900                         public PacketWriter WriteInts (int[] ids) {
901                                 for (int i = 0; i < ids.Length; ++i)
902                                         WriteInt (ids [i]);
903                                 return this;
904                         }
905
906                         public PacketWriter WriteIds (long[] ids) {
907                                 for (int i = 0; i < ids.Length; ++i)
908                                         WriteId (ids [i]);
909                                 return this;
910                         }
911
912                         public PacketWriter WriteString (string s) {
913                                 if (s == null)
914                                         return WriteInt (-1);
915
916                                 byte[] b = Encoding.UTF8.GetBytes (s);
917                                 MakeRoom (4);
918                                 encode_int (data, b.Length, ref offset);
919                                 MakeRoom (b.Length);
920                                 Buffer.BlockCopy (b, 0, data, offset, b.Length);
921                                 offset += b.Length;
922                                 return this;
923                         }
924
925                         public PacketWriter WriteBool (bool val) {
926                                 WriteByte (val ? (byte)1 : (byte)0);
927                                 return this;
928                         }
929
930                         public PacketWriter WriteValue (ValueImpl v) {
931                                 ElementType t;
932
933                                 if (v.Value != null)
934                                         t = TypeCodeToElementType (Type.GetTypeCode (v.Value.GetType ()));
935                                 else
936                                         t = v.Type;
937                                 WriteByte ((byte)t);
938                                 switch (t) {
939                                 case ElementType.Boolean:
940                                         WriteInt ((bool)v.Value ? 1 : 0);
941                                         break;
942                                 case ElementType.Char:
943                                         WriteInt ((int)(char)v.Value);
944                                         break;
945                                 case ElementType.I1:
946                                         WriteInt ((int)(sbyte)v.Value);
947                                         break;
948                                 case ElementType.U1:
949                                         WriteInt ((int)(byte)v.Value);
950                                         break;
951                                 case ElementType.I2:
952                                         WriteInt ((int)(short)v.Value);
953                                         break;
954                                 case ElementType.U2:
955                                         WriteInt ((int)(ushort)v.Value);
956                                         break;
957                                 case ElementType.I4:
958                                         WriteInt ((int)(int)v.Value);
959                                         break;
960                                 case ElementType.U4:
961                                         WriteInt ((int)(uint)v.Value);
962                                         break;
963                                 case ElementType.I8:
964                                         WriteLong ((long)(long)v.Value);
965                                         break;
966                                 case ElementType.U8:
967                                         WriteLong ((long)(ulong)v.Value);
968                                         break;
969                                 case ElementType.R4:
970                                         WriteFloat ((float)v.Value);
971                                         break;
972                                 case ElementType.R8:
973                                         WriteDouble ((double)v.Value);
974                                         break;
975                                 case ElementType.String:
976                                 case ElementType.SzArray:
977                                 case ElementType.Class:
978                                 case ElementType.Array:
979                                 case ElementType.Object:
980                                         WriteId (v.Objid);
981                                         break;
982                                 case ElementType.ValueType:
983                                         // FIXME: 
984                                         if (v.IsEnum)
985                                                 throw new NotImplementedException ();
986                                         WriteByte (0);
987                                         WriteId (v.Klass);
988                                         WriteInt (v.Fields.Length);
989                                         for (int i = 0; i < v.Fields.Length; ++i)
990                                                 WriteValue (v.Fields [i]);
991                                         break;
992                                 case (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL:
993                                         break;
994                                 default:
995                                         throw new NotImplementedException ();
996                                 }
997
998                                 return this;
999                         }
1000
1001                         public PacketWriter WriteValues (ValueImpl[] values) {
1002                                 for (int i = 0; i < values.Length; ++i)
1003                                         WriteValue (values [i]);
1004                                 return this;
1005                         }
1006
1007                         public byte[] Data {
1008                                 get {
1009                                         return data;
1010                                 }
1011                         }
1012
1013                         public int Offset {
1014                                 get {
1015                                         return offset;
1016                                 }
1017                         }
1018                 }
1019
1020                 delegate void ReplyCallback (int packet_id, byte[] packet);
1021
1022                 bool closed;
1023                 Thread receiver_thread;
1024                 Dictionary<int, byte[]> reply_packets;
1025                 Dictionary<int, ReplyCallback> reply_cbs;
1026                 Dictionary<int, int> reply_cb_counts;
1027                 object reply_packets_monitor;
1028
1029                 internal event EventHandler<ErrorHandlerEventArgs> ErrorHandler;
1030
1031                 protected Connection () {
1032                         closed = false;
1033                         reply_packets = new Dictionary<int, byte[]> ();
1034                         reply_cbs = new Dictionary<int, ReplyCallback> ();
1035                         reply_cb_counts = new Dictionary<int, int> ();
1036                         reply_packets_monitor = new Object ();
1037                 }
1038                 
1039                 protected abstract int TransportReceive (byte[] buf, int buf_offset, int len);
1040                 protected abstract int TransportSend (byte[] buf, int buf_offset, int len);
1041                 protected abstract void TransportSetTimeouts (int send_timeout, int receive_timeout);
1042                 protected abstract void TransportClose ();
1043
1044                 internal VersionInfo Version;
1045                 
1046                 int Receive (byte[] buf, int buf_offset, int len) {
1047                         int offset = 0;
1048
1049                         while (offset < len) {
1050                                 int n = TransportReceive (buf, buf_offset + offset, len - offset);
1051
1052                                 if (n == 0)
1053                                         return offset;
1054                                 offset += n;
1055                         }
1056
1057                         return offset;
1058                 }
1059                 
1060                 // Do the wire protocol handshake
1061                 internal void Connect () {
1062                         byte[] buf = new byte [HANDSHAKE_STRING.Length];
1063                         char[] cbuf = new char [buf.Length];
1064
1065                         // FIXME: Add a timeout
1066                         int n = Receive (buf, 0, buf.Length);
1067                         if (n == 0)
1068                                 throw new IOException ("DWP Handshake failed.");
1069                         for (int i = 0; i < buf.Length; ++i)
1070                                 cbuf [i] = (char)buf [i];
1071
1072                         if (new String (cbuf) != HANDSHAKE_STRING)
1073                                 throw new IOException ("DWP Handshake failed.");
1074                         
1075                         TransportSend (buf, 0, buf.Length);
1076
1077                         receiver_thread = new Thread (new ThreadStart (receiver_thread_main));
1078                         receiver_thread.Start ();
1079
1080                         Version = VM_GetVersion ();
1081
1082                         //
1083                         // Tell the debuggee our protocol version, so newer debuggees can work
1084                         // with older clients
1085                         //
1086
1087                         //
1088                         // Older debuggees might not support this request
1089                         EventHandler<ErrorHandlerEventArgs> OrigErrorHandler = ErrorHandler;
1090                         ErrorHandler = null;
1091                         ErrorHandler += delegate (object sender, ErrorHandlerEventArgs args) {
1092                                 throw new NotSupportedException ();
1093                         };
1094                         try {
1095                                 VM_SetProtocolVersion (MAJOR_VERSION, MINOR_VERSION);
1096                         } catch (NotSupportedException) {
1097                         }
1098                         ErrorHandler = OrigErrorHandler;
1099                 }
1100
1101                 internal byte[] ReadPacket () {
1102                         // FIXME: Throw ClosedConnectionException () if the connection is closed
1103                         // FIXME: Throw ClosedConnectionException () if another thread closes the connection
1104                         // FIXME: Locking
1105                         byte[] header = new byte [HEADER_LENGTH];
1106
1107                         int len = Receive (header, 0, header.Length);
1108                         if (len == 0)
1109                                 return new byte [0];
1110                         if (len != HEADER_LENGTH) {
1111                                 // FIXME:
1112                                 throw new IOException ("Packet of length " + len + " is read.");
1113                         }
1114
1115                         int packetLength = GetPacketLength (header);
1116                         if (packetLength < 11)
1117                                 throw new IOException ("Invalid packet length.");
1118
1119                         if (packetLength == 11) {
1120                                 return header;
1121                         } else {
1122                                 byte[] buf = new byte [packetLength];
1123                                 for (int i = 0; i < header.Length; ++i)
1124                                         buf [i] = header [i];
1125                                 len = Receive (buf, header.Length, packetLength - header.Length);
1126                                 if (len != packetLength - header.Length)
1127                                         throw new IOException ();
1128                                 return buf;
1129                         }
1130                 }
1131
1132                 internal void WritePacket (byte[] packet) {
1133                         // FIXME: Throw ClosedConnectionException () if the connection is closed
1134                         // FIXME: Throw ClosedConnectionException () if another thread closes the connection
1135                         // FIXME: Locking
1136                         TransportSend (packet, 0, packet.Length);
1137                 }
1138
1139                 internal void Close () {
1140                         closed = true;
1141                 }
1142
1143                 internal bool IsClosed {
1144                         get {
1145                                 return closed;
1146                         }
1147                 }
1148
1149                 bool disconnected;
1150
1151                 void receiver_thread_main () {
1152                         while (!closed) {
1153                                 try {
1154                                         bool res = ReceivePacket ();
1155                                         if (!res)
1156                                                 break;
1157                                 } catch (Exception ex) {
1158                                         if (!closed) {
1159                                                 Console.WriteLine (ex);
1160                                         }
1161                                         break;
1162                                 }
1163                         }
1164
1165                         lock (reply_packets_monitor) {
1166                                 disconnected = true;
1167                                 Monitor.PulseAll (reply_packets_monitor);
1168                                 TransportClose ();
1169                         }
1170                         EventHandler.VMDisconnect (0, 0, null);
1171                 }
1172
1173                 bool ReceivePacket () {
1174                                 byte[] packet = ReadPacket ();
1175
1176                                 if (packet.Length == 0) {
1177                                         return false;
1178                                 }
1179
1180                                 if (IsReplyPacket (packet)) {
1181                                         int id = GetPacketId (packet);
1182                                         ReplyCallback cb = null;
1183                                         lock (reply_packets_monitor) {
1184                                                 reply_cbs.TryGetValue (id, out cb);
1185                                                 if (cb == null) {
1186                                                         reply_packets [id] = packet;
1187                                                         Monitor.PulseAll (reply_packets_monitor);
1188                                                 } else {
1189                                                         int c = reply_cb_counts [id];
1190                                                         c --;
1191                                                         if (c == 0) {
1192                                                                 reply_cbs.Remove (id);
1193                                                                 reply_cb_counts.Remove (id);
1194                                                         }
1195                                                 }
1196                                         }
1197
1198                                         if (cb != null)
1199                                                 cb.Invoke (id, packet);
1200                                 } else {
1201                                         PacketReader r = new PacketReader (packet);
1202
1203                                         if (r.CommandSet == CommandSet.EVENT && r.Command == (int)CmdEvent.COMPOSITE) {
1204                                                 int spolicy = r.ReadByte ();
1205                                                 int nevents = r.ReadInt ();
1206
1207                                                 SuspendPolicy suspend_policy = decode_suspend_policy (spolicy);
1208
1209                                                 EventInfo[] events = new EventInfo [nevents];
1210
1211                                                 for (int i = 0; i < nevents; ++i) {
1212                                                         EventKind kind = (EventKind)r.ReadByte ();
1213                                                         int req_id = r.ReadInt ();
1214
1215                                                         EventType etype = (EventType)kind;
1216
1217                                                         if (kind == EventKind.VM_START) {
1218                                                                 long thread_id = r.ReadId ();
1219                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id };
1220                                                                 //EventHandler.VMStart (req_id, thread_id, null);
1221                                                         } else if (kind == EventKind.VM_DEATH) {
1222                                                                 //EventHandler.VMDeath (req_id, 0, null);
1223                                                                 events [i] = new EventInfo (etype, req_id) { };
1224                                                         } else if (kind == EventKind.THREAD_START) {
1225                                                                 long thread_id = r.ReadId ();
1226                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = thread_id };
1227                                                                 //EventHandler.ThreadStart (req_id, thread_id, thread_id);
1228                                                         } else if (kind == EventKind.THREAD_DEATH) {
1229                                                                 long thread_id = r.ReadId ();
1230                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = thread_id };
1231                                                                 //EventHandler.ThreadDeath (req_id, thread_id, thread_id);
1232                                                         } else if (kind == EventKind.ASSEMBLY_LOAD) {
1233                                                                 long thread_id = r.ReadId ();
1234                                                                 long id = r.ReadId ();
1235                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1236                                                                 //EventHandler.AssemblyLoad (req_id, thread_id, id);
1237                                                         } else if (kind == EventKind.ASSEMBLY_UNLOAD) {
1238                                                                 long thread_id = r.ReadId ();
1239                                                                 long id = r.ReadId ();
1240                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1241                                                                 //EventHandler.AssemblyUnload (req_id, thread_id, id);
1242                                                         } else if (kind == EventKind.TYPE_LOAD) {
1243                                                                 long thread_id = r.ReadId ();
1244                                                                 long id = r.ReadId ();
1245                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1246                                                                 //EventHandler.TypeLoad (req_id, thread_id, id);
1247                                                         } else if (kind == EventKind.METHOD_ENTRY) {
1248                                                                 long thread_id = r.ReadId ();
1249                                                                 long id = r.ReadId ();
1250                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1251                                                                 //EventHandler.MethodEntry (req_id, thread_id, id);
1252                                                         } else if (kind == EventKind.METHOD_EXIT) {
1253                                                                 long thread_id = r.ReadId ();
1254                                                                 long id = r.ReadId ();
1255                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1256                                                                 //EventHandler.MethodExit (req_id, thread_id, id);
1257                                                         } else if (kind == EventKind.BREAKPOINT) {
1258                                                                 long thread_id = r.ReadId ();
1259                                                                 long id = r.ReadId ();
1260                                                                 long loc = r.ReadLong ();
1261                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
1262                                                                 //EventHandler.Breakpoint (req_id, thread_id, id, loc);
1263                                                         } else if (kind == EventKind.STEP) {
1264                                                                 long thread_id = r.ReadId ();
1265                                                                 long id = r.ReadId ();
1266                                                                 long loc = r.ReadLong ();
1267                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
1268                                                                 //EventHandler.Step (req_id, thread_id, id, loc);
1269                                                         } else if (kind == EventKind.EXCEPTION) {
1270                                                                 long thread_id = r.ReadId ();
1271                                                                 long id = r.ReadId ();
1272                                                                 long loc = 0; // FIXME
1273                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
1274                                                                 //EventHandler.Exception (req_id, thread_id, id, loc);
1275                                                         } else if (kind == EventKind.APPDOMAIN_CREATE) {
1276                                                                 long thread_id = r.ReadId ();
1277                                                                 long id = r.ReadId ();
1278                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1279                                                                 //EventHandler.AppDomainCreate (req_id, thread_id, id);
1280                                                         } else if (kind == EventKind.APPDOMAIN_UNLOAD) {
1281                                                                 long thread_id = r.ReadId ();
1282                                                                 long id = r.ReadId ();
1283                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
1284                                                                 //EventHandler.AppDomainUnload (req_id, thread_id, id);
1285                                                         } else if (kind == EventKind.USER_BREAK) {
1286                                                                 long thread_id = r.ReadId ();
1287                                                                 long id = 0;
1288                                                                 long loc = 0;
1289                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
1290                                                                 //EventHandler.Exception (req_id, thread_id, id, loc);
1291                                                         } else if (kind == EventKind.USER_LOG) {
1292                                                                 long thread_id = r.ReadId ();
1293                                                                 int level = r.ReadInt ();
1294                                                                 string category = r.ReadString ();
1295                                                                 string message = r.ReadString ();
1296                                                                 events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Level = level, Category = category, Message = message };
1297                                                                 //EventHandler.Exception (req_id, thread_id, id, loc);
1298                                                         } else if (kind == EventKind.KEEPALIVE) {
1299                                                                 events [i] = new EventInfo (etype, req_id) { };
1300                                                         } else {
1301                                                                 throw new NotImplementedException ("Unknown event kind: " + kind);
1302                                                         }
1303                                                 }
1304
1305                                                 EventHandler.Events (suspend_policy, events);
1306                                         }
1307                                 }
1308
1309                                 return true;
1310                 }
1311
1312                 internal IEventHandler EventHandler {
1313                         get; set;
1314                 }
1315
1316                 static String CommandString (CommandSet command_set, int command)
1317                 {
1318                         string cmd;
1319                         switch (command_set) {
1320                         case CommandSet.VM:
1321                                 cmd = ((CmdVM)command).ToString ();
1322                                 break;
1323                         case CommandSet.OBJECT_REF:
1324                                 cmd = ((CmdObjectRef)command).ToString ();
1325                                 break;
1326                         case CommandSet.STRING_REF:
1327                                 cmd = ((CmdStringRef)command).ToString ();
1328                                 break;
1329                         case CommandSet.THREAD:
1330                                 cmd = ((CmdThread)command).ToString ();
1331                                 break;
1332                         case CommandSet.ARRAY_REF:
1333                                 cmd = ((CmdArrayRef)command).ToString ();
1334                                 break;
1335                         case CommandSet.EVENT_REQUEST:
1336                                 cmd = ((CmdEventRequest)command).ToString ();
1337                                 break;
1338                         case CommandSet.STACK_FRAME:
1339                                 cmd = ((CmdStackFrame)command).ToString ();
1340                                 break;
1341                         case CommandSet.APPDOMAIN:
1342                                 cmd = ((CmdAppDomain)command).ToString ();
1343                                 break;
1344                         case CommandSet.ASSEMBLY:
1345                                 cmd = ((CmdAssembly)command).ToString ();
1346                                 break;
1347                         case CommandSet.METHOD:
1348                                 cmd = ((CmdMethod)command).ToString ();
1349                                 break;
1350                         case CommandSet.TYPE:
1351                                 cmd = ((CmdType)command).ToString ();
1352                                 break;
1353                         case CommandSet.MODULE:
1354                                 cmd = ((CmdModule)command).ToString ();
1355                                 break;
1356                         case CommandSet.EVENT:
1357                                 cmd = ((CmdEvent)command).ToString ();
1358                                 break;
1359                         default:
1360                                 cmd = command.ToString ();
1361                                 break;
1362                         }
1363                         return string.Format ("[{0} {1}]", command_set, cmd);
1364                 }
1365
1366                 long total_protocol_ticks;
1367
1368                 void LogPacket (int packet_id, byte[] encoded_packet, byte[] reply_packet, CommandSet command_set, int command, Stopwatch watch) {
1369                         watch.Stop ();
1370                         total_protocol_ticks += watch.ElapsedTicks;
1371                         var ts = TimeSpan.FromTicks (total_protocol_ticks);
1372                         string msg = string.Format ("Packet: {0} sent: {1} received: {2} ms: {3} total ms: {4} {5}",
1373                            packet_id, encoded_packet.Length, reply_packet.Length, watch.ElapsedMilliseconds,
1374                            (ts.Seconds * 1000) + ts.Milliseconds,
1375                            CommandString (command_set, command));
1376
1377                         LoggingStream.WriteLine (msg);
1378                         LoggingStream.Flush ();
1379                 }
1380
1381                 /* Send a request and call cb when a result is received */
1382                 int Send (CommandSet command_set, int command, PacketWriter packet, Action<PacketReader> cb, int count) {
1383                         int id = IdGenerator;
1384
1385                         Stopwatch watch = null;
1386                         if (EnableConnectionLogging)
1387                                 watch = Stopwatch.StartNew ();
1388
1389                         byte[] encoded_packet;
1390                         if (packet == null)
1391                                 encoded_packet = EncodePacket (id, (int)command_set, command, null, 0);
1392                         else
1393                                 encoded_packet = EncodePacket (id, (int)command_set, command, packet.Data, packet.Offset);
1394
1395                         lock (reply_packets_monitor) {
1396                                 reply_cbs [id] = delegate (int packet_id, byte[] p) {
1397                                         if (EnableConnectionLogging)
1398                                                 LogPacket (packet_id, encoded_packet, p, command_set, command, watch);
1399                                         /* Run the callback on a tp thread to avoid blocking the receive thread */
1400                                         PacketReader r = new PacketReader (p);
1401                                         cb.BeginInvoke (r, null, null);
1402                                 };
1403                                 reply_cb_counts [id] = count;
1404                         }
1405
1406                         WritePacket (encoded_packet);
1407
1408                         return id;
1409                 }
1410
1411                 PacketReader SendReceive (CommandSet command_set, int command, PacketWriter packet) {
1412                         int id = IdGenerator;
1413                         Stopwatch watch = null;
1414
1415                         if (disconnected)
1416                                 throw new VMDisconnectedException ();
1417
1418                         if (EnableConnectionLogging)
1419                                 watch = Stopwatch.StartNew ();
1420
1421                         byte[] encoded_packet;
1422
1423                         if (packet == null)
1424                                 encoded_packet = EncodePacket (id, (int)command_set, command, null, 0);
1425                         else
1426                                 encoded_packet = EncodePacket (id, (int)command_set, command, packet.Data, packet.Offset);
1427
1428                         WritePacket (encoded_packet);
1429
1430                         int packetId = id;
1431
1432                         /* Wait for the reply packet */
1433                         while (true) {
1434                                 lock (reply_packets_monitor) {
1435                                         if (reply_packets.ContainsKey (packetId)) {
1436                                                 byte[] reply = reply_packets [packetId];
1437                                                 reply_packets.Remove (packetId);
1438                                                 PacketReader r = new PacketReader (reply);
1439
1440                                                 if (EnableConnectionLogging)
1441                                                         LogPacket (packetId, encoded_packet, reply, command_set, command, watch);
1442                                                 if (r.ErrorCode != 0) {
1443                                                         if (ErrorHandler != null)
1444                                                                 ErrorHandler (this, new ErrorHandlerEventArgs () { ErrorCode = (ErrorCode)r.ErrorCode });
1445                                                         throw new NotImplementedException ("No error handler set.");
1446                                                 } else {
1447                                                         return r;
1448                                                 }
1449                                         } else {
1450                                                 if (disconnected)
1451                                                         throw new VMDisconnectedException ();
1452                                                 Monitor.Wait (reply_packets_monitor);
1453                                         }
1454                                 }
1455                         }
1456                 }
1457
1458                 PacketReader SendReceive (CommandSet command_set, int command) {
1459                         return SendReceive (command_set, command, null);
1460                 }
1461
1462                 int packet_id_generator;
1463
1464                 int IdGenerator {
1465                         get {
1466                                 return Interlocked.Increment (ref packet_id_generator);
1467                         }
1468                 }
1469
1470                 CattrInfo[] ReadCattrs (PacketReader r) {
1471                         CattrInfo[] res = new CattrInfo [r.ReadInt ()];
1472                         for (int i = 0; i < res.Length; ++i) {
1473                                 CattrInfo info = new CattrInfo ();
1474                                 info.ctor_id = r.ReadId ();
1475                                 info.ctor_args = new ValueImpl [r.ReadInt ()];
1476                                 for (int j = 0; j < info.ctor_args.Length; ++j) {
1477                                         info.ctor_args [j] = r.ReadValue ();
1478                                 }
1479                                 info.named_args = new CattrNamedArgInfo [r.ReadInt ()];
1480                                 for (int j = 0; j < info.named_args.Length; ++j) {
1481                                         CattrNamedArgInfo arg = new CattrNamedArgInfo ();
1482                                         int arg_type = r.ReadByte ();
1483                                         arg.is_property = arg_type == 0x54;
1484                                         arg.id = r.ReadId ();
1485                                         arg.value = r.ReadValue ();
1486                                         info.named_args [j] = arg;
1487                                 }
1488                                 res [i] = info;
1489                         }
1490                         return res;
1491                 }
1492
1493                 static ElementType TypeCodeToElementType (TypeCode c) {
1494                         switch (c) {
1495                         case TypeCode.Boolean:
1496                                 return ElementType.Boolean;
1497                         case TypeCode.Char:
1498                                 return ElementType.Char;
1499                         case TypeCode.SByte:
1500                                 return ElementType.I1;
1501                         case TypeCode.Byte:
1502                                 return ElementType.U1;
1503                         case TypeCode.Int16:
1504                                 return ElementType.I2;
1505                         case TypeCode.UInt16:
1506                                 return ElementType.U2;
1507                         case TypeCode.Int32:
1508                                 return ElementType.I4;
1509                         case TypeCode.UInt32:
1510                                 return ElementType.U4;
1511                         case TypeCode.Int64:
1512                                 return ElementType.I8;
1513                         case TypeCode.UInt64:
1514                                 return ElementType.U8;
1515                         case TypeCode.Single:
1516                                 return ElementType.R4;
1517                         case TypeCode.Double:
1518                                 return ElementType.R8;
1519                         default:
1520                                 throw new NotImplementedException ();
1521                         }
1522                 }
1523
1524                 /*
1525                  * Implementation of debugger commands
1526                  */
1527
1528                 internal VersionInfo VM_GetVersion () {
1529                         var res = SendReceive (CommandSet.VM, (int)CmdVM.VERSION, null);
1530                         VersionInfo info = new VersionInfo ();
1531                         info.VMVersion = res.ReadString ();
1532                         info.MajorVersion = res.ReadInt ();
1533                         info.MinorVersion = res.ReadInt ();
1534                         return info;
1535                 }
1536
1537                 internal void VM_SetProtocolVersion (int major, int minor) {
1538                         SendReceive (CommandSet.VM, (int)CmdVM.SET_PROTOCOL_VERSION, new PacketWriter ().WriteInt (major).WriteInt (minor));
1539                 }
1540
1541                 internal long[] VM_GetThreads () {
1542                         var res = SendReceive (CommandSet.VM, (int)CmdVM.ALL_THREADS, null);
1543                         int len = res.ReadInt ();
1544                         long[] arr = new long [len];
1545                         for (int i = 0; i < len; ++i)
1546                                 arr [i] = res.ReadId ();
1547                         return arr;
1548                 }
1549
1550                 internal void VM_Suspend () {
1551                         SendReceive (CommandSet.VM, (int)CmdVM.SUSPEND);
1552                 }
1553
1554                 internal void VM_Resume () {
1555                         SendReceive (CommandSet.VM, (int)CmdVM.RESUME);
1556                 }
1557
1558                 internal void VM_Exit (int exitCode) {
1559                         SendReceive (CommandSet.VM, (int)CmdVM.EXIT, new PacketWriter ().WriteInt (exitCode));
1560                 }
1561
1562                 internal void VM_Dispose () {
1563                         SendReceive (CommandSet.VM, (int)CmdVM.DISPOSE);
1564                 }
1565
1566                 internal ValueImpl VM_InvokeMethod (long thread, long method, ValueImpl this_arg, ValueImpl[] arguments, InvokeFlags flags, out ValueImpl exc) {
1567                         exc = null;
1568                         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));
1569                         if (r.ReadByte () == 0) {
1570                                 exc = r.ReadValue ();
1571                                 return null;
1572                         } else {
1573                                 return r.ReadValue ();
1574                         }
1575                 }
1576
1577                 internal delegate void InvokeMethodCallback (ValueImpl v, ValueImpl exc, ErrorCode error, object state);
1578
1579                 internal int VM_BeginInvokeMethod (long thread, long method, ValueImpl this_arg, ValueImpl[] arguments, InvokeFlags flags, InvokeMethodCallback callback, object state) {
1580                         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) {
1581                                         ValueImpl v, exc;
1582
1583                                         if (r.ErrorCode != 0) {
1584                                                 callback (null, null, (ErrorCode)r.ErrorCode, state);
1585                                         } else {
1586                                                 if (r.ReadByte () == 0) {
1587                                                         exc = r.ReadValue ();
1588                                                         v = null;
1589                                                 } else {
1590                                                         v = r.ReadValue ();
1591                                                         exc = null;
1592                                                 }
1593
1594                                                 callback (v, exc, 0, state);
1595                                         }
1596                                 }, 1);
1597                 }
1598
1599                 internal int VM_BeginInvokeMethods (long thread, long[] methods, ValueImpl this_arg, List<ValueImpl[]> arguments, InvokeFlags flags, InvokeMethodCallback callback, object state) {
1600                         // FIXME: Merge this with INVOKE_METHOD
1601                         var w = new PacketWriter ();
1602                         w.WriteId (thread);
1603                         w.WriteInt ((int)flags);
1604                         w.WriteInt (methods.Length);
1605                         for (int i = 0; i < methods.Length; ++i) {
1606                                 w.WriteId (methods [i]);
1607                                 w.WriteValue (this_arg);
1608                                 w.WriteInt (arguments [i].Length);
1609                                 w.WriteValues (arguments [i]);
1610                         }
1611                         return Send (CommandSet.VM, (int)CmdVM.INVOKE_METHODS, w, delegate (PacketReader r) {
1612                                         ValueImpl v, exc;
1613
1614                                         if (r.ErrorCode != 0) {
1615                                                 callback (null, null, (ErrorCode)r.ErrorCode, state);
1616                                         } else {
1617                                                 if (r.ReadByte () == 0) {
1618                                                         exc = r.ReadValue ();
1619                                                         v = null;
1620                                                 } else {
1621                                                         v = r.ReadValue ();
1622                                                         exc = null;
1623                                                 }
1624
1625                                                 callback (v, exc, 0, state);
1626                                         }
1627                                 }, methods.Length);
1628                 }
1629
1630                 internal void VM_AbortInvoke (long thread, int id)
1631                 {
1632                         SendReceive (CommandSet.VM, (int)CmdVM.ABORT_INVOKE, new PacketWriter ().WriteId (thread).WriteInt (id));
1633                 }
1634
1635                 internal void SetSocketTimeouts (int send_timeout, int receive_timeout, int keepalive_interval)
1636                 {
1637                         TransportSetTimeouts (send_timeout, receive_timeout);
1638                         SendReceive (CommandSet.VM, (int)CmdVM.SET_KEEPALIVE, new PacketWriter ().WriteId (keepalive_interval));
1639                 }
1640
1641                 internal long[] VM_GetTypesForSourceFile (string fname, bool ignoreCase) {
1642                         var res = SendReceive (CommandSet.VM, (int)CmdVM.GET_TYPES_FOR_SOURCE_FILE, new PacketWriter ().WriteString (fname).WriteBool (ignoreCase));
1643                         int count = res.ReadInt ();
1644                         long[] types = new long [count];
1645                         for (int i = 0; i < count; ++i)
1646                                 types [i] = res.ReadId ();
1647                         return types;
1648                 }
1649
1650                 internal long[] VM_GetTypes (string name, bool ignoreCase) {
1651                         var res = SendReceive (CommandSet.VM, (int)CmdVM.GET_TYPES, new PacketWriter ().WriteString (name).WriteBool (ignoreCase));
1652                         int count = res.ReadInt ();
1653                         long[] types = new long [count];
1654                         for (int i = 0; i < count; ++i)
1655                                 types [i] = res.ReadId ();
1656                         return types;
1657                 }
1658
1659                 /*
1660                  * DOMAIN
1661                  */
1662
1663                 internal long RootDomain {
1664                         get {
1665                                 return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_ROOT_DOMAIN, null).ReadId ();
1666                         }
1667                 }
1668
1669                 internal string Domain_GetName (long id) {
1670                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_FRIENDLY_NAME, new PacketWriter ().WriteId (id)).ReadString ();
1671                 }
1672
1673                 internal long[] Domain_GetAssemblies (long id) {
1674                         var res = SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_ASSEMBLIES, new PacketWriter ().WriteId (id));
1675                         int count = res.ReadInt ();
1676                         long[] assemblies = new long [count];
1677                         for (int i = 0; i < count; ++i)
1678                                 assemblies [i] = res.ReadId ();
1679                         return assemblies;
1680                 }
1681
1682                 internal long Domain_GetEntryAssembly (long id) {
1683                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_ENTRY_ASSEMBLY, new PacketWriter ().WriteId (id)).ReadId ();
1684                 }
1685
1686                 internal long Domain_GetCorlib (long id) {
1687                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_CORLIB, new PacketWriter ().WriteId (id)).ReadId ();
1688                 }
1689
1690                 internal long Domain_CreateString (long id, string s) {
1691                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.CREATE_STRING, new PacketWriter ().WriteId (id).WriteString (s)).ReadId ();
1692                 }
1693
1694                 internal long Domain_CreateBoxedValue (long id, long type_id, ValueImpl v) {
1695                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.CREATE_BOXED_VALUE, new PacketWriter ().WriteId (id).WriteId (type_id).WriteValue (v)).ReadId ();
1696                 }
1697
1698                 /*
1699                  * METHOD
1700                  */
1701
1702                 internal string Method_GetName (long id) {
1703                         return SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_NAME, new PacketWriter ().WriteId (id)).ReadString ();
1704                 }
1705
1706                 internal long Method_GetDeclaringType (long id) {
1707                         return SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_DECLARING_TYPE, new PacketWriter ().WriteId (id)).ReadId ();
1708                 }
1709
1710                 internal DebugInfo Method_GetDebugInfo (long id) {
1711                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_DEBUG_INFO, new PacketWriter ().WriteId (id));
1712
1713                         DebugInfo info = new DebugInfo ();
1714                         info.max_il_offset = res.ReadInt ();
1715
1716                         SourceInfo[] sources = null;
1717                         if (Version.AtLeast (2, 13)) {
1718                                 int n = res.ReadInt ();
1719                                 sources = new SourceInfo [n];
1720                                 for (int i = 0; i < n; ++i) {
1721                                         sources [i].source_file = res.ReadString ();
1722                                         if (Version.AtLeast (2, 14)) {
1723                                                 sources [i].hash = new byte [16];
1724                                                 for (int j = 0; j < 16; ++j)
1725                                                         sources [i].hash [j] = (byte)res.ReadByte ();
1726                                         }
1727                                 }
1728                         } else {
1729                                 sources = new SourceInfo [1];
1730                                 sources [0].source_file = res.ReadString ();
1731                         }
1732
1733                         int n_il_offsets = res.ReadInt ();
1734                         info.il_offsets = new int [n_il_offsets];
1735                         info.line_numbers = new int [n_il_offsets];
1736                         info.source_files = new SourceInfo [n_il_offsets];
1737                         info.column_numbers = new int [n_il_offsets];
1738                         for (int i = 0; i < n_il_offsets; ++i) {
1739                                 info.il_offsets [i] = res.ReadInt ();
1740                                 info.line_numbers [i] = res.ReadInt ();
1741                                 if (Version.AtLeast (2, 12)) {
1742                                         int idx = res.ReadInt ();
1743                                         info.source_files [i] = idx >= 0 ? sources [idx] : default (SourceInfo);
1744                                 } else {
1745                                         info.source_files [i] = sources [0];
1746                                 }
1747                                 if (Version.AtLeast (2, 19))
1748                                         info.column_numbers [i] = res.ReadInt ();
1749                                 else
1750                                         info.column_numbers [i] = 0;
1751                         }
1752
1753                         return info;
1754                 }
1755
1756                 internal ParamInfo Method_GetParamInfo (long id) {
1757                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_PARAM_INFO, new PacketWriter ().WriteId (id));
1758
1759                         ParamInfo info = new ParamInfo ();
1760                         info.call_conv = res.ReadInt ();
1761                         info.param_count = res.ReadInt ();
1762                         info.generic_param_count = res.ReadInt ();
1763                         info.ret_type = res.ReadId ();
1764                         info.param_types = new long [info.param_count];
1765                         for (int i = 0; i < info.param_count; ++i)
1766                                 info.param_types [i] = res.ReadId ();
1767                         info.param_names = new string [info.param_count];                       
1768                         for (int i = 0; i < info.param_count; ++i)
1769                                 info.param_names [i] = res.ReadString ();
1770
1771                         return info;
1772                 }
1773
1774                 internal LocalsInfo Method_GetLocalsInfo (long id) {
1775                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_LOCALS_INFO, new PacketWriter ().WriteId (id));
1776
1777                         LocalsInfo info = new LocalsInfo ();
1778                         int nlocals = res.ReadInt ();
1779                         info.types = new long [nlocals];
1780                         for (int i = 0; i < nlocals; ++i)
1781                                 info.types [i] = res.ReadId ();
1782                         info.names = new string [nlocals];
1783                         for (int i = 0; i < nlocals; ++i)
1784                                 info.names [i] = res.ReadString ();
1785                         info.live_range_start = new int [nlocals];
1786                         info.live_range_end = new int [nlocals];
1787                         for (int i = 0; i < nlocals; ++i) {
1788                                 info.live_range_start [i] = res.ReadInt ();
1789                                 info.live_range_end [i] = res.ReadInt ();
1790                         }
1791
1792                         return info;
1793                 }
1794
1795                 internal MethodInfo Method_GetInfo (long id) {
1796                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_INFO, new PacketWriter ().WriteId (id));
1797
1798                         MethodInfo info = new MethodInfo ();
1799                         info.attributes = res.ReadInt ();
1800                         info.iattributes = res.ReadInt ();
1801                         info.token = res.ReadInt ();
1802                         if (Version.AtLeast (2, 12)) {
1803                                 int attrs = res.ReadByte ();
1804                                 if ((attrs & (1 << 0)) != 0)
1805                                         info.is_gmd = true;
1806                                 if ((attrs & (1 << 1)) != 0)
1807                                         info.is_generic_method = true;
1808                                 info.gmd = res.ReadId ();
1809                                 if (Version.AtLeast (2, 15)) {
1810                                         if (info.is_generic_method) {
1811                                                 int n = res.ReadInt ();
1812                                                 info.type_args = res.ReadIds (n);
1813                                         }
1814                                 }
1815                         }
1816                         return info;
1817                 }
1818
1819                 internal MethodBodyInfo Method_GetBody (long id) {
1820                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_BODY, new PacketWriter ().WriteId (id));
1821
1822                         MethodBodyInfo info = new MethodBodyInfo ();
1823                         info.il = new byte [res.ReadInt ()];
1824                         for (int i = 0; i < info.il.Length; ++i)
1825                                 info.il [i] = (byte)res.ReadByte ();
1826
1827                         if (Version.AtLeast (2, 18)) {
1828                                 info.clauses = new ExceptionClauseInfo [res.ReadInt ()];
1829
1830                                 for (int i = 0; i < info.clauses.Length; ++i) {
1831                                         var clause = new ExceptionClauseInfo {
1832                                                 flags = (ExceptionClauseFlags) res.ReadInt (),
1833                                                 try_offset = res.ReadInt (),
1834                                                 try_length = res.ReadInt (),
1835                                                 handler_offset = res.ReadInt (),
1836                                                 handler_length = res.ReadInt (),
1837                                         };
1838
1839                                         if (clause.flags == ExceptionClauseFlags.None)
1840                                                 clause.catch_type_id = res.ReadId ();
1841                                         else if (clause.flags == ExceptionClauseFlags.Filter)
1842                                                 clause.filter_offset = res.ReadInt ();
1843
1844                                         info.clauses [i] = clause;
1845                                 }
1846                         } else
1847                                 info.clauses = new ExceptionClauseInfo [0];
1848
1849                         return info;
1850                 }
1851
1852                 internal ResolvedToken Method_ResolveToken (long id, int token) {
1853                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.RESOLVE_TOKEN, new PacketWriter ().WriteId (id).WriteInt (token));
1854
1855                         TokenType type = (TokenType)res.ReadByte ();
1856                         switch (type) {
1857                         case TokenType.STRING:
1858                                 return new ResolvedToken () { Type = type, Str = res.ReadString () };
1859                         case TokenType.TYPE:
1860                         case TokenType.METHOD:
1861                         case TokenType.FIELD:
1862                                 return new ResolvedToken () { Type = type, Id = res.ReadId () };
1863                         case TokenType.UNKNOWN:
1864                                 return new ResolvedToken () { Type = type };
1865                         default:
1866                                 throw new NotImplementedException ();
1867                         }
1868                 }
1869
1870                 internal CattrInfo[] Method_GetCustomAttributes (long id, long attr_type_id, bool inherit) {
1871                         PacketReader r = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_CATTRS, new PacketWriter ().WriteId (id).WriteId (attr_type_id));
1872                         return ReadCattrs (r);
1873                 }
1874
1875                 /*
1876                  * THREAD
1877                  */
1878
1879                 internal string Thread_GetName (long id) {
1880                         return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_NAME, new PacketWriter ().WriteId (id)).ReadString ();
1881                 }
1882
1883                 internal FrameInfo[] Thread_GetFrameInfo (long id, int start_frame, int length) {
1884                         var res = SendReceive (CommandSet.THREAD, (int)CmdThread.GET_FRAME_INFO, new PacketWriter ().WriteId (id).WriteInt (start_frame).WriteInt (length));
1885                         int count = res.ReadInt ();
1886
1887                         var frames = new FrameInfo [count];
1888                         for (int i = 0; i < count; ++i) {
1889                                 var f = new FrameInfo ();
1890                                 f.id = res.ReadInt ();
1891                                 f.method = res.ReadId ();
1892                                 f.il_offset = res.ReadInt ();
1893                                 f.flags = (StackFrameFlags)res.ReadByte ();
1894                                 frames [i] = f;
1895                         }
1896
1897                         return frames;
1898                 }
1899
1900                 internal int Thread_GetState (long id) {
1901                         return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_STATE, new PacketWriter ().WriteId (id)).ReadInt ();
1902                 }
1903
1904                 internal ThreadInfo Thread_GetInfo (long id) {
1905                         PacketReader r = SendReceive (CommandSet.THREAD, (int)CmdThread.GET_INFO, new PacketWriter ().WriteId (id));
1906
1907                         ThreadInfo res = new ThreadInfo () { is_thread_pool = r.ReadByte () > 0 ? true : false };
1908
1909                         return res;
1910                 }
1911
1912                 internal long Thread_GetId (long id) {
1913                         return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_ID, new PacketWriter ().WriteId (id)).ReadLong ();
1914                 }
1915
1916                 internal long Thread_GetTID (long id) {
1917                         return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_TID, new PacketWriter ().WriteId (id)).ReadLong ();
1918                 }
1919
1920                 /*
1921                  * MODULE
1922                  */
1923
1924                 internal ModuleInfo Module_GetInfo (long id) {
1925                         PacketReader r = SendReceive (CommandSet.MODULE, (int)CmdModule.GET_INFO, new PacketWriter ().WriteId (id));
1926                         ModuleInfo info = new ModuleInfo { Name = r.ReadString (), ScopeName = r.ReadString (), FQName = r.ReadString (), Guid = r.ReadString (), Assembly = r.ReadId () };
1927                         return info;
1928                 }
1929
1930                 /*
1931                  * ASSEMBLY
1932                  */
1933
1934                 internal string Assembly_GetLocation (long id) {
1935                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_LOCATION, new PacketWriter ().WriteId (id)).ReadString ();
1936                 }
1937
1938                 internal long Assembly_GetEntryPoint (long id) {
1939                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_ENTRY_POINT, new PacketWriter ().WriteId (id)).ReadId ();
1940                 }
1941
1942                 internal long Assembly_GetManifestModule (long id) {
1943                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_MANIFEST_MODULE, new PacketWriter ().WriteId (id)).ReadId ();
1944                 }
1945
1946                 internal long Assembly_GetObject (long id) {
1947                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_OBJECT, new PacketWriter ().WriteId (id)).ReadId ();
1948                 }
1949
1950                 internal long Assembly_GetType (long id, string name, bool ignoreCase) {
1951                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_TYPE, new PacketWriter ().WriteId (id).WriteString (name).WriteBool (ignoreCase)).ReadId ();
1952                 }
1953
1954                 internal string Assembly_GetName (long id) {
1955                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_NAME, new PacketWriter ().WriteId (id)).ReadString ();
1956                 }
1957
1958                 /*
1959                  * TYPE
1960                  */
1961
1962                 internal TypeInfo Type_GetInfo (long id) {
1963                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_INFO, new PacketWriter ().WriteId (id));
1964                         TypeInfo res = new TypeInfo ();
1965
1966                         res.ns = r.ReadString ();
1967                         res.name = r.ReadString ();
1968                         res.full_name = r.ReadString ();
1969                         res.assembly = r.ReadId ();
1970                         res.module = r.ReadId ();
1971                         res.base_type = r.ReadId ();
1972                         res.element_type = r.ReadId ();
1973                         res.token = r.ReadInt ();
1974                         res.rank = r.ReadByte ();
1975                         res.attributes = r.ReadInt ();
1976                         int b = r.ReadByte ();
1977                         res.is_byref = (b & 1) != 0;
1978                         res.is_pointer = (b & 2) != 0;
1979                         res.is_primitive = (b & 4) != 0;
1980                         res.is_valuetype = (b & 8) != 0;
1981                         res.is_enum = (b & 16) != 0;
1982                         res.is_gtd = (b & 32) != 0;
1983                         res.is_generic_type = (b & 64) != 0;
1984
1985                         int nested_len = r.ReadInt ();
1986                         res.nested = new long [nested_len];
1987                         for (int i = 0; i < nested_len; ++i)
1988                                 res.nested [i] = r.ReadId ();
1989
1990                         if (Version.AtLeast (2, 12))
1991                                 res.gtd = r.ReadId ();
1992                         if (Version.AtLeast (2, 15) && res.is_generic_type) {
1993                                 int n = r.ReadInt ();
1994                                 res.type_args = r.ReadIds (n);
1995                         }
1996
1997                         return res;
1998                 }
1999
2000                 internal long[] Type_GetMethods (long id) {
2001                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_METHODS, new PacketWriter ().WriteId (id));
2002
2003                         int n = r.ReadInt ();
2004                         long[] res = new long [n];
2005                         for (int i = 0; i < n; ++i)
2006                                 res [i] = r.ReadId ();
2007                         return res;
2008                 }
2009
2010                 internal long[] Type_GetFields (long id, out string[] names, out long[] types, out int[] attrs) {
2011                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_FIELDS, new PacketWriter ().WriteId (id));
2012
2013                         int n = r.ReadInt ();
2014                         long[] res = new long [n];
2015                         names = new string [n];
2016                         types = new long [n];
2017                         attrs = new int [n];
2018                         for (int i = 0; i < n; ++i) {
2019                                 res [i] = r.ReadId ();
2020                                 names [i] = r.ReadString ();
2021                                 types [i] = r.ReadId ();
2022                                 attrs [i] = r.ReadInt ();
2023                         }
2024                         return res;
2025                 }
2026
2027                 internal PropInfo[] Type_GetProperties (long id) {
2028                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_PROPERTIES, new PacketWriter ().WriteId (id));
2029
2030                         int n = r.ReadInt ();
2031                         PropInfo[] res = new PropInfo [n];
2032                         for (int i = 0; i < n; ++i) {
2033                                 res [i] = new PropInfo ();
2034                                 res [i].id = r.ReadId ();
2035                                 res [i].name = r.ReadString ();
2036                                 res [i].get_method = r.ReadId ();
2037                                 res [i].set_method = r.ReadId ();
2038                                 res [i].attrs = r.ReadInt ();
2039                         }
2040
2041                         return res;
2042                 }
2043
2044                 internal long Type_GetObject (long id) {
2045                         return SendReceive (CommandSet.TYPE, (int)CmdType.GET_OBJECT, new PacketWriter ().WriteId (id)).ReadId ();
2046                 }
2047
2048                 internal ValueImpl[] Type_GetValues (long id, long[] fields, long thread_id) {
2049                         int len = fields.Length;
2050                         PacketReader r;
2051                         if (thread_id != 0)
2052                                 r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_VALUES_2, new PacketWriter ().WriteId (id).WriteId (thread_id).WriteInt (len).WriteIds (fields));
2053                         else
2054                                 r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_VALUES, new PacketWriter ().WriteId (id).WriteInt (len).WriteIds (fields));
2055
2056                         ValueImpl[] res = new ValueImpl [len];
2057                         for (int i = 0; i < len; ++i)
2058                                 res [i] = r.ReadValue ();
2059                         return res;
2060                 }                       
2061
2062                 internal void Type_SetValues (long id, long[] fields, ValueImpl[] values) {
2063                         SendReceive (CommandSet.TYPE, (int)CmdType.SET_VALUES, new PacketWriter ().WriteId (id).WriteInt (fields.Length).WriteIds (fields).WriteValues (values));
2064                 }
2065
2066                 internal string[] Type_GetSourceFiles (long id, bool return_full_paths) {
2067                         var r = SendReceive (CommandSet.TYPE, return_full_paths ? (int)CmdType.GET_SOURCE_FILES_2 : (int)CmdType.GET_SOURCE_FILES, new PacketWriter ().WriteId (id));
2068                         int len = r.ReadInt ();
2069                         string[] res = new string [len];
2070                         for (int i = 0; i < len; ++i)
2071                                 res [i] = r.ReadString ();
2072                         return res;
2073                 }
2074
2075                 internal bool Type_IsAssignableFrom (long id, long c_id) {
2076                         return SendReceive (CommandSet.TYPE, (int)CmdType.IS_ASSIGNABLE_FROM, new PacketWriter ().WriteId (id).WriteId (c_id)).ReadByte () > 0;
2077                 }
2078
2079                 internal CattrInfo[] Type_GetCustomAttributes (long id, long attr_type_id, bool inherit) {
2080                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_CATTRS, new PacketWriter ().WriteId (id).WriteId (attr_type_id));
2081                         return ReadCattrs (r);
2082                 }
2083
2084                 internal CattrInfo[] Type_GetFieldCustomAttributes (long id, long field_id, long attr_type_id, bool inherit) {
2085                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_FIELD_CATTRS, new PacketWriter ().WriteId (id).WriteId (field_id).WriteId (attr_type_id));
2086                         return ReadCattrs (r);
2087                 }
2088
2089                 internal CattrInfo[] Type_GetPropertyCustomAttributes (long id, long field_id, long attr_type_id, bool inherit) {
2090                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_PROPERTY_CATTRS, new PacketWriter ().WriteId (id).WriteId (field_id).WriteId (attr_type_id));
2091                         return ReadCattrs (r);
2092                 }
2093
2094                 public long[] Type_GetMethodsByNameFlags (long id, string name, int flags, bool ignoreCase) {
2095                         flags |= ignoreCase ? (int)BindingFlagsExtensions.BINDING_FLAGS_IGNORE_CASE : 0;
2096                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.CMD_TYPE_GET_METHODS_BY_NAME_FLAGS, new PacketWriter ().WriteId (id).WriteString (name).WriteInt (flags));
2097                         int len = r.ReadInt ();
2098                         long[] res = new long [len];
2099                         for (int i = 0; i < len; ++i)
2100                                 res [i] = r.ReadId ();
2101                         return res;
2102                 }
2103
2104                 internal long[] Type_GetInterfaces (long id) {
2105                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_INTERFACES, new PacketWriter ().WriteId (id));
2106                         int len = r.ReadInt ();
2107                         return r.ReadIds (len);
2108                 }
2109
2110                 internal IfaceMapInfo[] Type_GetInterfaceMap (long id, long[] ids) {
2111                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_INTERFACE_MAP, new PacketWriter ().WriteId (id).WriteInt (ids.Length).WriteIds (ids));
2112                         var res = new IfaceMapInfo [ids.Length];
2113                         for (int i = 0; i < ids.Length; ++i) {
2114                                 int n = r.ReadInt ();
2115
2116                                 res [i].iface_id = ids [i];
2117                                 res [i].iface_methods = r.ReadIds (n);
2118                                 res [i].target_methods = r.ReadIds (n);
2119                         }
2120
2121                         return res;
2122                 }
2123
2124                 /*
2125                  * EVENTS
2126                  */
2127
2128                 internal int EnableEvent (EventType etype, SuspendPolicy suspend_policy, List<Modifier> mods) {
2129                         var w = new PacketWriter ().WriteByte ((byte)etype).WriteByte ((byte)suspend_policy);
2130                         if (mods != null) {
2131                                 if (mods.Count > 255)
2132                                         throw new NotImplementedException ();
2133                                 w.WriteByte ((byte)mods.Count);
2134                                 foreach (Modifier mod in mods) {
2135                                         if (mod is CountModifier) {
2136                                                 w.WriteByte ((byte)ModifierKind.COUNT);
2137                                                 w.WriteInt ((mod as CountModifier).Count);
2138                                         } else if (mod is LocationModifier) {
2139                                                 w.WriteByte ((byte)ModifierKind.LOCATION_ONLY);
2140                                                 w.WriteId ((mod as LocationModifier).Method);
2141                                                 w.WriteLong ((mod as LocationModifier).Location);
2142                                         } else if (mod is StepModifier) {
2143                                                 w.WriteByte ((byte)ModifierKind.STEP);
2144                                                 w.WriteId ((mod as StepModifier).Thread);
2145                                                 w.WriteInt ((mod as StepModifier).Size);
2146                                                 w.WriteInt ((mod as StepModifier).Depth);
2147                                                 if (Version.AtLeast (2, 16))
2148                                                         w.WriteInt ((mod as StepModifier).Filter);
2149                                         } else if (mod is ThreadModifier) {
2150                                                 w.WriteByte ((byte)ModifierKind.THREAD_ONLY);
2151                                                 w.WriteId ((mod as ThreadModifier).Thread);
2152                                         } else if (mod is ExceptionModifier) {
2153                                                 var em = mod as ExceptionModifier;
2154                                                 w.WriteByte ((byte)ModifierKind.EXCEPTION_ONLY);
2155                                                 w.WriteId (em.Type);
2156                                                 if (Version.MajorVersion > 2 || Version.MinorVersion > 0) {
2157                                                         /* This is only supported in protocol version 2.1 */
2158                                                         w.WriteBool (em.Caught);
2159                                                         w.WriteBool (em.Uncaught);
2160                                                 } else if (!em.Caught || !em.Uncaught) {
2161                                                         throw new NotSupportedException ("This request is not supported by the protocol version implemented by the debuggee.");
2162                                                 }
2163                                         } else if (mod is AssemblyModifier) {
2164                                                 w.WriteByte ((byte)ModifierKind.ASSEMBLY_ONLY);
2165                                                 var amod = (mod as AssemblyModifier);
2166                                                 w.WriteInt (amod.Assemblies.Length);
2167                                                 foreach (var id in amod.Assemblies)
2168                                                         w.WriteId (id);
2169                                         } else if (mod is SourceFileModifier) {
2170                                                 w.WriteByte ((byte)ModifierKind.SOURCE_FILE_ONLY);
2171                                                 var smod = (mod as SourceFileModifier);
2172                                                 w.WriteInt (smod.SourceFiles.Length);
2173                                                 foreach (var s in smod.SourceFiles)
2174                                                         w.WriteString (s);
2175                                         } else if (mod is TypeNameModifier) {
2176                                                 w.WriteByte ((byte)ModifierKind.TYPE_NAME_ONLY);
2177                                                 var tmod = (mod as TypeNameModifier);
2178                                                 w.WriteInt (tmod.TypeNames.Length);
2179                                                 foreach (var s in tmod.TypeNames)
2180                                                         w.WriteString (s);
2181                                         } else {
2182                                                 throw new NotImplementedException ();
2183                                         }
2184                                 }
2185                         } else {
2186                                 w.WriteByte (0);
2187                         }
2188                         return SendReceive (CommandSet.EVENT_REQUEST, (int)CmdEventRequest.SET, w).ReadInt ();
2189                 }
2190
2191                 internal void ClearEventRequest (EventType etype, int req_id) {
2192                         SendReceive (CommandSet.EVENT_REQUEST, (int)CmdEventRequest.CLEAR, new PacketWriter ().WriteByte ((byte)etype).WriteInt (req_id));
2193                 }                       
2194
2195                 internal void ClearAllBreakpoints () {
2196                         SendReceive (CommandSet.EVENT_REQUEST, (int)CmdEventRequest.CLEAR_ALL_BREAKPOINTS, new PacketWriter ());
2197                 }
2198                         
2199                 /*
2200                  * STACK FRAME
2201                  */
2202                 internal ValueImpl StackFrame_GetThis (long thread_id, long id) {
2203                         PacketReader r = SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.GET_THIS, new PacketWriter ().WriteId (thread_id).WriteId (id));
2204                         return r.ReadValue ();
2205                 }
2206
2207                 internal ValueImpl[] StackFrame_GetValues (long thread_id, long id, int[] pos) {
2208                         /* pos < 0 -> argument at pos (-pos) - 1 */
2209                         /* pos >= 0 -> local at pos */
2210                         int len = pos.Length;
2211                         PacketReader r = SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.GET_VALUES, new PacketWriter ().WriteId (thread_id).WriteId (id).WriteInt (len).WriteInts (pos));
2212
2213                         ValueImpl[] res = new ValueImpl [len];
2214                         for (int i = 0; i < len; ++i)
2215                                 res [i] = r.ReadValue ();
2216                         return res;
2217                 }
2218
2219                 internal void StackFrame_SetValues (long thread_id, long id, int[] pos, ValueImpl[] values) {
2220                         /* pos < 0 -> argument at pos (-pos) - 1 */
2221                         /* pos >= 0 -> local at pos */
2222                         int len = pos.Length;
2223                         SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.SET_VALUES, new PacketWriter ().WriteId (thread_id).WriteId (id).WriteInt (len).WriteInts (pos).WriteValues (values));
2224                 }
2225
2226                 /*
2227                  * ARRAYS
2228                  */
2229                 internal int[] Array_GetLength (long id, out int rank, out int[] lower_bounds) {
2230                         var r = SendReceive (CommandSet.ARRAY_REF, (int)CmdArrayRef.GET_LENGTH, new PacketWriter ().WriteId (id));
2231                         rank = r.ReadInt ();
2232                         int[] res = new int [rank];
2233                         lower_bounds = new int [rank];
2234                         for (int i = 0; i < rank; ++i) {
2235                                 res [i] = r.ReadInt ();
2236                                 lower_bounds [i] = r.ReadInt ();
2237                         }
2238                         return res;
2239                 }
2240
2241                 internal ValueImpl[] Array_GetValues (long id, int index, int len) {
2242                         var r = SendReceive (CommandSet.ARRAY_REF, (int)CmdArrayRef.GET_VALUES, new PacketWriter ().WriteId (id).WriteInt (index).WriteInt (len));
2243                         ValueImpl[] res = new ValueImpl [len];
2244                         for (int i = 0; i < len; ++i)
2245                                 res [i] = r.ReadValue ();
2246                         return res;
2247                 }
2248
2249                 internal void Array_SetValues (long id, int index, ValueImpl[] values) {
2250                         SendReceive (CommandSet.ARRAY_REF, (int)CmdArrayRef.SET_VALUES, new PacketWriter ().WriteId (id).WriteInt (index).WriteInt (values.Length).WriteValues (values));
2251                 }
2252
2253                 /*
2254                  * STRINGS
2255                  */
2256                 internal string String_GetValue (long id) {
2257                         return SendReceive (CommandSet.STRING_REF, (int)CmdStringRef.GET_VALUE, new PacketWriter ().WriteId (id)).ReadString ();
2258                 }                       
2259
2260                 internal int String_GetLength (long id) {
2261                         return (int)SendReceive (CommandSet.STRING_REF, (int)CmdStringRef.GET_LENGTH, new PacketWriter ().WriteId (id)).ReadLong ();
2262                 }                       
2263
2264                 internal char[] String_GetChars (long id, int index, int length) {
2265                         var r = SendReceive (CommandSet.STRING_REF, (int)CmdStringRef.GET_CHARS, new PacketWriter ().WriteId (id).WriteLong (index).WriteLong (length));
2266                         var res = new char [length];
2267                         for (int i = 0; i < length; ++i)
2268                                 res [i] = (char)r.ReadShort ();
2269                         return res;
2270                 }                       
2271
2272                 /*
2273                  * OBJECTS
2274                  */
2275                 internal long Object_GetType (long id) {
2276                         return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_TYPE, new PacketWriter ().WriteId (id)).ReadId ();
2277                 }                       
2278
2279                 internal long Object_GetDomain (long id) {
2280                         return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_DOMAIN, new PacketWriter ().WriteId (id)).ReadId ();
2281                 }                       
2282
2283                 internal ValueImpl[] Object_GetValues (long id, long[] fields) {
2284                         int len = fields.Length;
2285                         PacketReader r = SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_VALUES, new PacketWriter ().WriteId (id).WriteInt (len).WriteIds (fields));
2286
2287                         ValueImpl[] res = new ValueImpl [len];
2288                         for (int i = 0; i < len; ++i)
2289                                 res [i] = r.ReadValue ();
2290                         return res;
2291                 }
2292
2293                 internal void Object_SetValues (long id, long[] fields, ValueImpl[] values) {
2294                         SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.SET_VALUES, new PacketWriter ().WriteId (id).WriteInt (fields.Length).WriteIds (fields).WriteValues (values));
2295                 }
2296
2297                 internal bool Object_IsCollected (long id) {
2298                         return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.IS_COLLECTED, new PacketWriter ().WriteId (id)).ReadInt () == 1;
2299                 }                       
2300
2301                 internal long Object_GetAddress (long id) {
2302                         return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_ADDRESS, new PacketWriter ().WriteId (id)).ReadLong ();
2303                 }                       
2304
2305                 internal ObjectRefInfo Object_GetInfo (long id) {
2306                         ObjectRefInfo res = new ObjectRefInfo ();
2307                         PacketReader r = SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_INFO, new PacketWriter ().WriteId (id));
2308
2309                         res.type_id = r.ReadId ();
2310                         res.domain_id = r.ReadId ();
2311                         return res;
2312                 }
2313
2314                 public void ForceDisconnect ()
2315                 {
2316                         TransportClose ();
2317                 }
2318         }
2319         
2320         class TcpConnection : Connection
2321         {
2322                 Socket socket;
2323                 
2324                 internal TcpConnection (Socket socket)
2325                 {
2326                         this.socket = socket;
2327                         //socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.NoDelay, 1);
2328                 }
2329                 
2330                 internal EndPoint EndPoint {
2331                         get {
2332                                 return socket.RemoteEndPoint;
2333                         }
2334                 }
2335                 
2336                 protected override int TransportSend (byte[] buf, int buf_offset, int len)
2337                 {
2338                         return socket.Send (buf, buf_offset, len, SocketFlags.None);
2339                 }
2340                 
2341                 protected override int TransportReceive (byte[] buf, int buf_offset, int len)
2342                 {
2343                         return socket.Receive (buf, buf_offset, len, SocketFlags.None);
2344                 }
2345                 
2346                 protected override void TransportSetTimeouts (int send_timeout, int receive_timeout)
2347                 {
2348                         socket.SendTimeout = send_timeout;
2349                         socket.ReceiveTimeout = receive_timeout;
2350                 }
2351                 
2352                 protected override void TransportClose ()
2353                 {
2354                         socket.Close ();
2355                 }
2356         }
2357
2358         /* This is the interface exposed by the debugger towards the debugger agent */
2359         interface IEventHandler
2360         {
2361                 void Events (SuspendPolicy suspend_policy, EventInfo[] events);
2362
2363                 void VMDisconnect (int req_id, long thread_id, string vm_uri);
2364         }
2365 }