2010-03-12 Jb Evain <jbevain@novell.com>
[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 Mono.Cecil.Metadata;
9
10 namespace Mono.Debugger.Soft
11 {
12         class VersionInfo {
13                 public string VMVersion {
14                         get; set;
15                 }
16
17                 public int MajorVersion {
18                         get; set;
19                 }
20
21                 public int MinorVersion {
22                         get; set;
23                 }
24         }
25
26         class DebugInfo {
27                 public int max_il_offset;
28                 public string filename;
29                 public int[] il_offsets;
30                 public int[] line_numbers;
31         }
32
33         struct FrameInfo {
34                 public long id;
35                 public long method;
36                 public int il_offset;
37                 public StackFrameFlags flags;
38         }
39
40         class TypeInfo {
41                 public string ns, name, full_name;
42                 public long assembly, module, base_type, element_type;
43                 public int token, rank, attributes;
44                 public bool is_byref, is_pointer, is_primitive, is_valuetype, is_enum;
45                 public long[] nested;
46         }
47
48         class MethodInfo {
49                 public int attributes, iattributes, token;
50         }
51
52         class MethodBodyInfo {
53                 public byte[] il;
54         }
55
56         struct ParamInfo {
57                 public int call_conv;
58                 public int param_count;
59                 public int generic_param_count;
60                 public long ret_type;
61                 public long[] param_types;
62                 public string[] param_names;
63         }
64
65         struct LocalsInfo {
66                 public long[] types;
67                 public string[] names;
68                 public int[] live_range_start;
69                 public int[] live_range_end;
70         }
71
72         struct PropInfo {
73                 public long id;
74                 public string name;
75                 public long get_method, set_method;
76                 public int attrs;
77         }
78
79         class CattrNamedArgInfo {
80                 public bool is_property;
81                 public long id;
82                 public ValueImpl value;
83         }
84
85         class CattrInfo {
86                 public long ctor_id;
87                 public ValueImpl[] ctor_args;
88                 public CattrNamedArgInfo[] named_args;
89         }
90
91         class ThreadInfo {
92                 public bool is_thread_pool;
93         }
94
95         enum ValueTypeId {
96                 VALUE_TYPE_ID_NULL = 0xf0,
97                 VALUE_TYPE_ID_TYPE = 0xf1
98         }
99
100         enum InvokeFlags {
101                 NONE = 0x0,
102                 DISABLE_BREAKPOINTS = 0x1,
103                 SINGLE_THREADED = 0x2
104         }
105
106         class ValueImpl {
107                 public ElementType Type; /* or one of the VALUE_TYPE_ID constants */
108                 public long Objid;
109                 public object Value;
110                 public long Klass; // For ElementType.ValueType
111                 public ValueImpl[] Fields; // for ElementType.ValueType
112                 public bool IsEnum; // For ElementType.ValueType
113                 public long Id; /* For VALUE_TYPE_ID_TYPE */
114         }
115
116         class ModuleInfo {
117                 public string Name, ScopeName, FQName, Guid;
118                 public long Assembly;
119         }               
120
121         enum TokenType {
122                 STRING = 0,
123                 TYPE = 1,
124                 FIELD = 2,
125                 METHOD = 3,
126                 UNKNOWN = 4
127         }
128
129         enum StackFrameFlags {
130                 DEBUGGER_INVOKE = 1
131         }
132
133         class ResolvedToken {
134                 public TokenType Type;
135                 public string Str;
136                 public long Id;
137         }
138
139         class Modifier {
140         }
141
142         class CountModifier : Modifier {
143                 public int Count {
144                         get; set;
145                 }
146         }
147
148         class LocationModifier : Modifier {
149                 public long Method {
150                         get; set;
151                 }
152
153                 public long Location {
154                         get; set;
155                 }
156         }
157
158         class StepModifier : Modifier {
159                 public long Thread {
160                         get; set;
161                 }
162
163                 public int Depth {
164                         get; set;
165                 }
166
167                 public int Size {
168                         get; set;
169                 }
170         }
171
172         class ThreadModifier : Modifier {
173                 public long Thread {
174                         get; set;
175                 }
176         }
177
178         class ExceptionModifier : Modifier {
179                 public long Type {
180                         get; set;
181                 }
182                 public bool Caught {
183                         get; set;
184                 }
185                 public bool Uncaught {
186                         get; set;
187                 }
188         }
189
190         class AssemblyModifier : Modifier {
191                 public long[] Assemblies {
192                         get; set;
193                 }
194         }
195
196         public enum ErrorCode {
197                 NONE = 0,
198                 INVALID_OBJECT = 20,
199                 INVALID_FIELDID = 25,
200                 INVALID_FRAMEID = 30,
201                 NOT_IMPLEMENTED = 100,
202                 NOT_SUSPENDED = 101,
203                 INVALID_ARGUMENT = 102,
204                 ERR_UNLOADED = 103,
205                 ERR_NO_INVOCATION = 104
206         }
207
208         public class ErrorHandlerEventArgs : EventArgs {
209
210                 public ErrorCode ErrorCode {
211                         get; set;
212                 }
213         }
214
215         /*
216          * Represents the connection to the debuggee
217          */
218         class Connection
219         {
220                 /*
221                  * The protocol and the packet format is based on JDWP, the differences 
222                  * are in the set of supported events, and the commands.
223                  */
224                 public const string HANDSHAKE_STRING = "DWP-Handshake";
225
226                 public const int HEADER_LENGTH = 11;
227
228                 /*
229                  * Th version of the wire-protocol implemented by the library. The library
230                  * and the debuggee can communicate if they implement the same major version.
231                  * If they implement a different minor version, they can communicate, but some
232                  * features might not be available. This allows older clients to communicate
233                  * with newer runtimes, and vice versa.
234                  */
235                 public const int MAJOR_VERSION = 2;
236                 public const int MINOR_VERSION = 1;
237
238                 enum WPSuspendPolicy {
239                         NONE = 0,
240                         EVENT_THREAD = 1,
241                         ALL = 2
242                 }
243
244                 enum CommandSet {
245                         VM = 1,
246                         OBJECT_REF = 9,
247                         STRING_REF = 10,
248                         THREAD = 11,
249                         ARRAY_REF = 13,
250                         EVENT_REQUEST = 15,
251                         STACK_FRAME = 16,
252                         APPDOMAIN = 20,
253                         ASSEMBLY = 21,
254                         METHOD = 22,
255                         TYPE = 23,
256                         MODULE = 24,
257                         EVENT = 64
258                 }
259
260                 enum EventKind {
261                         VM_START = 0,
262                         VM_DEATH = 1,
263                         THREAD_START = 2,
264                         THREAD_DEATH = 3,
265                         APPDOMAIN_CREATE = 4, // Not in JDI
266                         APPDOMAIN_UNLOAD = 5, // Not in JDI
267                         METHOD_ENTRY = 6,
268                         METHOD_EXIT = 7,
269                         ASSEMBLY_LOAD = 8,
270                         ASSEMBLY_UNLOAD = 9,
271                         BREAKPOINT = 10,
272                         STEP = 11,
273                         TYPE_LOAD = 12,
274                         EXCEPTION = 13
275                 }
276
277                 enum ModifierKind {
278                         COUNT = 1,
279                         THREAD_ONLY = 3,
280                         LOCATION_ONLY = 7,
281                         EXCEPTION_ONLY = 8,
282                         STEP = 10,
283                         ASSEMBLY_ONLY = 11
284                 }
285
286                 enum CmdVM {
287                         VERSION = 1,
288                         ALL_THREADS = 2,
289                         SUSPEND = 3,
290                         RESUME = 4,
291                         EXIT = 5,
292                         DISPOSE = 6,
293                         INVOKE_METHOD = 7,
294                         SET_PROTOCOL_VERSION = 8,
295                         ABORT_INVOKE = 9
296                 }
297
298                 enum CmdEvent {
299                         COMPOSITE = 100
300                 }
301
302                 enum CmdThread {
303                         GET_FRAME_INFO = 1,
304                         GET_NAME = 2,
305                         GET_STATE = 3,
306                         GET_INFO = 4
307                 }
308
309                 enum CmdEventRequest {
310                         SET = 1,
311                         CLEAR = 2,
312                         CLEAR_ALL_BREAKPOINTS = 3
313                 }
314
315                 enum CmdAppDomain {
316                         GET_ROOT_DOMAIN = 1,
317                         GET_FRIENDLY_NAME = 2,
318                         GET_ASSEMBLIES = 3,
319                         GET_ENTRY_ASSEMBLY = 4,
320                         CREATE_STRING = 5,
321                         GET_CORLIB = 6,
322                         CREATE_BOXED_VALUE = 7
323                 }
324
325                 enum CmdAssembly {
326                         GET_LOCATION = 1,
327                         GET_ENTRY_POINT = 2,
328                         GET_MANIFEST_MODULE = 3,
329                         GET_OBJECT = 4,
330                         GET_TYPE = 5,
331                         GET_NAME = 6
332                 }
333
334                 enum CmdModule {
335                         GET_INFO = 1,
336                 }
337
338                 enum CmdMethod {
339                         GET_NAME = 1,
340                         GET_DECLARING_TYPE = 2,
341                         GET_DEBUG_INFO = 3,
342                         GET_PARAM_INFO = 4,
343                         GET_LOCALS_INFO = 5,
344                         GET_INFO = 6,
345                         GET_BODY = 7,
346                         RESOLVE_TOKEN = 8
347                 }
348
349                 enum CmdType {
350                         GET_INFO = 1,
351                         GET_METHODS = 2,
352                         GET_FIELDS = 3,
353                         GET_VALUES = 4,
354                         GET_OBJECT = 5,
355                         GET_SOURCE_FILES = 6,
356                         SET_VALUES = 7,
357                         IS_ASSIGNABLE_FROM = 8,
358                         GET_PROPERTIES = 9,
359                         GET_CATTRS = 10,
360                         GET_FIELD_CATTRS = 11,
361                         GET_PROPERTY_CATTRS = 12
362                 }
363
364                 enum CmdStackFrame {
365                         GET_VALUES = 1,
366                         GET_THIS = 2,
367                         SET_VALUES = 3
368                 }
369
370                 enum CmdArrayRef {
371                         GET_LENGTH = 1,
372                         GET_VALUES = 2,
373                         SET_VALUES = 3
374                 }
375
376                 enum CmdStringRef {
377                         GET_VALUE = 1
378                 }
379
380                 enum CmdObjectRef {
381                         GET_TYPE = 1,
382                         GET_VALUES = 2,
383                         IS_COLLECTED = 3,
384                         GET_ADDRESS = 4,
385                         GET_DOMAIN = 5,
386                         SET_VALUES = 6
387                 }
388
389                 class Header {
390                         public int id;
391                         public int command_set;
392                         public int command;
393                         public int flags;
394                 }                       
395
396                 public static int GetPacketLength (byte[] header) {
397                         int offset = 0;
398                         return decode_int (header, ref offset);
399                 }
400
401                 public static bool IsReplyPacket (byte[] packet) {
402                         int offset = 8;
403                         return decode_byte (packet, ref offset) == 0x80;
404                 }
405
406                 public static int GetPacketId (byte[] packet) {
407                         int offset = 4;
408                         return decode_int (packet, ref offset);
409                 }
410
411                 static int decode_byte (byte[] packet, ref int offset) {
412                         return packet [offset++];
413                 }
414
415                 static int decode_short (byte[] packet, ref int offset) {
416                         int res = ((int)packet [offset] << 8) | (int)packet [offset + 1];
417                         offset += 2;
418                         return res;
419                 }
420
421                 static int decode_int (byte[] packet, ref int offset) {
422                         int res = ((int)packet [offset] << 24) | ((int)packet [offset + 1] << 16) | ((int)packet [offset + 2] << 8) | (int)packet [offset + 3];
423                         offset += 4;
424                         return res;
425                 }
426
427                 static long decode_id (byte[] packet, ref int offset) {
428                         return decode_int (packet, ref offset);
429                 }
430
431                 static long decode_long (byte[] packet, ref int offset) {
432                         uint high = (uint)decode_int (packet, ref offset);
433                         uint low = (uint)decode_int (packet, ref offset);
434
435                         return (long)(((ulong)high << 32) | (ulong)low);
436                 }
437
438                 public static SuspendPolicy decode_suspend_policy (int suspend_policy) {
439                         switch ((WPSuspendPolicy)suspend_policy) {
440                         case WPSuspendPolicy.NONE:
441                                 return SuspendPolicy.None;
442                         case WPSuspendPolicy.EVENT_THREAD:
443                                 return SuspendPolicy.EventThread;
444                         case WPSuspendPolicy.ALL:
445                                 return SuspendPolicy.All;
446                         default:
447                                 throw new NotImplementedException ();
448                         }
449                 }
450
451                 static Header decode_command_header (byte[] packet) {
452                         int offset = 0;
453                         Header res = new Header ();
454
455                         decode_int (packet, ref offset);
456                         res.id = decode_int (packet, ref offset);
457                         res.flags = decode_byte (packet, ref offset);
458                         res.command_set = decode_byte (packet, ref offset);
459                         res.command = decode_byte (packet, ref offset);
460
461                         return res;
462                 }
463
464                 static void encode_byte (byte[] buf, int b, ref int offset) {
465                         buf [offset] = (byte)b;
466                         offset ++;
467                 }
468
469                 static void encode_int (byte[] buf, int i, ref int offset) {
470                         buf [offset] = (byte)((i >> 24) & 0xff);
471                         buf [offset + 1] = (byte)((i >> 16) & 0xff);
472                         buf [offset + 2] = (byte)((i >> 8) & 0xff);
473                         buf [offset + 3] = (byte)((i >> 0) & 0xff);
474                         offset += 4;
475                 }
476
477                 static void encode_id (byte[] buf, long id, ref int offset) {
478                         encode_int (buf, (int)id, ref offset);
479                 }
480
481                 static void encode_long (byte[] buf, long l, ref int offset) {
482                         encode_int (buf, (int)((l >> 32) & 0xffffffff), ref offset);
483                         encode_int (buf, (int)(l & 0xffffffff), ref offset);
484                 }
485
486                 public static byte[] EncodePacket (int id, int commandSet, int command, byte[] data, int dataLen) {
487                         byte[] buf = new byte [dataLen + 11];
488                         int offset = 0;
489                         
490                         encode_int (buf, buf.Length, ref offset);
491                         encode_int (buf, id, ref offset);
492                         encode_byte (buf, 0, ref offset);
493                         encode_byte (buf, commandSet, ref offset);
494                         encode_byte (buf, command, ref offset);
495
496                         for (int i = 0; i < dataLen; ++i)
497                                 buf [offset + i] = data [i];
498
499                         return buf;
500                 }
501
502                 class PacketReader {
503                         byte[] packet;
504                         int offset;
505
506                         public PacketReader (byte[] packet) {
507                                 this.packet = packet;
508
509                                 // For event packets
510                                 Header header = decode_command_header (packet);
511                                 CommandSet = (CommandSet)header.command_set;
512                                 Command = header.command;
513
514                                 // For reply packets
515                                 offset = 0;
516                                 ReadInt (); // length
517                                 ReadInt (); // id
518                                 ReadByte (); // flags
519                                 ErrorCode = ReadShort ();
520                         }
521
522                         public CommandSet CommandSet {
523                                 get; set;
524                         }
525
526                         public int Command {
527                                 get; set;
528                         }
529
530                         public int ErrorCode {
531                                 get; set;
532                         }
533
534                         public int Offset {
535                                 get {
536                                         return offset;
537                                 }
538                         }
539
540                         public int ReadByte () {
541                                 return decode_byte (packet, ref offset);
542                         }
543
544                         public int ReadShort () {
545                                 return decode_short (packet, ref offset);
546                         }
547
548                         public int ReadInt () {
549                                 return decode_int (packet, ref offset);
550                         }
551
552                         public long ReadId () {
553                                 return decode_id (packet, ref offset);
554                         }
555
556                         public long ReadLong () {
557                                 return decode_long (packet, ref offset);
558                         }
559
560                         public float ReadFloat () {
561                                 float f = DataConverter.FloatFromBE (packet, offset);
562                                 offset += 4;
563                                 return f;
564                         }
565
566                         public double ReadDouble () {
567                                 double d = DataConverter.DoubleFromBE (packet, offset);
568                                 offset += 8;
569                                 return d;
570                         }
571
572                         public string ReadString () {
573                                 int len = decode_int (packet, ref offset);
574                                 string res = new String (Encoding.UTF8.GetChars (packet, offset, len));
575                                 offset += len;
576                                 return res;
577                         }
578
579                         public ValueImpl ReadValue () {
580                                 ElementType etype = (ElementType)ReadByte ();
581
582                                 switch (etype) {
583                                 case ElementType.Void:
584                                         return new ValueImpl { Type = etype };
585                                 case ElementType.I1:
586                                         return new ValueImpl { Type = etype, Value = (sbyte)ReadInt () };
587                                 case ElementType.U1:
588                                         return new ValueImpl { Type = etype, Value = (byte)ReadInt () };
589                                 case ElementType.Boolean:
590                                         return new ValueImpl { Type = etype, Value = ReadInt () != 0 };
591                                 case ElementType.I2:
592                                         return new ValueImpl { Type = etype, Value = (short)ReadInt () };
593                                 case ElementType.U2:
594                                         return new ValueImpl { Type = etype, Value = (ushort)ReadInt () };
595                                 case ElementType.Char:
596                                         return new ValueImpl { Type = etype, Value = (char)ReadInt () };
597                                 case ElementType.I4:
598                                         return new ValueImpl { Type = etype, Value = ReadInt () };
599                                 case ElementType.U4:
600                                         return new ValueImpl { Type = etype, Value = (uint)ReadInt () };
601                                 case ElementType.I8:
602                                         return new ValueImpl { Type = etype, Value = ReadLong () };
603                                 case ElementType.U8:
604                                         return new ValueImpl { Type = etype, Value = (ulong)ReadLong () };
605                                 case ElementType.R4:
606                                         return new ValueImpl { Type = etype, Value = ReadFloat () };
607                                 case ElementType.R8:
608                                         return new ValueImpl { Type = etype, Value = ReadDouble () };
609                                 case ElementType.I:
610                                 case ElementType.U:
611                                 case ElementType.Ptr:
612                                         // FIXME: The client and the debuggee might have different word sizes
613                                         return new ValueImpl { Type = etype, Value = ReadLong () };
614                                 case ElementType.String:
615                                 case ElementType.SzArray:
616                                 case ElementType.Class:
617                                 case ElementType.Array:
618                                 case ElementType.Object:
619                                         long objid = ReadId ();
620                                         return new ValueImpl () { Type = etype, Objid = objid };
621                                 case ElementType.ValueType:
622                                         bool is_enum = ReadByte () == 1;
623                                         long klass = ReadId ();
624                                         long nfields = ReadInt ();
625                                         ValueImpl[] fields = new ValueImpl [nfields];
626                                         for (int i = 0; i < nfields; ++i)
627                                                 fields [i] = ReadValue ();
628                                         return new ValueImpl () { Type = etype, Klass = klass, Fields = fields, IsEnum = is_enum };
629                                 case (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL:
630                                         return new ValueImpl { Type = etype };
631                                 case (ElementType)ValueTypeId.VALUE_TYPE_ID_TYPE:
632                                         return new ValueImpl () { Type = etype, Id = ReadId () };
633                                 default:
634                                         throw new NotImplementedException ("Unable to handle type " + etype);
635                                 }
636                         }
637                 }
638
639                 class PacketWriter {
640
641                         byte[] data;
642                         int offset;
643
644                         public PacketWriter () {
645                                 // FIXME:
646                                 data = new byte [1024];
647                                 offset = 0;
648                         }
649
650                         public PacketWriter WriteByte (byte val) {
651                                 encode_byte (data, val, ref offset);
652                                 return this;
653                         }
654
655                         public PacketWriter WriteInt (int val) {
656                                 encode_int (data, val, ref offset);
657                                 return this;
658                         }
659
660                         public PacketWriter WriteId (long id) {
661                                 encode_id (data, id, ref offset);
662                                 return this;
663                         }
664
665                         public PacketWriter WriteLong (long val) {
666                                 encode_long (data, val, ref offset);
667                                 return this;
668                         }
669
670                         public PacketWriter WriteFloat (float f) {
671                                 byte[] b = DataConverter.GetBytesBE (f);
672                                 for (int i = 0; i < 4; ++i)
673                                         data [offset + i] = b [i];
674                                 offset += 4;
675                                 return this;
676                         }
677
678                         public PacketWriter WriteDouble (double d) {
679                                 byte[] b = DataConverter.GetBytesBE (d);
680                                 for (int i = 0; i < 8; ++i)
681                                         data [offset + i] = b [i];
682                                 offset += 8;
683                                 return this;
684                         }
685
686                         public PacketWriter WriteInts (int[] ids) {
687                                 for (int i = 0; i < ids.Length; ++i)
688                                         WriteInt (ids [i]);
689                                 return this;
690                         }
691
692                         public PacketWriter WriteIds (long[] ids) {
693                                 for (int i = 0; i < ids.Length; ++i)
694                                         WriteId (ids [i]);
695                                 return this;
696                         }
697
698                         public PacketWriter WriteString (string s) {
699                                 encode_int (data, s.Length, ref offset);
700                                 byte[] b = Encoding.UTF8.GetBytes (s);
701                                 Buffer.BlockCopy (b, 0, data, offset, b.Length);
702                                 offset += b.Length;
703                                 return this;
704                         }
705
706                         public PacketWriter WriteBool (bool val) {
707                                 WriteByte (val ? (byte)1 : (byte)0);
708                                 return this;
709                         }
710
711                         public PacketWriter WriteValue (ValueImpl v) {
712                                 ElementType t;
713
714                                 if (v.Value != null)
715                                         t = TypeCodeToElementType (Type.GetTypeCode (v.Value.GetType ()));
716                                 else
717                                         t = v.Type;
718                                 WriteByte ((byte)t);
719                                 switch (t) {
720                                 case ElementType.Boolean:
721                                         WriteInt ((bool)v.Value ? 1 : 0);
722                                         break;
723                                 case ElementType.Char:
724                                         WriteInt ((int)(char)v.Value);
725                                         break;
726                                 case ElementType.I1:
727                                         WriteInt ((int)(sbyte)v.Value);
728                                         break;
729                                 case ElementType.U1:
730                                         WriteInt ((int)(byte)v.Value);
731                                         break;
732                                 case ElementType.I2:
733                                         WriteInt ((int)(short)v.Value);
734                                         break;
735                                 case ElementType.U2:
736                                         WriteInt ((int)(ushort)v.Value);
737                                         break;
738                                 case ElementType.I4:
739                                         WriteInt ((int)(int)v.Value);
740                                         break;
741                                 case ElementType.U4:
742                                         WriteInt ((int)(uint)v.Value);
743                                         break;
744                                 case ElementType.I8:
745                                         WriteLong ((long)(long)v.Value);
746                                         break;
747                                 case ElementType.U8:
748                                         WriteLong ((long)(ulong)v.Value);
749                                         break;
750                                 case ElementType.R4:
751                                         WriteFloat ((float)v.Value);
752                                         break;
753                                 case ElementType.R8:
754                                         WriteDouble ((double)v.Value);
755                                         break;
756                                 case ElementType.String:
757                                 case ElementType.SzArray:
758                                 case ElementType.Class:
759                                 case ElementType.Array:
760                                 case ElementType.Object:
761                                         WriteId (v.Objid);
762                                         break;
763                                 case ElementType.ValueType:
764                                         // FIXME: 
765                                         if (v.IsEnum)
766                                                 throw new NotImplementedException ();
767                                         WriteByte (0);
768                                         WriteId (v.Klass);
769                                         WriteInt (v.Fields.Length);
770                                         for (int i = 0; i < v.Fields.Length; ++i)
771                                                 WriteValue (v.Fields [i]);
772                                         break;
773                                 case (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL:
774                                         break;
775                                 default:
776                                         throw new NotImplementedException ();
777                                 }
778
779                                 return this;
780                         }
781
782                         public PacketWriter WriteValues (ValueImpl[] values) {
783                                 for (int i = 0; i < values.Length; ++i)
784                                         WriteValue (values [i]);
785                                 return this;
786                         }
787
788                         public byte[] Data {
789                                 get {
790                                         return data;
791                                 }
792                         }
793
794                         public int Offset {
795                                 get {
796                                         return offset;
797                                 }
798                         }
799                 }
800
801                 delegate void ReplyCallback (int packet_id, byte[] packet);
802
803                 Socket socket;
804                 bool closed;
805                 Thread receiver_thread;
806                 Dictionary<int, byte[]> reply_packets;
807                 Dictionary<int, ReplyCallback> reply_cbs;
808                 object reply_packets_monitor;
809
810                 public event EventHandler<ErrorHandlerEventArgs> ErrorHandler;
811
812                 public Connection (Socket socket) {
813                         this.socket = socket;
814                         //socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.NoDelay, 1);
815                         closed = false;
816                         reply_packets = new Dictionary<int, byte[]> ();
817                         reply_cbs = new Dictionary<int, ReplyCallback> ();
818                         reply_packets_monitor = new Object ();
819                 }
820
821                 int Receive (byte[] buf, int buf_offset, int len) {
822                         int offset = 0;
823
824                         while (offset < len) {
825                                 int n = socket.Receive (buf, buf_offset + offset, len - offset, SocketFlags.None);
826
827                                 if (n == 0)
828                                         return offset;
829                                 offset += n;
830                         }
831
832                         return offset;
833                 }
834
835                 public VersionInfo Version;
836
837                 // Do the wire protocol handshake
838                 public void Connect () {
839                         byte[] buf = new byte [HANDSHAKE_STRING.Length];
840                         char[] cbuf = new char [buf.Length];
841
842                         // FIXME: Add a timeout
843                         int n = Receive (buf, 0, buf.Length);
844                         if (n == 0)
845                                 throw new IOException ("DWP Handshake failed.");
846                         for (int i = 0; i < buf.Length; ++i)
847                                 cbuf [i] = (char)buf [i];
848
849                         if (new String (cbuf) != HANDSHAKE_STRING)
850                                 throw new IOException ("DWP Handshake failed.");
851
852                         socket.Send (buf);
853
854                         receiver_thread = new Thread (new ThreadStart (receiver_thread_main));
855                         receiver_thread.Start ();
856
857                         Version = VM_GetVersion ();
858
859                         //
860                         // Tell the debuggee our protocol version, so newer debuggees can work
861                         // with older clients
862                         //
863
864                         //
865                         // Older debuggees might not support this request
866                         EventHandler<ErrorHandlerEventArgs> OrigErrorHandler = ErrorHandler;
867                         ErrorHandler = null;
868                         ErrorHandler += delegate (object sender, ErrorHandlerEventArgs args) {
869                                 throw new NotSupportedException ();
870                         };
871                         try {
872                                 VM_SetProtocolVersion (MAJOR_VERSION, MINOR_VERSION);
873                         } catch (NotSupportedException) {
874                         }
875                         ErrorHandler = OrigErrorHandler;
876                 }
877
878                 public EndPoint EndPoint {
879                         get {
880                                 return socket.RemoteEndPoint;
881                         }
882                 }
883
884                 public byte[] ReadPacket () {
885                         // FIXME: Throw ClosedConnectionException () if the connection is closed
886                         // FIXME: Throw ClosedConnectionException () if another thread closes the connection
887                         // FIXME: Locking
888                         byte[] header = new byte [HEADER_LENGTH];
889
890                         int len = Receive (header, 0, header.Length);
891                         if (len == 0)
892                                 return new byte [0];
893                         if (len != HEADER_LENGTH) {
894                                 // FIXME:
895                                 throw new IOException ("Packet of length " + len + " is read.");
896                         }
897
898                         int packetLength = GetPacketLength (header);
899                         if (packetLength < 11)
900                                 throw new IOException ("Invalid packet length.");
901
902                         if (packetLength == 11) {
903                                 return header;
904                         } else {
905                                 byte[] buf = new byte [packetLength];
906                                 for (int i = 0; i < header.Length; ++i)
907                                         buf [i] = header [i];
908                                 len = Receive (buf, header.Length, packetLength - header.Length);
909                                 if (len != packetLength - header.Length)
910                                         throw new IOException ();
911                                 return buf;
912                         }
913                 }
914
915                 public void WritePacket (byte[] packet) {
916                         // FIXME: Throw ClosedConnectionException () if the connection is closed
917                         // FIXME: Throw ClosedConnectionException () if another thread closes the connection
918                         // FIXME: Locking
919                         socket.Send (packet);
920                 }
921
922                 public void Close () {
923                         closed = true;
924                 }
925
926                 public bool IsClosed {
927                         get {
928                                 return closed;
929                         }
930                 }
931
932                 bool disconnected;
933
934                 void receiver_thread_main () {
935                         while (true) {
936                                 try {
937                                         bool res = ReceivePacket ();
938                                         if (!res)
939                                                 break;
940                                 } catch (Exception ex) {
941                                         Console.WriteLine (ex);
942                                         break;
943                                 }
944                         }
945
946                         lock (reply_packets_monitor) {
947                                 disconnected = true;
948                                 Monitor.PulseAll (reply_packets_monitor);
949                         }
950                         EventHandler.VMDisconnect (0, 0, null);
951                 }
952
953                 bool ReceivePacket () {
954                                 byte[] packet = ReadPacket ();
955
956                                 if (packet.Length == 0) {
957                                         return false;
958                                 }
959
960                                 if (IsReplyPacket (packet)) {
961                                         int id = GetPacketId (packet);
962                                         ReplyCallback cb = null;
963                                         lock (reply_packets_monitor) {
964                                                 reply_cbs.TryGetValue (id, out cb);
965                                                 if (cb == null) {
966                                                         reply_packets [id] = packet;
967                                                         Monitor.PulseAll (reply_packets_monitor);
968                                                 }
969                                         }
970
971                                         if (cb != null)
972                                                 cb.Invoke (id, packet);
973                                 } else {
974                                         PacketReader r = new PacketReader (packet);
975
976                                         if (r.CommandSet == CommandSet.EVENT && r.Command == (int)CmdEvent.COMPOSITE) {
977                                                 r.ReadByte (); // suspend_policy
978                                                 int nevents = r.ReadInt ();
979
980                                                 for (int i = 0; i < nevents; ++i) {
981                                                         EventKind kind = (EventKind)r.ReadByte ();
982                                                         int req_id = r.ReadInt ();
983
984                                                         if (kind == EventKind.VM_START) {
985                                                                 long thread_id = r.ReadId ();
986                                                                 EventHandler.VMStart (req_id, thread_id, null);
987                                                         } else if (kind == EventKind.VM_DEATH) {
988                                                                 EventHandler.VMDeath (req_id, 0, null);
989                                                         } else if (kind == EventKind.THREAD_START) {
990                                                                 long thread_id = r.ReadId ();
991                                                                 EventHandler.ThreadStart (req_id, thread_id, thread_id);
992                                                         } else if (kind == EventKind.THREAD_DEATH) {
993                                                                 long thread_id = r.ReadId ();
994                                                                 EventHandler.ThreadDeath (req_id, thread_id, thread_id);
995                                                         } else if (kind == EventKind.ASSEMBLY_LOAD) {
996                                                                 long thread_id = r.ReadId ();
997                                                                 long id = r.ReadId ();
998                                                                 EventHandler.AssemblyLoad (req_id, thread_id, id);
999                                                         } else if (kind == EventKind.ASSEMBLY_UNLOAD) {
1000                                                                 long thread_id = r.ReadId ();
1001                                                                 long id = r.ReadId ();
1002                                                                 EventHandler.AssemblyUnload (req_id, thread_id, id);
1003                                                         } else if (kind == EventKind.TYPE_LOAD) {
1004                                                                 long thread_id = r.ReadId ();
1005                                                                 long id = r.ReadId ();
1006                                                                 EventHandler.TypeLoad (req_id, thread_id, id);
1007                                                         } else if (kind == EventKind.METHOD_ENTRY) {
1008                                                                 long thread_id = r.ReadId ();
1009                                                                 long id = r.ReadId ();
1010                                                                 EventHandler.MethodEntry (req_id, thread_id, id);
1011                                                         } else if (kind == EventKind.METHOD_EXIT) {
1012                                                                 long thread_id = r.ReadId ();
1013                                                                 long id = r.ReadId ();
1014                                                                 EventHandler.MethodExit (req_id, thread_id, id);
1015                                                         } else if (kind == EventKind.BREAKPOINT) {
1016                                                                 long thread_id = r.ReadId ();
1017                                                                 long id = r.ReadId ();
1018                                                                 long loc = r.ReadLong ();
1019                                                                 EventHandler.Breakpoint (req_id, thread_id, id, loc);
1020                                                         } else if (kind == EventKind.STEP) {
1021                                                                 long thread_id = r.ReadId ();
1022                                                                 long id = r.ReadId ();
1023                                                                 long loc = r.ReadLong ();
1024                                                                 EventHandler.Step (req_id, thread_id, id, loc);
1025                                                         } else if (kind == EventKind.EXCEPTION) {
1026                                                                 long thread_id = r.ReadId ();
1027                                                                 long id = r.ReadId ();
1028                                                                 long loc = 0; // FIXME
1029                                                                 EventHandler.Exception (req_id, thread_id, id, loc);
1030                                                         } else if (kind == EventKind.APPDOMAIN_CREATE) {
1031                                                                 long thread_id = r.ReadId ();
1032                                                                 long id = r.ReadId ();
1033                                                                 EventHandler.AppDomainCreate (req_id, thread_id, id);
1034                                                         } else if (kind == EventKind.APPDOMAIN_UNLOAD) {
1035                                                                 long thread_id = r.ReadId ();
1036                                                                 long id = r.ReadId ();
1037                                                                 EventHandler.AppDomainUnload (req_id, thread_id, id);
1038                                                         } else {
1039                                                                 throw new NotImplementedException ("Unknown event kind: " + kind);
1040                                                         }
1041                                                 }
1042                                         }
1043                                 }
1044
1045                                 return true;
1046                 }
1047
1048                 public IEventHandler EventHandler {
1049                         get; set;
1050                 }
1051
1052                 /* Send a request and call cb when a result is received */
1053                 int Send (CommandSet command_set, int command, PacketWriter packet, Action<PacketReader> cb) {
1054                         int id = IdGenerator;
1055
1056                         lock (reply_packets_monitor) {
1057                                 reply_cbs [id] = delegate (int packet_id, byte[] p) {
1058                                         /* Run the callback on a tp thread to avoid blocking the receive thread */
1059                                         PacketReader r = new PacketReader (p);
1060                                         cb.BeginInvoke (r, null, null);
1061                                 };
1062                         }
1063                                                 
1064                         if (packet == null)
1065                                 WritePacket (EncodePacket (id, (int)command_set, command, null, 0));
1066                         else
1067                                 WritePacket (EncodePacket (id, (int)command_set, command, packet.Data, packet.Offset));
1068
1069                         return id;
1070                 }
1071
1072                 PacketReader SendReceive (CommandSet command_set, int command, PacketWriter packet) {
1073                         int id = IdGenerator;
1074
1075                         if (packet == null)
1076                                 WritePacket (EncodePacket (id, (int)command_set, command, null, 0));
1077                         else
1078                                 WritePacket (EncodePacket (id, (int)command_set, command, packet.Data, packet.Offset));
1079
1080                         int packetId = id;
1081
1082                         /* Wait for the reply packet */
1083                         while (true) {
1084                                 lock (reply_packets_monitor) {
1085                                         if (reply_packets.ContainsKey (packetId)) {
1086                                                 byte[] reply = reply_packets [packetId];
1087                                                 reply_packets.Remove (packetId);
1088                                                 PacketReader r = new PacketReader (reply);
1089                                                 if (r.ErrorCode != 0) {
1090                                                         if (ErrorHandler != null)
1091                                                                 ErrorHandler (this, new ErrorHandlerEventArgs () { ErrorCode = (ErrorCode)r.ErrorCode });
1092                                                         throw new NotImplementedException ("No error handler set.");
1093                                                 } else {
1094                                                         return r;
1095                                                 }
1096                                         } else {
1097                                                 if (disconnected)
1098                                                         throw new VMDisconnectedException ();
1099                                                 Monitor.Wait (reply_packets_monitor);
1100                                         }
1101                                 }
1102                         }
1103                 }
1104
1105                 PacketReader SendReceive (CommandSet command_set, int command) {
1106                         return SendReceive (command_set, command, null);
1107                 }
1108
1109                 int packet_id_generator;
1110
1111                 int IdGenerator {
1112                         get {
1113                                 return Interlocked.Increment (ref packet_id_generator);
1114                         }
1115                 }
1116
1117                 CattrInfo[] ReadCattrs (PacketReader r) {
1118                         CattrInfo[] res = new CattrInfo [r.ReadInt ()];
1119                         for (int i = 0; i < res.Length; ++i) {
1120                                 CattrInfo info = new CattrInfo ();
1121                                 info.ctor_id = r.ReadId ();
1122                                 info.ctor_args = new ValueImpl [r.ReadInt ()];
1123                                 for (int j = 0; j < info.ctor_args.Length; ++j) {
1124                                         info.ctor_args [j] = r.ReadValue ();
1125                                 }
1126                                 info.named_args = new CattrNamedArgInfo [r.ReadInt ()];
1127                                 for (int j = 0; j < info.named_args.Length; ++j) {
1128                                         CattrNamedArgInfo arg = new CattrNamedArgInfo ();
1129                                         int arg_type = r.ReadByte ();
1130                                         arg.is_property = arg_type == 0x54;
1131                                         arg.id = r.ReadId ();
1132                                         arg.value = r.ReadValue ();
1133                                         info.named_args [j] = arg;
1134                                 }
1135                                 res [i] = info;
1136                         }
1137                         return res;
1138                 }
1139
1140                 static ElementType TypeCodeToElementType (TypeCode c) {
1141                         switch (c) {
1142                         case TypeCode.Boolean:
1143                                 return ElementType.Boolean;
1144                         case TypeCode.Char:
1145                                 return ElementType.Char;
1146                         case TypeCode.SByte:
1147                                 return ElementType.I1;
1148                         case TypeCode.Byte:
1149                                 return ElementType.U1;
1150                         case TypeCode.Int16:
1151                                 return ElementType.I2;
1152                         case TypeCode.UInt16:
1153                                 return ElementType.U2;
1154                         case TypeCode.Int32:
1155                                 return ElementType.I4;
1156                         case TypeCode.UInt32:
1157                                 return ElementType.U4;
1158                         case TypeCode.Int64:
1159                                 return ElementType.I8;
1160                         case TypeCode.UInt64:
1161                                 return ElementType.U8;
1162                         case TypeCode.Single:
1163                                 return ElementType.R4;
1164                         case TypeCode.Double:
1165                                 return ElementType.R8;
1166                         default:
1167                                 throw new NotImplementedException ();
1168                         }
1169                 }
1170
1171                 /*
1172                  * Implementation of debugger commands
1173                  */
1174
1175                 public VersionInfo VM_GetVersion () {
1176                         var res = SendReceive (CommandSet.VM, (int)CmdVM.VERSION, null);
1177                         VersionInfo info = new VersionInfo ();
1178                         info.VMVersion = res.ReadString ();
1179                         info.MajorVersion = res.ReadInt ();
1180                         info.MinorVersion = res.ReadInt ();
1181                         return info;
1182                 }
1183
1184                 public void VM_SetProtocolVersion (int major, int minor) {
1185                         SendReceive (CommandSet.VM, (int)CmdVM.SET_PROTOCOL_VERSION, new PacketWriter ().WriteInt (major).WriteInt (minor));
1186                 }
1187
1188                 public long[] VM_GetThreads () {
1189                         var res = SendReceive (CommandSet.VM, (int)CmdVM.ALL_THREADS, null);
1190                         int len = res.ReadInt ();
1191                         long[] arr = new long [len];
1192                         for (int i = 0; i < len; ++i)
1193                                 arr [i] = res.ReadId ();
1194                         return arr;
1195                 }
1196
1197                 public void VM_Suspend () {
1198                         SendReceive (CommandSet.VM, (int)CmdVM.SUSPEND);
1199                 }
1200
1201                 public void VM_Resume () {
1202                         SendReceive (CommandSet.VM, (int)CmdVM.RESUME);
1203                 }
1204
1205                 public void VM_Exit (int exitCode) {
1206                         SendReceive (CommandSet.VM, (int)CmdVM.EXIT, new PacketWriter ().WriteInt (exitCode));
1207                 }
1208
1209                 public void VM_Dispose () {
1210                         SendReceive (CommandSet.VM, (int)CmdVM.DISPOSE);
1211                 }
1212
1213                 public ValueImpl VM_InvokeMethod (long thread, long method, ValueImpl this_arg, ValueImpl[] arguments, InvokeFlags flags, out ValueImpl exc) {
1214                         exc = null;
1215                         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));
1216                         if (r.ReadByte () == 0) {
1217                                 exc = r.ReadValue ();
1218                                 return null;
1219                         } else {
1220                                 return r.ReadValue ();
1221                         }
1222                 }
1223
1224                 public delegate void InvokeMethodCallback (ValueImpl v, ValueImpl exc, ErrorCode error, object state);
1225
1226                 public int VM_BeginInvokeMethod (long thread, long method, ValueImpl this_arg, ValueImpl[] arguments, InvokeFlags flags, InvokeMethodCallback callback, object state) {
1227                         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) {
1228                                         ValueImpl v, exc;
1229
1230                                         if (r.ErrorCode != 0) {
1231                                                 callback (null, null, (ErrorCode)r.ErrorCode, state);
1232                                         } else {
1233                                                 if (r.ReadByte () == 0) {
1234                                                         exc = r.ReadValue ();
1235                                                         v = null;
1236                                                 } else {
1237                                                         v = r.ReadValue ();
1238                                                         exc = null;
1239                                                 }
1240
1241                                                 callback (v, exc, 0, state);
1242                                         }
1243                                 });
1244                 }
1245
1246                 public void VM_AbortInvoke (long thread, int id)
1247                 {
1248                         SendReceive (CommandSet.VM, (int)CmdVM.ABORT_INVOKE, new PacketWriter ().WriteId (thread).WriteInt (id));
1249                 }
1250
1251                 /*
1252                  * DOMAIN
1253                  */
1254
1255                 public long RootDomain {
1256                         get {
1257                                 return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_ROOT_DOMAIN, null).ReadId ();
1258                         }
1259                 }
1260
1261                 public string Domain_GetName (long id) {
1262                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_FRIENDLY_NAME, new PacketWriter ().WriteId (id)).ReadString ();
1263                 }
1264
1265                 public long[] Domain_GetAssemblies (long id) {
1266                         var res = SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_ASSEMBLIES, new PacketWriter ().WriteId (id));
1267                         int count = res.ReadInt ();
1268                         long[] assemblies = new long [count];
1269                         for (int i = 0; i < count; ++i)
1270                                 assemblies [i] = res.ReadId ();
1271                         return assemblies;
1272                 }
1273
1274                 public long Domain_GetEntryAssembly (long id) {
1275                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_ENTRY_ASSEMBLY, new PacketWriter ().WriteId (id)).ReadId ();
1276                 }
1277
1278                 public long Domain_GetCorlib (long id) {
1279                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.GET_CORLIB, new PacketWriter ().WriteId (id)).ReadId ();
1280                 }
1281
1282                 public long Domain_CreateString (long id, string s) {
1283                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.CREATE_STRING, new PacketWriter ().WriteId (id).WriteString (s)).ReadId ();
1284                 }
1285
1286                 public long Domain_CreateBoxedValue (long id, long type_id, ValueImpl v) {
1287                         return SendReceive (CommandSet.APPDOMAIN, (int)CmdAppDomain.CREATE_BOXED_VALUE, new PacketWriter ().WriteId (id).WriteId (type_id).WriteValue (v)).ReadId ();
1288                 }
1289
1290                 /*
1291                  * METHOD
1292                  */
1293
1294                 public string Method_GetName (long id) {
1295                         return SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_NAME, new PacketWriter ().WriteId (id)).ReadString ();
1296                 }
1297
1298                 public long Method_GetDeclaringType (long id) {
1299                         return SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_DECLARING_TYPE, new PacketWriter ().WriteId (id)).ReadId ();
1300                 }
1301
1302                 public DebugInfo Method_GetDebugInfo (long id) {
1303                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_DEBUG_INFO, new PacketWriter ().WriteId (id));
1304
1305                         DebugInfo info = new DebugInfo ();
1306                         info.max_il_offset = res.ReadInt ();
1307                         info.filename = res.ReadString ();
1308
1309                         int n_il_offsets = res.ReadInt ();
1310                         info.il_offsets = new int [n_il_offsets];
1311                         info.line_numbers = new int [n_il_offsets];
1312                         for (int i = 0; i < n_il_offsets; ++i) {
1313                                 info.il_offsets [i] = res.ReadInt ();
1314                                 info.line_numbers [i] = res.ReadInt ();
1315                         }
1316
1317                         return info;
1318                 }
1319
1320                 public ParamInfo Method_GetParamInfo (long id) {
1321                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_PARAM_INFO, new PacketWriter ().WriteId (id));
1322
1323                         ParamInfo info = new ParamInfo ();
1324                         info.call_conv = res.ReadInt ();
1325                         info.param_count = res.ReadInt ();
1326                         info.generic_param_count = res.ReadInt ();
1327                         info.ret_type = res.ReadId ();
1328                         info.param_types = new long [info.param_count];
1329                         for (int i = 0; i < info.param_count; ++i)
1330                                 info.param_types [i] = res.ReadId ();
1331                         info.param_names = new string [info.param_count];                       
1332                         for (int i = 0; i < info.param_count; ++i)
1333                                 info.param_names [i] = res.ReadString ();
1334
1335                         return info;
1336                 }
1337
1338                 public LocalsInfo Method_GetLocalsInfo (long id) {
1339                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_LOCALS_INFO, new PacketWriter ().WriteId (id));
1340
1341                         LocalsInfo info = new LocalsInfo ();
1342                         int nlocals = res.ReadInt ();
1343                         info.types = new long [nlocals];
1344                         for (int i = 0; i < nlocals; ++i)
1345                                 info.types [i] = res.ReadId ();
1346                         info.names = new string [nlocals];
1347                         for (int i = 0; i < nlocals; ++i)
1348                                 info.names [i] = res.ReadString ();
1349                         info.live_range_start = new int [nlocals];
1350                         info.live_range_end = new int [nlocals];
1351                         for (int i = 0; i < nlocals; ++i) {
1352                                 info.live_range_start [i] = res.ReadInt ();
1353                                 info.live_range_end [i] = res.ReadInt ();
1354                         }
1355
1356                         return info;
1357                 }
1358
1359                 public MethodInfo Method_GetInfo (long id) {
1360                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_INFO, new PacketWriter ().WriteId (id));
1361
1362                         MethodInfo info = new MethodInfo ();
1363                         info.attributes = res.ReadInt ();
1364                         info.iattributes = res.ReadInt ();
1365                         info.token = res.ReadInt ();
1366
1367                         return info;
1368                 }
1369
1370                 public MethodBodyInfo Method_GetBody (long id) {
1371                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.GET_BODY, new PacketWriter ().WriteId (id));
1372
1373                         MethodBodyInfo info = new MethodBodyInfo ();
1374                         info.il = new byte [res.ReadInt ()];
1375                         for (int i = 0; i < info.il.Length; ++i)
1376                                 info.il [i] = (byte)res.ReadByte ();
1377
1378                         return info;
1379                 }
1380
1381                 public ResolvedToken Method_ResolveToken (long id, int token) {
1382                         var res = SendReceive (CommandSet.METHOD, (int)CmdMethod.RESOLVE_TOKEN, new PacketWriter ().WriteId (id).WriteInt (token));
1383
1384                         TokenType type = (TokenType)res.ReadByte ();
1385                         switch (type) {
1386                         case TokenType.STRING:
1387                                 return new ResolvedToken () { Type = type, Str = res.ReadString () };
1388                         case TokenType.TYPE:
1389                         case TokenType.METHOD:
1390                         case TokenType.FIELD:
1391                                 return new ResolvedToken () { Type = type, Id = res.ReadId () };
1392                         case TokenType.UNKNOWN:
1393                                 return new ResolvedToken () { Type = type };
1394                         default:
1395                                 throw new NotImplementedException ();
1396                         }
1397                 }
1398
1399                 /*
1400                  * THREAD
1401                  */
1402
1403                 public string Thread_GetName (long id) {
1404                         return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_NAME, new PacketWriter ().WriteId (id)).ReadString ();
1405                 }
1406
1407                 public FrameInfo[] Thread_GetFrameInfo (long id, int start_frame, int length) {
1408                         var res = SendReceive (CommandSet.THREAD, (int)CmdThread.GET_FRAME_INFO, new PacketWriter ().WriteId (id).WriteInt (start_frame).WriteInt (length));
1409                         int count = res.ReadInt ();
1410
1411                         var frames = new FrameInfo [count];
1412                         for (int i = 0; i < count; ++i) {
1413                                 frames [i].id = res.ReadInt ();
1414                                 frames [i].method = res.ReadId ();
1415                                 frames [i].il_offset = res.ReadInt ();
1416                                 frames [i].flags = (StackFrameFlags)res.ReadByte ();
1417                         }
1418                         return frames;
1419                 }
1420
1421                 public int Thread_GetState (long id) {
1422                         return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_STATE, new PacketWriter ().WriteId (id)).ReadInt ();
1423                 }
1424
1425                 public ThreadInfo Thread_GetInfo (long id) {
1426                         PacketReader r = SendReceive (CommandSet.THREAD, (int)CmdThread.GET_INFO, new PacketWriter ().WriteId (id));
1427
1428                         ThreadInfo res = new ThreadInfo () { is_thread_pool = r.ReadByte () > 0 ? true : false };
1429
1430                         return res;
1431                 }
1432
1433                 /*
1434                  * MODULE
1435                  */
1436
1437                 public ModuleInfo Module_GetInfo (long id) {
1438                         PacketReader r = SendReceive (CommandSet.MODULE, (int)CmdModule.GET_INFO, new PacketWriter ().WriteId (id));
1439                         ModuleInfo info = new ModuleInfo { Name = r.ReadString (), ScopeName = r.ReadString (), FQName = r.ReadString (), Guid = r.ReadString (), Assembly = r.ReadId () };
1440                         return info;
1441                 }
1442
1443                 /*
1444                  * ASSEMBLY
1445                  */
1446
1447                 public string Assembly_GetLocation (long id) {
1448                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_LOCATION, new PacketWriter ().WriteId (id)).ReadString ();
1449                 }
1450
1451                 public long Assembly_GetEntryPoint (long id) {
1452                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_ENTRY_POINT, new PacketWriter ().WriteId (id)).ReadId ();
1453                 }
1454
1455                 public long Assembly_GetManifestModule (long id) {
1456                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_MANIFEST_MODULE, new PacketWriter ().WriteId (id)).ReadId ();
1457                 }
1458
1459                 public long Assembly_GetObject (long id) {
1460                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_OBJECT, new PacketWriter ().WriteId (id)).ReadId ();
1461                 }
1462
1463                 public long Assembly_GetType (long id, string name, bool ignoreCase) {
1464                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_TYPE, new PacketWriter ().WriteId (id).WriteString (name).WriteBool (ignoreCase)).ReadId ();
1465                 }
1466
1467                 public string Assembly_GetName (long id) {
1468                         return SendReceive (CommandSet.ASSEMBLY, (int)CmdAssembly.GET_NAME, new PacketWriter ().WriteId (id)).ReadString ();
1469                 }
1470
1471                 /*
1472                  * TYPE
1473                  */
1474
1475                 public TypeInfo Type_GetInfo (long id) {
1476                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_INFO, new PacketWriter ().WriteId (id));
1477                         TypeInfo res = new TypeInfo ();
1478
1479                         res.ns = r.ReadString ();
1480                         res.name = r.ReadString ();
1481                         res.full_name = r.ReadString ();
1482                         res.assembly = r.ReadId ();
1483                         res.module = r.ReadId ();
1484                         res.base_type = r.ReadId ();
1485                         res.element_type = r.ReadId ();
1486                         res.token = r.ReadInt ();
1487                         res.rank = r.ReadByte ();
1488                         res.attributes = r.ReadInt ();
1489                         int b = r.ReadByte ();
1490                         res.is_byref = (b & 1) != 0;
1491                         res.is_pointer = (b & 2) != 0;
1492                         res.is_primitive = (b & 4) != 0;
1493                         res.is_valuetype = (b & 8) != 0;
1494                         res.is_enum = (b & 16) != 0;
1495
1496                         int nested_len = r.ReadInt ();
1497                         res.nested = new long [nested_len];
1498                         for (int i = 0; i < nested_len; ++i)
1499                                 res.nested [i] = r.ReadId ();
1500
1501                         return res;
1502                 }
1503
1504                 public long[] Type_GetMethods (long id) {
1505                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_METHODS, new PacketWriter ().WriteId (id));
1506
1507                         int n = r.ReadInt ();
1508                         long[] res = new long [n];
1509                         for (int i = 0; i < n; ++i)
1510                                 res [i] = r.ReadId ();
1511                         return res;
1512                 }
1513
1514                 public long[] Type_GetFields (long id, out string[] names, out long[] types, out int[] attrs) {
1515                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_FIELDS, new PacketWriter ().WriteId (id));
1516
1517                         int n = r.ReadInt ();
1518                         long[] res = new long [n];
1519                         names = new string [n];
1520                         types = new long [n];
1521                         attrs = new int [n];
1522                         for (int i = 0; i < n; ++i) {
1523                                 res [i] = r.ReadId ();
1524                                 names [i] = r.ReadString ();
1525                                 types [i] = r.ReadId ();
1526                                 attrs [i] = r.ReadInt ();
1527                         }
1528                         return res;
1529                 }
1530
1531                 public PropInfo[] Type_GetProperties (long id) {
1532                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_PROPERTIES, new PacketWriter ().WriteId (id));
1533
1534                         int n = r.ReadInt ();
1535                         PropInfo[] res = new PropInfo [n];
1536                         for (int i = 0; i < n; ++i) {
1537                                 res [i] = new PropInfo ();
1538                                 res [i].id = r.ReadId ();
1539                                 res [i].name = r.ReadString ();
1540                                 res [i].get_method = r.ReadId ();
1541                                 res [i].set_method = r.ReadId ();
1542                                 res [i].attrs = r.ReadInt ();
1543                         }
1544
1545                         return res;
1546                 }
1547
1548                 public long Type_GetObject (long id) {
1549                         return SendReceive (CommandSet.TYPE, (int)CmdType.GET_OBJECT, new PacketWriter ().WriteId (id)).ReadId ();
1550                 }
1551
1552                 public ValueImpl[] Type_GetValues (long id, long[] fields) {
1553                         int len = fields.Length;
1554                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_VALUES, new PacketWriter ().WriteId (id).WriteInt (len).WriteIds (fields));
1555
1556                         ValueImpl[] res = new ValueImpl [len];
1557                         for (int i = 0; i < len; ++i)
1558                                 res [i] = r.ReadValue ();
1559                         return res;
1560                 }                       
1561
1562                 public void Type_SetValues (long id, long[] fields, ValueImpl[] values) {
1563                         SendReceive (CommandSet.TYPE, (int)CmdType.SET_VALUES, new PacketWriter ().WriteId (id).WriteInt (fields.Length).WriteIds (fields).WriteValues (values));
1564                 }
1565
1566                 public string[] Type_GetSourceFiles (long id) {
1567                         var r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_SOURCE_FILES, new PacketWriter ().WriteId (id));
1568                         int len = r.ReadInt ();
1569                         string[] res = new string [len];
1570                         for (int i = 0; i < len; ++i)
1571                                 res [i] = r.ReadString ();
1572                         return res;
1573                 }
1574
1575                 public bool Type_IsAssignableFrom (long id, long c_id) {
1576                         return SendReceive (CommandSet.TYPE, (int)CmdType.IS_ASSIGNABLE_FROM, new PacketWriter ().WriteId (id).WriteId (c_id)).ReadByte () > 0;
1577                 }
1578
1579                 public CattrInfo[] Type_GetCustomAttributes (long id, long attr_type_id, bool inherit) {
1580                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_CATTRS, new PacketWriter ().WriteId (id).WriteId (attr_type_id));
1581                         return ReadCattrs (r);
1582                 }
1583
1584                 public CattrInfo[] Type_GetFieldCustomAttributes (long id, long field_id, long attr_type_id, bool inherit) {
1585                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_FIELD_CATTRS, new PacketWriter ().WriteId (id).WriteId (field_id).WriteId (attr_type_id));
1586                         return ReadCattrs (r);
1587                 }
1588
1589                 public CattrInfo[] Type_GetPropertyCustomAttributes (long id, long field_id, long attr_type_id, bool inherit) {
1590                         PacketReader r = SendReceive (CommandSet.TYPE, (int)CmdType.GET_PROPERTY_CATTRS, new PacketWriter ().WriteId (id).WriteId (field_id).WriteId (attr_type_id));
1591                         return ReadCattrs (r);
1592                 }
1593                         
1594                 /*
1595                  * EVENTS
1596                  */
1597
1598                 public int EnableEvent (EventType etype, SuspendPolicy suspend_policy, List<Modifier> mods) {
1599                         var w = new PacketWriter ().WriteByte ((byte)etype).WriteByte ((byte)suspend_policy);
1600                         if (mods != null) {
1601                                 if (mods.Count > 255)
1602                                         throw new NotImplementedException ();
1603                                 w.WriteByte ((byte)mods.Count);
1604                                 foreach (Modifier mod in mods) {
1605                                         if (mod is CountModifier) {
1606                                                 w.WriteByte ((byte)ModifierKind.COUNT);
1607                                                 w.WriteInt ((mod as CountModifier).Count);
1608                                         } else if (mod is LocationModifier) {
1609                                                 w.WriteByte ((byte)ModifierKind.LOCATION_ONLY);
1610                                                 w.WriteId ((mod as LocationModifier).Method);
1611                                                 w.WriteLong ((mod as LocationModifier).Location);
1612                                         } else if (mod is StepModifier) {
1613                                                 w.WriteByte ((byte)ModifierKind.STEP);
1614                                                 w.WriteId ((mod as StepModifier).Thread);
1615                                                 w.WriteInt ((mod as StepModifier).Size);
1616                                                 w.WriteInt ((mod as StepModifier).Depth);
1617                                         } else if (mod is ThreadModifier) {
1618                                                 w.WriteByte ((byte)ModifierKind.THREAD_ONLY);
1619                                                 w.WriteId ((mod as ThreadModifier).Thread);
1620                                         } else if (mod is ExceptionModifier) {
1621                                                 var em = mod as ExceptionModifier;
1622                                                 w.WriteByte ((byte)ModifierKind.EXCEPTION_ONLY);
1623                                                 w.WriteId (em.Type);
1624                                                 if (Version.MajorVersion > 2 || Version.MinorVersion > 0) {
1625                                                         /* This is only supported in protocol version 2.1 */
1626                                                         w.WriteBool (em.Caught);
1627                                                         w.WriteBool (em.Uncaught);
1628                                                 } else if (!em.Caught || !em.Uncaught) {
1629                                                         throw new NotSupportedException ("This request is not supported by the protocol version implemented by the debuggee.");
1630                                                 }
1631                                         } else if (mod is AssemblyModifier) {
1632                                                 w.WriteByte ((byte)ModifierKind.ASSEMBLY_ONLY);
1633                                                 var amod = (mod as AssemblyModifier);
1634                                                 w.WriteInt (amod.Assemblies.Length);
1635                                                 foreach (var id in amod.Assemblies)
1636                                                         w.WriteId (id);
1637                                         } else {
1638                                                 throw new NotImplementedException ();
1639                                         }
1640                                 }
1641                         } else {
1642                                 w.WriteByte (0);
1643                         }
1644                         return SendReceive (CommandSet.EVENT_REQUEST, (int)CmdEventRequest.SET, w).ReadInt ();
1645                 }
1646
1647                 public void ClearEventRequest (EventType etype, int req_id) {
1648                         SendReceive (CommandSet.EVENT_REQUEST, (int)CmdEventRequest.CLEAR, new PacketWriter ().WriteByte ((byte)etype).WriteInt (req_id));
1649                 }                       
1650
1651                 public void ClearAllBreakpoints () {
1652                         SendReceive (CommandSet.EVENT_REQUEST, (int)CmdEventRequest.CLEAR_ALL_BREAKPOINTS, new PacketWriter ());
1653                 }
1654                         
1655                 /*
1656                  * STACK FRAME
1657                  */
1658                 public ValueImpl StackFrame_GetThis (long thread_id, long id) {
1659                         PacketReader r = SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.GET_THIS, new PacketWriter ().WriteId (thread_id).WriteId (id));
1660                         return r.ReadValue ();
1661                 }
1662
1663                 public ValueImpl[] StackFrame_GetValues (long thread_id, long id, int[] pos) {
1664                         /* pos < 0 -> argument at pos (-pos) - 1 */
1665                         /* pos >= 0 -> local at pos */
1666                         int len = pos.Length;
1667                         PacketReader r = SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.GET_VALUES, new PacketWriter ().WriteId (thread_id).WriteId (id).WriteInt (len).WriteInts (pos));
1668
1669                         ValueImpl[] res = new ValueImpl [len];
1670                         for (int i = 0; i < len; ++i)
1671                                 res [i] = r.ReadValue ();
1672                         return res;
1673                 }
1674
1675                 public void StackFrame_SetValues (long thread_id, long id, int[] pos, ValueImpl[] values) {
1676                         /* pos < 0 -> argument at pos (-pos) - 1 */
1677                         /* pos >= 0 -> local at pos */
1678                         int len = pos.Length;
1679                         SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.SET_VALUES, new PacketWriter ().WriteId (thread_id).WriteId (id).WriteInt (len).WriteInts (pos).WriteValues (values));
1680                 }
1681
1682                 /*
1683                  * ARRAYS
1684                  */
1685                 public int[] Array_GetLength (long id, out int rank, out int[] lower_bounds) {
1686                         var r = SendReceive (CommandSet.ARRAY_REF, (int)CmdArrayRef.GET_LENGTH, new PacketWriter ().WriteId (id));
1687                         rank = r.ReadInt ();
1688                         int[] res = new int [rank];
1689                         lower_bounds = new int [rank];
1690                         for (int i = 0; i < rank; ++i) {
1691                                 res [i] = r.ReadInt ();
1692                                 lower_bounds [i] = r.ReadInt ();
1693                         }
1694                         return res;
1695                 }
1696
1697                 public ValueImpl[] Array_GetValues (long id, int index, int len) {
1698                         var r = SendReceive (CommandSet.ARRAY_REF, (int)CmdArrayRef.GET_VALUES, new PacketWriter ().WriteId (id).WriteInt (index).WriteInt (len));
1699                         ValueImpl[] res = new ValueImpl [len];
1700                         for (int i = 0; i < len; ++i)
1701                                 res [i] = r.ReadValue ();
1702                         return res;
1703                 }
1704
1705                 public void Array_SetValues (long id, int index, ValueImpl[] values) {
1706                         SendReceive (CommandSet.ARRAY_REF, (int)CmdArrayRef.SET_VALUES, new PacketWriter ().WriteId (id).WriteInt (index).WriteInt (values.Length).WriteValues (values));
1707                 }
1708
1709                 /*
1710                  * STRINGS
1711                  */
1712                 public string String_GetValue (long id) {
1713                         return SendReceive (CommandSet.STRING_REF, (int)CmdStringRef.GET_VALUE, new PacketWriter ().WriteId (id)).ReadString ();
1714                 }                       
1715
1716                 /*
1717                  * OBJECTS
1718                  */
1719                 public long Object_GetType (long id) {
1720                         return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_TYPE, new PacketWriter ().WriteId (id)).ReadId ();
1721                 }                       
1722
1723                 public long Object_GetDomain (long id) {
1724                         return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_DOMAIN, new PacketWriter ().WriteId (id)).ReadId ();
1725                 }                       
1726
1727                 public ValueImpl[] Object_GetValues (long id, long[] fields) {
1728                         int len = fields.Length;
1729                         PacketReader r = SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_VALUES, new PacketWriter ().WriteId (id).WriteInt (len).WriteIds (fields));
1730
1731                         ValueImpl[] res = new ValueImpl [len];
1732                         for (int i = 0; i < len; ++i)
1733                                 res [i] = r.ReadValue ();
1734                         return res;
1735                 }
1736
1737                 public void Object_SetValues (long id, long[] fields, ValueImpl[] values) {
1738                         SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.SET_VALUES, new PacketWriter ().WriteId (id).WriteInt (fields.Length).WriteIds (fields).WriteValues (values));
1739                 }
1740
1741                 public bool Object_IsCollected (long id) {
1742                         return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.IS_COLLECTED, new PacketWriter ().WriteId (id)).ReadInt () == 1;
1743                 }                       
1744
1745                 public long Object_GetAddress (long id) {
1746                         return SendReceive (CommandSet.OBJECT_REF, (int)CmdObjectRef.GET_ADDRESS, new PacketWriter ().WriteId (id)).ReadLong ();
1747                 }                       
1748
1749         }
1750
1751         /* This is the interface exposed by the debugger towards the debugger agent */
1752         interface IEventHandler
1753         {
1754                 void VMStart (int req_id, long thread_id, string vm_uri);
1755
1756                 void VMDeath (int req_id, long thread_id, string vm_uri);
1757
1758                 void VMDisconnect (int req_id, long thread_id, string vm_uri);
1759
1760                 void ThreadStart (int req_id, long thread_id, long id);
1761
1762                 void ThreadDeath (int req_id, long thread_id, long id);
1763
1764                 void AssemblyLoad (int req_id, long thread_id, long id);
1765
1766                 void AssemblyUnload (int req_id, long thread_id, long id);
1767
1768                 void TypeLoad (int req_id, long thread_id, long id);
1769
1770                 void MethodEntry (int req_id, long thread_id, long id);
1771
1772                 void MethodExit (int req_id, long thread_id, long id);
1773
1774                 void Breakpoint (int req_id, long thread_id, long method_id, long loc);
1775
1776                 void Step (int req_id, long thread_id, long method_id, long loc);
1777
1778                 void Exception (int req_id, long thread_id, long exc_id, long loc);
1779
1780                 void AppDomainCreate (int req_id, long thread_id, long id);
1781
1782                 void AppDomainUnload (int req_id, long thread_id, long id);
1783         }
1784 }