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