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