Merge pull request #186 from QuickJack/master
[mono.git] / mcs / class / Mono.Debugger.Soft / Mono.Debugger.Soft / VirtualMachine.cs
1 using System;
2 using System.IO;
3 using System.Threading;
4 using System.Net;
5 using System.Diagnostics;
6 using System.Collections;
7 using System.Collections.Generic;
8 using Mono.Cecil.Metadata;
9
10 namespace Mono.Debugger.Soft
11 {
12         public class VirtualMachine : Mirror
13         {
14                 Queue queue;
15                 object queue_monitor;
16                 object startup_monitor;
17                 AppDomainMirror root_domain;
18                 Dictionary<int, EventRequest> requests;
19                 ITargetProcess process;
20
21                 internal Connection conn;
22
23                 VersionInfo version;
24
25                 internal VirtualMachine (ITargetProcess process, Connection conn) : base () {
26                         SetVirtualMachine (this);
27                         queue = new Queue ();
28                         queue_monitor = new Object ();
29                         startup_monitor = new Object ();
30                         requests = new Dictionary <int, EventRequest> ();
31                         this.conn = conn;
32                         this.process = process;
33                         conn.ErrorHandler += ErrorHandler;
34                 }
35
36                 // The standard output of the process is available normally through Process
37                 public StreamReader StandardOutput { get; set; }
38                 public StreamReader StandardError { get; set; }
39
40                 
41                 public Process Process {
42                         get {
43                                 ProcessWrapper pw = process as ProcessWrapper;
44                                 if (pw == null)
45                                     throw new InvalidOperationException ("Process instance not available");
46                                 return pw.Process;
47                         }
48                 }
49
50                 public ITargetProcess TargetProcess {
51                         get {
52                                 return process;
53                         }
54                 }
55
56                 public AppDomainMirror RootDomain {
57                         get {
58                                 return root_domain;
59                         }
60             }
61
62                 public EndPoint EndPoint {
63                         get {
64                                 var tcpConn = conn as TcpConnection;
65                                 if (tcpConn != null)
66                                         return tcpConn.EndPoint;
67                                 return null;
68                         }
69                 }
70
71                 public VersionInfo Version {
72                         get {
73                                 return version;
74                         }
75                 }
76
77                 EventSet current_es;
78                 int current_es_index;
79
80                 /*
81                  * It is impossible to determine when to resume when using this method, since
82                  * the debuggee is suspended only once per event-set, not event.
83                  */
84                 [Obsolete ("Use GetNextEventSet () instead")]
85                 public Event GetNextEvent () {
86                         lock (queue_monitor) {
87                                 if (current_es == null || current_es_index == current_es.Events.Length) {
88                                         if (queue.Count == 0)
89                                                 Monitor.Wait (queue_monitor);
90                                         current_es = (EventSet)queue.Dequeue ();
91                                         current_es_index = 0;
92                                 }
93                                 return current_es.Events [current_es_index ++];
94                         }
95                 }
96
97                 public Event GetNextEvent (int timeout) {
98                         throw new NotImplementedException ();
99                 }
100
101                 public EventSet GetNextEventSet () {
102                         lock (queue_monitor) {
103                                 if (queue.Count == 0)
104                                         Monitor.Wait (queue_monitor);
105
106                                 current_es = null;
107                                 current_es_index = 0;
108
109                                 return (EventSet)queue.Dequeue ();
110                         }
111                 }
112
113                 [Obsolete ("Use GetNextEventSet () instead")]
114                 public T GetNextEvent<T> () where T : Event {
115                         return GetNextEvent () as T;
116                 }
117
118                 public void Suspend () {
119                         conn.VM_Suspend ();
120             }
121
122                 public void Resume () {
123                         try {
124                                 conn.VM_Resume ();
125                         } catch (CommandException ex) {
126                                 if (ex.ErrorCode == ErrorCode.NOT_SUSPENDED)
127                                         throw new InvalidOperationException ("The vm is not suspended.");
128                                 else
129                                         throw;
130                         }
131             }
132
133                 public void Exit (int exitCode) {
134                         conn.VM_Exit (exitCode);
135                 }
136
137                 public void Dispose () {
138                         conn.VM_Dispose ();
139                         conn.Close ();
140                         notify_vm_event (EventType.VMDisconnect, SuspendPolicy.None, 0, 0, null);
141                 }
142
143                 public IList<ThreadMirror> GetThreads () {
144                         long[] ids = vm.conn.VM_GetThreads ();
145                         ThreadMirror[] res = new ThreadMirror [ids.Length];
146                         for (int i = 0; i < ids.Length; ++i)
147                                 res [i] = GetThread (ids [i]);
148                         return res;
149                 }
150
151                 // Same as the mirrorOf methods in JDI
152                 public PrimitiveValue CreateValue (object value) {
153                         if (value == null)
154                                 return new PrimitiveValue (vm, null);
155
156                         if (!value.GetType ().IsPrimitive)
157                                 throw new ArgumentException ("value must be of a primitive type instead of '" + value.GetType () + "'", "value");
158
159                         return new PrimitiveValue (vm, value);
160                 }
161
162                 public EnumMirror CreateEnumMirror (TypeMirror type, PrimitiveValue value) {
163                         return new EnumMirror (this, type, value);
164                 }
165
166                 //
167                 // Enable send and receive timeouts on the connection and send a keepalive event
168                 // every 'keepalive_interval' milliseconds.
169                 //
170
171                 public void SetSocketTimeouts (int send_timeout, int receive_timeout, int keepalive_interval)
172                 {
173                         conn.SetSocketTimeouts (send_timeout, receive_timeout, keepalive_interval);
174                 }
175
176                 //
177                 // Methods to create event request objects
178                 //
179                 public BreakpointEventRequest CreateBreakpointRequest (MethodMirror method, long il_offset) {
180                         return new BreakpointEventRequest (this, method, il_offset);
181                 }
182
183                 public BreakpointEventRequest CreateBreakpointRequest (Location loc) {
184                         if (loc == null)
185                                 throw new ArgumentNullException ("loc");
186                         CheckMirror (loc);
187                         return new BreakpointEventRequest (this, loc.Method, loc.ILOffset);
188                 }
189
190                 public StepEventRequest CreateStepRequest (ThreadMirror thread) {
191                         return new StepEventRequest (this, thread);
192                 }
193
194                 public MethodEntryEventRequest CreateMethodEntryRequest () {
195                         return new MethodEntryEventRequest (this);
196                 }
197
198                 public MethodExitEventRequest CreateMethodExitRequest () {
199                         return new MethodExitEventRequest (this);
200                 }
201
202                 public ExceptionEventRequest CreateExceptionRequest (TypeMirror exc_type) {
203                         return new ExceptionEventRequest (this, exc_type, true, true);
204                 }
205
206                 public ExceptionEventRequest CreateExceptionRequest (TypeMirror exc_type, bool caught, bool uncaught) {
207                         return new ExceptionEventRequest (this, exc_type, caught, uncaught);
208                 }
209
210                 public AssemblyLoadEventRequest CreateAssemblyLoadRequest () {
211                         return new AssemblyLoadEventRequest (this);
212                 }
213
214                 public TypeLoadEventRequest CreateTypeLoadRequest () {
215                         return new TypeLoadEventRequest (this);
216                 }
217
218                 public void EnableEvents (params EventType[] events) {
219                         foreach (EventType etype in events) {
220                                 if (etype == EventType.Breakpoint)
221                                         throw new ArgumentException ("Breakpoint events cannot be requested using EnableEvents", "events");
222                                 conn.EnableEvent (etype, SuspendPolicy.All, null);
223                         }
224                 }
225
226                 public BreakpointEventRequest SetBreakpoint (MethodMirror method, long il_offset) {
227                         BreakpointEventRequest req = CreateBreakpointRequest (method, il_offset);
228
229                         req.Enable ();
230
231                         return req;
232                 }
233
234                 public void ClearAllBreakpoints () {
235                         conn.ClearAllBreakpoints ();
236                 }
237                 
238                 public void Disconnect () {
239                         conn.Close ();
240                 }
241
242                 //
243                 // Return a list of TypeMirror objects for all loaded types which reference the
244                 // source file FNAME. Might return false positives.
245                 // Since protocol version 2.7.
246                 //
247                 public IList<TypeMirror> GetTypesForSourceFile (string fname, bool ignoreCase) {
248                         long[] ids = conn.VM_GetTypesForSourceFile (fname, ignoreCase);
249                         var res = new TypeMirror [ids.Length];
250                         for (int i = 0; i < ids.Length; ++i)
251                                 res [i] = GetType (ids [i]);
252                         return res;
253                 }
254
255                 //
256                 // Return a list of TypeMirror objects for all loaded types named 'NAME'.
257                 // NAME should be in the the same for as with Assembly.GetType ().
258                 // Since protocol version 2.9.
259                 //
260                 public IList<TypeMirror> GetTypes (string name, bool ignoreCase) {
261                         long[] ids = conn.VM_GetTypes (name, ignoreCase);
262                         var res = new TypeMirror [ids.Length];
263                         for (int i = 0; i < ids.Length; ++i)
264                                 res [i] = GetType (ids [i]);
265                         return res;
266                 }
267                 
268                 internal void queue_event_set (EventSet es) {
269                         lock (queue_monitor) {
270                                 queue.Enqueue (es);
271                                 Monitor.Pulse (queue_monitor);
272                         }
273                 }
274
275                 internal void ErrorHandler (object sender, ErrorHandlerEventArgs args) {
276                         switch (args.ErrorCode) {
277                         case ErrorCode.INVALID_OBJECT:
278                                 throw new ObjectCollectedException ();
279                         case ErrorCode.INVALID_FRAMEID:
280                                 throw new InvalidStackFrameException ();
281                         case ErrorCode.NOT_SUSPENDED:
282                                 throw new InvalidOperationException ("The vm is not suspended.");
283                         case ErrorCode.NOT_IMPLEMENTED:
284                                 throw new NotSupportedException ("This request is not supported by the protocol version implemented by the debuggee.");
285                         case ErrorCode.ABSENT_INFORMATION:
286                                 throw new AbsentInformationException ();
287                         case ErrorCode.NO_SEQ_POINT_AT_IL_OFFSET:
288                                 throw new ArgumentException ("Cannot set breakpoint on the specified IL offset.");
289                         default:
290                                 throw new CommandException (args.ErrorCode);
291                         }
292                 }
293
294                 /* Wait for the debuggee to start up and connect to it */
295                 internal void connect () {
296                         conn.Connect ();
297
298                         // Test the connection
299                         version = conn.Version;
300                         if (version.MajorVersion != Connection.MAJOR_VERSION)
301                                 throw new NotSupportedException (String.Format ("The debuggee implements protocol version {0}.{1}, while {2}.{3} is required.", version.MajorVersion, version.MinorVersion, Connection.MAJOR_VERSION, Connection.MINOR_VERSION));
302
303                         long root_domain_id = conn.RootDomain;
304                         root_domain = GetDomain (root_domain_id);
305                 }
306
307                 internal void notify_vm_event (EventType evtype, SuspendPolicy spolicy, int req_id, long thread_id, string vm_uri) {
308                         //Console.WriteLine ("Event: " + evtype + "(" + vm_uri + ")");
309
310                         switch (evtype) {
311                         case EventType.VMStart:
312                                 /* Notify the main thread that the debuggee started up */
313                                 lock (startup_monitor) {
314                                         Monitor.Pulse (startup_monitor);
315                                 }
316                                 queue_event_set (new EventSet (this, spolicy, new Event[] { new VMStartEvent (vm, req_id, thread_id) }));
317                                 break;
318                         case EventType.VMDeath:
319                                 queue_event_set (new EventSet (this, spolicy, new Event[] { new VMDeathEvent (vm, req_id) }));
320                                 break;
321                         case EventType.VMDisconnect:
322                                 queue_event_set (new EventSet (this, spolicy, new Event[] { new VMDisconnectEvent (vm, req_id) }));
323                                 break;
324                         default:
325                                 throw new Exception ();
326                         }
327                 }
328
329                 //
330                 // Methods to create instances of mirror objects
331                 //
332
333                 /*
334                 class MirrorCache<T> {
335                         static Dictionary <long, T> mirrors;
336                         static object mirror_lock = new object ();
337
338                         internal static T GetMirror (VirtualMachine vm, long id) {
339                                 lock (mirror_lock) {
340                                 if (mirrors == null)
341                                         mirrors = new Dictionary <long, T> ();
342                                 T obj;
343                                 if (!mirrors.TryGetValue (id, out obj)) {
344                                         obj = CreateMirror (vm, id);
345                                         mirrors [id] = obj;
346                                 }
347                                 return obj;
348                                 }
349                         }
350
351                         internal static T CreateMirror (VirtualMachine vm, long id) {
352                         }
353                 }
354                 */
355
356                 // FIXME: When to remove items from the cache ?
357
358                 Dictionary <long, MethodMirror> methods;
359                 object methods_lock = new object ();
360
361                 internal MethodMirror GetMethod (long id) {
362                         lock (methods_lock) {
363                                 if (methods == null)
364                                         methods = new Dictionary <long, MethodMirror> ();
365                                 MethodMirror obj;
366                                 if (id == 0)
367                                         return null;
368                                 if (!methods.TryGetValue (id, out obj)) {
369                                         obj = new MethodMirror (this, id);
370                                         methods [id] = obj;
371                                 }
372                                 return obj;
373                         }
374             }
375
376                 Dictionary <long, AssemblyMirror> assemblies;
377                 object assemblies_lock = new object ();
378
379                 internal AssemblyMirror GetAssembly (long id) {
380                         lock (assemblies_lock) {
381                                 if (assemblies == null)
382                                         assemblies = new Dictionary <long, AssemblyMirror> ();
383                                 AssemblyMirror obj;
384                                 if (id == 0)
385                                         return null;
386                                 if (!assemblies.TryGetValue (id, out obj)) {
387                                         obj = new AssemblyMirror (this, id);
388                                         assemblies [id] = obj;
389                                 }
390                                 return obj;
391                         }
392             }
393
394                 Dictionary <long, ModuleMirror> modules;
395                 object modules_lock = new object ();
396
397                 internal ModuleMirror GetModule (long id) {
398                         lock (modules_lock) {
399                                 if (modules == null)
400                                         modules = new Dictionary <long, ModuleMirror> ();
401                                 ModuleMirror obj;
402                                 if (id == 0)
403                                         return null;
404                                 if (!modules.TryGetValue (id, out obj)) {
405                                         obj = new ModuleMirror (this, id);
406                                         modules [id] = obj;
407                                 }
408                                 return obj;
409                         }
410             }
411
412                 Dictionary <long, AppDomainMirror> domains;
413                 object domains_lock = new object ();
414
415                 internal AppDomainMirror GetDomain (long id) {
416                         lock (domains_lock) {
417                                 if (domains == null)
418                                         domains = new Dictionary <long, AppDomainMirror> ();
419                                 AppDomainMirror obj;
420                                 if (id == 0)
421                                         return null;
422                                 if (!domains.TryGetValue (id, out obj)) {
423                                         obj = new AppDomainMirror (this, id);
424                                         domains [id] = obj;
425                                 }
426                                 return obj;
427                         }
428             }
429
430                 Dictionary <long, TypeMirror> types;
431                 object types_lock = new object ();
432
433                 internal TypeMirror GetType (long id) {
434                         lock (types_lock) {
435                                 if (types == null)
436                                         types = new Dictionary <long, TypeMirror> ();
437                                 TypeMirror obj;
438                                 if (id == 0)
439                                         return null;
440                                 if (!types.TryGetValue (id, out obj)) {
441                                         obj = new TypeMirror (this, id);
442                                         types [id] = obj;
443                                 }
444                                 return obj;
445                         }
446             }
447
448                 Dictionary <long, ObjectMirror> objects;
449                 object objects_lock = new object ();
450
451                 internal T GetObject<T> (long id, long domain_id, long type_id) where T : ObjectMirror {
452                         lock (objects_lock) {
453                                 if (objects == null)
454                                         objects = new Dictionary <long, ObjectMirror> ();
455                                 ObjectMirror obj;
456                                 if (!objects.TryGetValue (id, out obj)) {
457                                         /*
458                                          * Obtain the domain/type of the object to determine the type of
459                                          * object we need to create.
460                                          */
461                                         if (domain_id == 0 || type_id == 0) {
462                                                 if (conn.Version.AtLeast (2, 5)) {
463                                                         var info = conn.Object_GetInfo (id);
464                                                         domain_id = info.domain_id;
465                                                         type_id = info.type_id;
466                                                 } else {
467                                                         if (domain_id == 0)
468                                                                 domain_id = conn.Object_GetDomain (id);
469                                                         if (type_id == 0)
470                                                                 type_id = conn.Object_GetType (id);
471                                                 }
472                                         }
473                                         AppDomainMirror d = GetDomain (domain_id);
474                                         TypeMirror t = GetType (type_id);
475
476                                         if (t.Assembly == d.Corlib && t.Namespace == "System.Threading" && t.Name == "Thread")
477                                                 obj = new ThreadMirror (this, id, t, d);
478                                         else if (t.Assembly == d.Corlib && t.Namespace == "System" && t.Name == "String")
479                                                 obj = new StringMirror (this, id, t, d);
480                                         else if (typeof (T) == typeof (ArrayMirror))
481                                                 obj = new ArrayMirror (this, id, t, d);
482                                         else
483                                                 obj = new ObjectMirror (this, id, t, d);
484                                         objects [id] = obj;
485                                 }
486                                 return (T)obj;
487                         }
488             }
489
490                 internal T GetObject<T> (long id) where T : ObjectMirror {
491                         return GetObject<T> (id, 0, 0);
492                 }
493
494                 internal ObjectMirror GetObject (long objid) {
495                         return GetObject<ObjectMirror> (objid);
496                 }
497
498                 internal ThreadMirror GetThread (long id) {
499                         return GetObject <ThreadMirror> (id);
500                 }
501
502                 object requests_lock = new object ();
503
504                 internal void AddRequest (EventRequest req, int id) {
505                         lock (requests_lock) {
506                                 requests [id] = req;
507                         }
508                 }
509
510                 internal void RemoveRequest (EventRequest req, int id) {
511                         lock (requests_lock) {
512                                 requests.Remove (id);
513                         }
514                 }
515
516                 internal EventRequest GetRequest (int id) {
517                         lock (requests_lock) {
518                                 return requests [id];
519                         }
520                 }
521
522                 internal Value DecodeValue (ValueImpl v) {
523                         if (v.Value != null)
524                                 return new PrimitiveValue (this, v.Value);
525
526                         switch (v.Type) {
527                         case ElementType.Void:
528                                 return null;
529                         case ElementType.SzArray:
530                         case ElementType.Array:
531                                 return GetObject<ArrayMirror> (v.Objid);
532                         case ElementType.String:
533                                 return GetObject<StringMirror> (v.Objid);
534                         case ElementType.Class:
535                         case ElementType.Object:
536                                 return GetObject (v.Objid);
537                         case ElementType.ValueType:
538                                 if (v.IsEnum)
539                                         return new EnumMirror (this, GetType (v.Klass), DecodeValues (v.Fields));
540                                 else
541                                         return new StructMirror (this, GetType (v.Klass), DecodeValues (v.Fields));
542                         case (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL:
543                                 return new PrimitiveValue (this, null);
544                         default:
545                                 throw new NotImplementedException ("" + v.Type);
546                         }
547                 }
548
549                 internal Value[] DecodeValues (ValueImpl[] values) {
550                         Value[] res = new Value [values.Length];
551                         for (int i = 0; i < values.Length; ++i)
552                                 res [i] = DecodeValue (values [i]);
553                         return res;
554                 }
555
556                 internal ValueImpl EncodeValue (Value v) {
557                         if (v is PrimitiveValue) {
558                                 object val = (v as PrimitiveValue).Value;
559                                 if (val == null)
560                                         return new ValueImpl { Type = (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL, Objid = 0 };
561                                 else
562                                         return new ValueImpl { Value = val };
563                         } else if (v is ObjectMirror) {
564                                 return new ValueImpl { Type = ElementType.Object, Objid = (v as ObjectMirror).Id };
565                         } else if (v is StructMirror) {
566                                 return new ValueImpl { Type = ElementType.ValueType, Klass = (v as StructMirror).Type.Id, Fields = EncodeValues ((v as StructMirror).Fields) };
567                         } else {
568                                 throw new NotSupportedException ();
569                         }
570                 }
571
572                 internal ValueImpl[] EncodeValues (IList<Value> values) {
573                         ValueImpl[] res = new ValueImpl [values.Count];
574                         for (int i = 0; i < values.Count; ++i)
575                                 res [i] = EncodeValue (values [i]);
576                         return res;
577                 }
578     }
579
580         class EventHandler : MarshalByRefObject, IEventHandler
581         {               
582                 VirtualMachine vm;
583
584                 public EventHandler (VirtualMachine vm) {
585                         this.vm = vm;
586                 }
587
588                 public void Events (SuspendPolicy suspend_policy, EventInfo[] events) {
589                         var l = new List<Event> ();
590
591                         for (int i = 0; i < events.Length; ++i) {
592                                 EventInfo ei = events [i];
593                                 int req_id = ei.ReqId;
594                                 long thread_id = ei.ThreadId;
595                                 long id = ei.Id;
596                                 long loc = ei.Location;
597
598                                 switch (ei.EventType) {
599                                 case EventType.VMStart:
600                                         vm.notify_vm_event (EventType.VMStart, suspend_policy, req_id, thread_id, null);
601                                         break;
602                                 case EventType.VMDeath:
603                                         vm.notify_vm_event (EventType.VMDeath, suspend_policy, req_id, thread_id, null);
604                                         break;
605                                 case EventType.ThreadStart:
606                                         l.Add (new ThreadStartEvent (vm, req_id, id));
607                                         break;
608                                 case EventType.ThreadDeath:
609                                         l.Add (new ThreadDeathEvent (vm, req_id, id));
610                                         break;
611                                 case EventType.AssemblyLoad:
612                                         l.Add (new AssemblyLoadEvent (vm, req_id, thread_id, id));
613                                         break;
614                                 case EventType.AssemblyUnload:
615                                         l.Add (new AssemblyUnloadEvent (vm, req_id, thread_id, id));
616                                         break;
617                                 case EventType.TypeLoad:
618                                         l.Add (new TypeLoadEvent (vm, req_id, thread_id, id));
619                                         break;
620                                 case EventType.MethodEntry:
621                                         l.Add (new MethodEntryEvent (vm, req_id, thread_id, id));
622                                         break;
623                                 case EventType.MethodExit:
624                                         l.Add (new MethodExitEvent (vm, req_id, thread_id, id));
625                                         break;
626                                 case EventType.Breakpoint:
627                                         l.Add (new BreakpointEvent (vm, req_id, thread_id, id, loc));
628                                         break;
629                                 case EventType.Step:
630                                         l.Add (new StepEvent (vm, req_id, thread_id, id, loc));
631                                         break;
632                                 case EventType.Exception:
633                                         l.Add (new ExceptionEvent (vm, req_id, thread_id, id, loc));
634                                         break;
635                                 case EventType.AppDomainCreate:
636                                         l.Add (new AppDomainCreateEvent (vm, req_id, thread_id, id));
637                                         break;
638                                 case EventType.AppDomainUnload:
639                                         l.Add (new AppDomainUnloadEvent (vm, req_id, thread_id, id));
640                                         break;
641                                 case EventType.UserBreak:
642                                         l.Add (new UserBreakEvent (vm, req_id, thread_id));
643                                         break;
644                                 case EventType.UserLog:
645                                         l.Add (new UserLogEvent (vm, req_id, thread_id, ei.Level, ei.Category, ei.Message));
646                                         break;
647                                 default:
648                                         break;
649                                 }
650                         }
651                         
652                         if (l.Count > 0)
653                                 vm.queue_event_set (new EventSet (vm, suspend_policy, l.ToArray ()));
654                 }
655
656                 public void VMDisconnect (int req_id, long thread_id, string vm_uri) {
657                         vm.notify_vm_event (EventType.VMDisconnect, SuspendPolicy.None, req_id, thread_id, vm_uri);
658         }
659     }
660
661         internal class CommandException : Exception {
662
663                 public CommandException (ErrorCode error_code) : base ("Debuggee returned error code " + error_code + ".") {
664                         ErrorCode = error_code;
665                 }
666
667                 public ErrorCode ErrorCode {
668                         get; set;
669                 }
670         }
671 }