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