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