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