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