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