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