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