3 using System.Threading;
5 using System.Diagnostics;
6 using System.Collections;
7 using System.Collections.Generic;
8 using Mono.Cecil.Metadata;
10 namespace Mono.Debugger.Soft
12 public class VirtualMachine : Mirror
16 object startup_monitor;
17 AppDomainMirror root_domain;
18 Dictionary<int, EventRequest> requests;
19 ITargetProcess process;
21 internal Connection conn;
25 internal VirtualMachine (ITargetProcess process, Connection conn) : base () {
26 SetVirtualMachine (this);
28 queue_monitor = new Object ();
29 startup_monitor = new Object ();
30 requests = new Dictionary <int, EventRequest> ();
32 this.process = process;
33 conn.ErrorHandler += ErrorHandler;
36 // The standard output of the process is available normally through Process
37 public StreamReader StandardOutput { get; set; }
38 public StreamReader StandardError { get; set; }
41 public Process Process {
43 ProcessWrapper pw = process as ProcessWrapper;
45 throw new InvalidOperationException ("Process instance not available");
50 public ITargetProcess TargetProcess {
56 public AppDomainMirror RootDomain {
62 public EndPoint EndPoint {
64 var tcpConn = conn as TcpConnection;
66 return tcpConn.EndPoint;
71 public VersionInfo Version {
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.
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) {
89 Monitor.Wait (queue_monitor);
90 current_es = (EventSet)queue.Dequeue ();
93 return current_es.Events [current_es_index ++];
97 public Event GetNextEvent (int timeout) {
98 throw new NotImplementedException ();
101 public EventSet GetNextEventSet () {
102 lock (queue_monitor) {
103 if (queue.Count == 0)
104 Monitor.Wait (queue_monitor);
107 current_es_index = 0;
109 return (EventSet)queue.Dequeue ();
113 [Obsolete ("Use GetNextEventSet () instead")]
114 public T GetNextEvent<T> () where T : Event {
115 return GetNextEvent () as T;
118 public void Suspend () {
122 public void Resume () {
125 } catch (CommandException ex) {
126 if (ex.ErrorCode == ErrorCode.NOT_SUSPENDED)
127 throw new VMNotSuspendedException ();
133 public void Exit (int exitCode) {
134 conn.VM_Exit (exitCode);
137 public void Detach () {
140 notify_vm_event (EventType.VMDisconnect, SuspendPolicy.None, 0, 0, null, 0);
143 [Obsolete ("This method was poorly named; use the Detach() method instead")]
144 public void Dispose ()
149 public void ForceDisconnect ()
151 conn.ForceDisconnect ();
154 public IList<ThreadMirror> GetThreads () {
155 long[] ids = vm.conn.VM_GetThreads ();
156 ThreadMirror[] res = new ThreadMirror [ids.Length];
157 for (int i = 0; i < ids.Length; ++i)
158 res [i] = GetThread (ids [i]);
162 // Same as the mirrorOf methods in JDI
163 public PrimitiveValue CreateValue (object value) {
165 return new PrimitiveValue (vm, null);
167 if (!value.GetType ().IsPrimitive)
168 throw new ArgumentException ("value must be of a primitive type instead of '" + value.GetType () + "'", "value");
170 return new PrimitiveValue (vm, value);
173 public EnumMirror CreateEnumMirror (TypeMirror type, PrimitiveValue value) {
174 return new EnumMirror (this, type, value);
178 // Enable send and receive timeouts on the connection and send a keepalive event
179 // every 'keepalive_interval' milliseconds.
182 public void SetSocketTimeouts (int send_timeout, int receive_timeout, int keepalive_interval)
184 conn.SetSocketTimeouts (send_timeout, receive_timeout, keepalive_interval);
188 // Methods to create event request objects
190 public BreakpointEventRequest CreateBreakpointRequest (MethodMirror method, long il_offset) {
191 return new BreakpointEventRequest (this, method, il_offset);
194 public BreakpointEventRequest CreateBreakpointRequest (Location loc) {
196 throw new ArgumentNullException ("loc");
198 return new BreakpointEventRequest (this, loc.Method, loc.ILOffset);
201 public StepEventRequest CreateStepRequest (ThreadMirror thread) {
202 return new StepEventRequest (this, thread);
205 public MethodEntryEventRequest CreateMethodEntryRequest () {
206 return new MethodEntryEventRequest (this);
209 public MethodExitEventRequest CreateMethodExitRequest () {
210 return new MethodExitEventRequest (this);
213 public ExceptionEventRequest CreateExceptionRequest (TypeMirror exc_type) {
214 return new ExceptionEventRequest (this, exc_type, true, true);
217 public ExceptionEventRequest CreateExceptionRequest (TypeMirror exc_type, bool caught, bool uncaught) {
218 return new ExceptionEventRequest (this, exc_type, caught, uncaught);
221 public AssemblyLoadEventRequest CreateAssemblyLoadRequest () {
222 return new AssemblyLoadEventRequest (this);
225 public TypeLoadEventRequest CreateTypeLoadRequest () {
226 return new TypeLoadEventRequest (this);
229 public void EnableEvents (params EventType[] events) {
230 EnableEvents (events, SuspendPolicy.All);
233 public void EnableEvents (EventType[] events, SuspendPolicy suspendPolicy) {
234 foreach (EventType etype in events) {
235 if (etype == EventType.Breakpoint)
236 throw new ArgumentException ("Breakpoint events cannot be requested using EnableEvents", "events");
237 conn.EnableEvent (etype, suspendPolicy, null);
241 public BreakpointEventRequest SetBreakpoint (MethodMirror method, long il_offset) {
242 BreakpointEventRequest req = CreateBreakpointRequest (method, il_offset);
249 public void ClearAllBreakpoints () {
250 conn.ClearAllBreakpoints ();
253 public void Disconnect () {
258 // Return a list of TypeMirror objects for all loaded types which reference the
259 // source file FNAME. Might return false positives.
260 // Since protocol version 2.7.
262 public IList<TypeMirror> GetTypesForSourceFile (string fname, bool ignoreCase) {
263 long[] ids = conn.VM_GetTypesForSourceFile (fname, ignoreCase);
264 var res = new TypeMirror [ids.Length];
265 for (int i = 0; i < ids.Length; ++i)
266 res [i] = GetType (ids [i]);
271 // Return a list of TypeMirror objects for all loaded types named 'NAME'.
272 // NAME should be in the the same for as with Assembly.GetType ().
273 // Since protocol version 2.9.
275 public IList<TypeMirror> GetTypes (string name, bool ignoreCase) {
276 long[] ids = conn.VM_GetTypes (name, ignoreCase);
277 var res = new TypeMirror [ids.Length];
278 for (int i = 0; i < ids.Length; ++i)
279 res [i] = GetType (ids [i]);
283 internal void queue_event_set (EventSet es) {
284 lock (queue_monitor) {
286 Monitor.Pulse (queue_monitor);
290 internal void ErrorHandler (object sender, ErrorHandlerEventArgs args) {
291 switch (args.ErrorCode) {
292 case ErrorCode.INVALID_OBJECT:
293 throw new ObjectCollectedException ();
294 case ErrorCode.INVALID_FRAMEID:
295 throw new InvalidStackFrameException ();
296 case ErrorCode.NOT_SUSPENDED:
297 throw new VMNotSuspendedException ();
298 case ErrorCode.NOT_IMPLEMENTED:
299 throw new NotSupportedException ("This request is not supported by the protocol version implemented by the debuggee.");
300 case ErrorCode.ABSENT_INFORMATION:
301 throw new AbsentInformationException ();
302 case ErrorCode.NO_SEQ_POINT_AT_IL_OFFSET:
303 throw new ArgumentException ("Cannot set breakpoint on the specified IL offset.");
305 throw new CommandException (args.ErrorCode);
309 /* Wait for the debuggee to start up and connect to it */
310 internal void connect () {
313 // Test the connection
314 version = conn.Version;
315 if (version.MajorVersion != Connection.MAJOR_VERSION)
316 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));
318 long root_domain_id = conn.RootDomain;
319 root_domain = GetDomain (root_domain_id);
322 internal void notify_vm_event (EventType evtype, SuspendPolicy spolicy, int req_id, long thread_id, string vm_uri, int exit_code) {
323 //Console.WriteLine ("Event: " + evtype + "(" + vm_uri + ")");
326 case EventType.VMStart:
327 /* Notify the main thread that the debuggee started up */
328 lock (startup_monitor) {
329 Monitor.Pulse (startup_monitor);
331 queue_event_set (new EventSet (this, spolicy, new Event[] { new VMStartEvent (vm, req_id, thread_id) }));
333 case EventType.VMDeath:
334 queue_event_set (new EventSet (this, spolicy, new Event[] { new VMDeathEvent (vm, req_id, exit_code) }));
336 case EventType.VMDisconnect:
337 queue_event_set (new EventSet (this, spolicy, new Event[] { new VMDisconnectEvent (vm, req_id) }));
340 throw new Exception ();
345 // Methods to create instances of mirror objects
349 class MirrorCache<T> {
350 static Dictionary <long, T> mirrors;
351 static object mirror_lock = new object ();
353 internal static T GetMirror (VirtualMachine vm, long id) {
356 mirrors = new Dictionary <long, T> ();
358 if (!mirrors.TryGetValue (id, out obj)) {
359 obj = CreateMirror (vm, id);
366 internal static T CreateMirror (VirtualMachine vm, long id) {
371 // FIXME: When to remove items from the cache ?
373 Dictionary <long, MethodMirror> methods;
374 object methods_lock = new object ();
376 internal MethodMirror GetMethod (long id) {
377 lock (methods_lock) {
379 methods = new Dictionary <long, MethodMirror> ();
383 if (!methods.TryGetValue (id, out obj)) {
384 obj = new MethodMirror (this, id);
391 Dictionary <long, AssemblyMirror> assemblies;
392 object assemblies_lock = new object ();
394 internal AssemblyMirror GetAssembly (long id) {
395 lock (assemblies_lock) {
396 if (assemblies == null)
397 assemblies = new Dictionary <long, AssemblyMirror> ();
401 if (!assemblies.TryGetValue (id, out obj)) {
402 obj = new AssemblyMirror (this, id);
403 assemblies [id] = obj;
409 Dictionary <long, ModuleMirror> modules;
410 object modules_lock = new object ();
412 internal ModuleMirror GetModule (long id) {
413 lock (modules_lock) {
415 modules = new Dictionary <long, ModuleMirror> ();
419 if (!modules.TryGetValue (id, out obj)) {
420 obj = new ModuleMirror (this, id);
427 Dictionary <long, AppDomainMirror> domains;
428 object domains_lock = new object ();
430 internal AppDomainMirror GetDomain (long id) {
431 lock (domains_lock) {
433 domains = new Dictionary <long, AppDomainMirror> ();
437 if (!domains.TryGetValue (id, out obj)) {
438 obj = new AppDomainMirror (this, id);
445 internal void InvalidateAssemblyCaches () {
446 lock (domains_lock) {
447 foreach (var d in domains.Values)
448 d.InvalidateAssembliesCache ();
452 Dictionary <long, TypeMirror> types;
453 object types_lock = new object ();
455 internal TypeMirror GetType (long id) {
458 types = new Dictionary <long, TypeMirror> ();
462 if (!types.TryGetValue (id, out obj)) {
463 obj = new TypeMirror (this, id);
470 internal TypeMirror[] GetTypes (long[] ids) {
471 var res = new TypeMirror [ids.Length];
472 for (int i = 0; i < ids.Length; ++i)
473 res [i] = GetType (ids [i]);
477 Dictionary <long, ObjectMirror> objects;
478 object objects_lock = new object ();
480 internal T GetObject<T> (long id, long domain_id, long type_id) where T : ObjectMirror {
481 lock (objects_lock) {
483 objects = new Dictionary <long, ObjectMirror> ();
485 if (!objects.TryGetValue (id, out obj)) {
487 * Obtain the domain/type of the object to determine the type of
488 * object we need to create.
490 if (domain_id == 0 || type_id == 0) {
491 if (conn.Version.AtLeast (2, 5)) {
492 var info = conn.Object_GetInfo (id);
493 domain_id = info.domain_id;
494 type_id = info.type_id;
497 domain_id = conn.Object_GetDomain (id);
499 type_id = conn.Object_GetType (id);
502 AppDomainMirror d = GetDomain (domain_id);
503 TypeMirror t = GetType (type_id);
505 if (t.Assembly == d.Corlib && t.Namespace == "System.Threading" && t.Name == "Thread")
506 obj = new ThreadMirror (this, id, t, d);
507 else if (t.Assembly == d.Corlib && t.Namespace == "System" && t.Name == "String")
508 obj = new StringMirror (this, id, t, d);
509 else if (typeof (T) == typeof (ArrayMirror))
510 obj = new ArrayMirror (this, id, t, d);
512 obj = new ObjectMirror (this, id, t, d);
519 internal T GetObject<T> (long id) where T : ObjectMirror {
520 return GetObject<T> (id, 0, 0);
523 internal ObjectMirror GetObject (long objid) {
524 return GetObject<ObjectMirror> (objid);
527 internal ThreadMirror GetThread (long id) {
528 return GetObject <ThreadMirror> (id);
531 Dictionary <long, FieldInfoMirror> fields;
532 object fields_lock = new object ();
534 internal FieldInfoMirror GetField (long id) {
537 fields = new Dictionary <long, FieldInfoMirror> ();
541 if (!fields.TryGetValue (id, out obj)) {
542 obj = new FieldInfoMirror (this, id);
549 object requests_lock = new object ();
551 internal void AddRequest (EventRequest req, int id) {
552 lock (requests_lock) {
557 internal void RemoveRequest (EventRequest req, int id) {
558 lock (requests_lock) {
559 requests.Remove (id);
563 internal EventRequest GetRequest (int id) {
564 lock (requests_lock) {
565 return requests [id];
569 internal Value DecodeValue (ValueImpl v) {
570 return DecodeValue (v, null);
573 internal Value DecodeValue (ValueImpl v, Dictionary<int, Value> parent_vtypes) {
575 return new PrimitiveValue (this, v.Value);
578 case ElementType.Void:
580 case ElementType.SzArray:
581 case ElementType.Array:
582 return GetObject<ArrayMirror> (v.Objid);
583 case ElementType.String:
584 return GetObject<StringMirror> (v.Objid);
585 case ElementType.Class:
586 case ElementType.Object:
587 return GetObject (v.Objid);
588 case ElementType.ValueType:
589 if (parent_vtypes == null)
590 parent_vtypes = new Dictionary<int, Value> ();
593 vtype = new EnumMirror (this, GetType (v.Klass), (Value[])null);
595 vtype = new StructMirror (this, GetType (v.Klass), (Value[])null);
596 parent_vtypes [parent_vtypes.Count] = vtype;
597 vtype.SetFields (DecodeValues (v.Fields, parent_vtypes));
598 parent_vtypes.Remove (parent_vtypes.Count - 1);
600 case (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL:
601 return new PrimitiveValue (this, null);
602 case (ElementType)ValueTypeId.VALUE_TYPE_ID_PARENT_VTYPE:
603 return parent_vtypes [v.Index];
605 throw new NotImplementedException ("" + v.Type);
609 internal Value[] DecodeValues (ValueImpl[] values) {
610 Value[] res = new Value [values.Length];
611 for (int i = 0; i < values.Length; ++i)
612 res [i] = DecodeValue (values [i]);
616 internal Value[] DecodeValues (ValueImpl[] values, Dictionary<int, Value> parent_vtypes) {
617 Value[] res = new Value [values.Length];
618 for (int i = 0; i < values.Length; ++i)
619 res [i] = DecodeValue (values [i], parent_vtypes);
623 internal ValueImpl EncodeValue (Value v) {
624 if (v is PrimitiveValue) {
625 object val = (v as PrimitiveValue).Value;
627 return new ValueImpl { Type = (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL, Objid = 0 };
629 return new ValueImpl { Value = val };
630 } else if (v is ObjectMirror) {
631 return new ValueImpl { Type = ElementType.Object, Objid = (v as ObjectMirror).Id };
632 } else if (v is StructMirror) {
633 return new ValueImpl { Type = ElementType.ValueType, Klass = (v as StructMirror).Type.Id, Fields = EncodeValues ((v as StructMirror).Fields) };
635 throw new NotSupportedException ();
639 internal ValueImpl[] EncodeValues (IList<Value> values) {
640 ValueImpl[] res = new ValueImpl [values.Count];
641 for (int i = 0; i < values.Count; ++i)
642 res [i] = EncodeValue (values [i]);
646 internal void CheckProtocolVersion (int major, int minor) {
647 if (!conn.Version.AtLeast (major, minor))
648 throw new NotSupportedException ("This request is not supported by the protocol version implemented by the debuggee.");
652 class EventHandler : MarshalByRefObject, IEventHandler
656 public EventHandler (VirtualMachine vm) {
660 public void Events (SuspendPolicy suspend_policy, EventInfo[] events) {
661 var l = new List<Event> ();
663 for (int i = 0; i < events.Length; ++i) {
664 EventInfo ei = events [i];
665 int req_id = ei.ReqId;
666 long thread_id = ei.ThreadId;
668 long loc = ei.Location;
670 switch (ei.EventType) {
671 case EventType.VMStart:
672 vm.notify_vm_event (EventType.VMStart, suspend_policy, req_id, thread_id, null, 0);
674 case EventType.VMDeath:
675 vm.notify_vm_event (EventType.VMDeath, suspend_policy, req_id, thread_id, null, ei.ExitCode);
677 case EventType.ThreadStart:
678 l.Add (new ThreadStartEvent (vm, req_id, id));
680 case EventType.ThreadDeath:
681 l.Add (new ThreadDeathEvent (vm, req_id, id));
683 case EventType.AssemblyLoad:
684 vm.InvalidateAssemblyCaches ();
685 l.Add (new AssemblyLoadEvent (vm, req_id, thread_id, id));
687 case EventType.AssemblyUnload:
688 vm.InvalidateAssemblyCaches ();
689 l.Add (new AssemblyUnloadEvent (vm, req_id, thread_id, id));
691 case EventType.TypeLoad:
692 l.Add (new TypeLoadEvent (vm, req_id, thread_id, id));
694 case EventType.MethodEntry:
695 l.Add (new MethodEntryEvent (vm, req_id, thread_id, id));
697 case EventType.MethodExit:
698 l.Add (new MethodExitEvent (vm, req_id, thread_id, id));
700 case EventType.Breakpoint:
701 l.Add (new BreakpointEvent (vm, req_id, thread_id, id, loc));
704 l.Add (new StepEvent (vm, req_id, thread_id, id, loc));
706 case EventType.Exception:
707 l.Add (new ExceptionEvent (vm, req_id, thread_id, id, loc));
709 case EventType.AppDomainCreate:
710 l.Add (new AppDomainCreateEvent (vm, req_id, thread_id, id));
712 case EventType.AppDomainUnload:
713 l.Add (new AppDomainUnloadEvent (vm, req_id, thread_id, id));
715 case EventType.UserBreak:
716 l.Add (new UserBreakEvent (vm, req_id, thread_id));
718 case EventType.UserLog:
719 l.Add (new UserLogEvent (vm, req_id, thread_id, ei.Level, ei.Category, ei.Message));
727 vm.queue_event_set (new EventSet (vm, suspend_policy, l.ToArray ()));
730 public void VMDisconnect (int req_id, long thread_id, string vm_uri) {
731 vm.notify_vm_event (EventType.VMDisconnect, SuspendPolicy.None, req_id, thread_id, vm_uri, 0);
735 public class CommandException : Exception {
737 internal CommandException (ErrorCode error_code) : base ("Debuggee returned error code " + error_code + ".") {
738 ErrorCode = error_code;
741 public ErrorCode ErrorCode {
746 public class VMNotSuspendedException : InvalidOperationException
748 public VMNotSuspendedException () : base ("The vm is not suspended.")