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