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