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