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