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