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