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