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 InvalidOperationException ("The vm is not suspended.");
133 public void Exit (int exitCode) {
134 conn.VM_Exit (exitCode);
137 public void Dispose () {
140 notify_vm_event (EventType.VMDisconnect, SuspendPolicy.None, 0, 0, null);
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]);
151 // Same as the mirrorOf methods in JDI
152 public PrimitiveValue CreateValue (object value) {
154 return new PrimitiveValue (vm, null);
156 if (!value.GetType ().IsPrimitive)
157 throw new ArgumentException ("value must be of a primitive type instead of '" + value.GetType () + "'", "value");
159 return new PrimitiveValue (vm, value);
162 public EnumMirror CreateEnumMirror (TypeMirror type, PrimitiveValue value) {
163 return new EnumMirror (this, type, value);
167 // Enable send and receive timeouts on the connection and send a keepalive event
168 // every 'keepalive_interval' milliseconds.
171 public void SetSocketTimeouts (int send_timeout, int receive_timeout, int keepalive_interval)
173 conn.SetSocketTimeouts (send_timeout, receive_timeout, keepalive_interval);
177 // Methods to create event request objects
179 public BreakpointEventRequest CreateBreakpointRequest (MethodMirror method, long il_offset) {
180 return new BreakpointEventRequest (this, method, il_offset);
183 public BreakpointEventRequest CreateBreakpointRequest (Location loc) {
185 throw new ArgumentNullException ("loc");
187 return new BreakpointEventRequest (this, loc.Method, loc.ILOffset);
190 public StepEventRequest CreateStepRequest (ThreadMirror thread) {
191 return new StepEventRequest (this, thread);
194 public MethodEntryEventRequest CreateMethodEntryRequest () {
195 return new MethodEntryEventRequest (this);
198 public MethodExitEventRequest CreateMethodExitRequest () {
199 return new MethodExitEventRequest (this);
202 public ExceptionEventRequest CreateExceptionRequest (TypeMirror exc_type) {
203 return new ExceptionEventRequest (this, exc_type, true, true);
206 public ExceptionEventRequest CreateExceptionRequest (TypeMirror exc_type, bool caught, bool uncaught) {
207 return new ExceptionEventRequest (this, exc_type, caught, uncaught);
210 public AssemblyLoadEventRequest CreateAssemblyLoadRequest () {
211 return new AssemblyLoadEventRequest (this);
214 public TypeLoadEventRequest CreateTypeLoadRequest () {
215 return new TypeLoadEventRequest (this);
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);
226 public BreakpointEventRequest SetBreakpoint (MethodMirror method, long il_offset) {
227 BreakpointEventRequest req = CreateBreakpointRequest (method, il_offset);
234 public void ClearAllBreakpoints () {
235 conn.ClearAllBreakpoints ();
238 public void Disconnect () {
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.
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]);
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.
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]);
268 internal void queue_event_set (EventSet es) {
269 lock (queue_monitor) {
271 Monitor.Pulse (queue_monitor);
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.");
290 throw new CommandException (args.ErrorCode);
294 /* Wait for the debuggee to start up and connect to it */
295 internal void connect () {
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));
303 long root_domain_id = conn.RootDomain;
304 root_domain = GetDomain (root_domain_id);
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 + ")");
311 case EventType.VMStart:
312 /* Notify the main thread that the debuggee started up */
313 lock (startup_monitor) {
314 Monitor.Pulse (startup_monitor);
316 queue_event_set (new EventSet (this, spolicy, new Event[] { new VMStartEvent (vm, req_id, thread_id) }));
318 case EventType.VMDeath:
319 queue_event_set (new EventSet (this, spolicy, new Event[] { new VMDeathEvent (vm, req_id) }));
321 case EventType.VMDisconnect:
322 queue_event_set (new EventSet (this, spolicy, new Event[] { new VMDisconnectEvent (vm, req_id) }));
325 throw new Exception ();
330 // Methods to create instances of mirror objects
334 class MirrorCache<T> {
335 static Dictionary <long, T> mirrors;
336 static object mirror_lock = new object ();
338 internal static T GetMirror (VirtualMachine vm, long id) {
341 mirrors = new Dictionary <long, T> ();
343 if (!mirrors.TryGetValue (id, out obj)) {
344 obj = CreateMirror (vm, id);
351 internal static T CreateMirror (VirtualMachine vm, long id) {
356 // FIXME: When to remove items from the cache ?
358 Dictionary <long, MethodMirror> methods;
359 object methods_lock = new object ();
361 internal MethodMirror GetMethod (long id) {
362 lock (methods_lock) {
364 methods = new Dictionary <long, MethodMirror> ();
368 if (!methods.TryGetValue (id, out obj)) {
369 obj = new MethodMirror (this, id);
376 Dictionary <long, AssemblyMirror> assemblies;
377 object assemblies_lock = new object ();
379 internal AssemblyMirror GetAssembly (long id) {
380 lock (assemblies_lock) {
381 if (assemblies == null)
382 assemblies = new Dictionary <long, AssemblyMirror> ();
386 if (!assemblies.TryGetValue (id, out obj)) {
387 obj = new AssemblyMirror (this, id);
388 assemblies [id] = obj;
394 Dictionary <long, ModuleMirror> modules;
395 object modules_lock = new object ();
397 internal ModuleMirror GetModule (long id) {
398 lock (modules_lock) {
400 modules = new Dictionary <long, ModuleMirror> ();
404 if (!modules.TryGetValue (id, out obj)) {
405 obj = new ModuleMirror (this, id);
412 Dictionary <long, AppDomainMirror> domains;
413 object domains_lock = new object ();
415 internal AppDomainMirror GetDomain (long id) {
416 lock (domains_lock) {
418 domains = new Dictionary <long, AppDomainMirror> ();
422 if (!domains.TryGetValue (id, out obj)) {
423 obj = new AppDomainMirror (this, id);
430 Dictionary <long, TypeMirror> types;
431 object types_lock = new object ();
433 internal TypeMirror GetType (long id) {
436 types = new Dictionary <long, TypeMirror> ();
440 if (!types.TryGetValue (id, out obj)) {
441 obj = new TypeMirror (this, id);
448 internal TypeMirror[] GetTypes (long[] ids) {
449 var res = new TypeMirror [ids.Length];
450 for (int i = 0; i < ids.Length; ++i)
451 res [i] = GetType (ids [i]);
455 Dictionary <long, ObjectMirror> objects;
456 object objects_lock = new object ();
458 internal T GetObject<T> (long id, long domain_id, long type_id) where T : ObjectMirror {
459 lock (objects_lock) {
461 objects = new Dictionary <long, ObjectMirror> ();
463 if (!objects.TryGetValue (id, out obj)) {
465 * Obtain the domain/type of the object to determine the type of
466 * object we need to create.
468 if (domain_id == 0 || type_id == 0) {
469 if (conn.Version.AtLeast (2, 5)) {
470 var info = conn.Object_GetInfo (id);
471 domain_id = info.domain_id;
472 type_id = info.type_id;
475 domain_id = conn.Object_GetDomain (id);
477 type_id = conn.Object_GetType (id);
480 AppDomainMirror d = GetDomain (domain_id);
481 TypeMirror t = GetType (type_id);
483 if (t.Assembly == d.Corlib && t.Namespace == "System.Threading" && t.Name == "Thread")
484 obj = new ThreadMirror (this, id, t, d);
485 else if (t.Assembly == d.Corlib && t.Namespace == "System" && t.Name == "String")
486 obj = new StringMirror (this, id, t, d);
487 else if (typeof (T) == typeof (ArrayMirror))
488 obj = new ArrayMirror (this, id, t, d);
490 obj = new ObjectMirror (this, id, t, d);
497 internal T GetObject<T> (long id) where T : ObjectMirror {
498 return GetObject<T> (id, 0, 0);
501 internal ObjectMirror GetObject (long objid) {
502 return GetObject<ObjectMirror> (objid);
505 internal ThreadMirror GetThread (long id) {
506 return GetObject <ThreadMirror> (id);
509 object requests_lock = new object ();
511 internal void AddRequest (EventRequest req, int id) {
512 lock (requests_lock) {
517 internal void RemoveRequest (EventRequest req, int id) {
518 lock (requests_lock) {
519 requests.Remove (id);
523 internal EventRequest GetRequest (int id) {
524 lock (requests_lock) {
525 return requests [id];
529 internal Value DecodeValue (ValueImpl v) {
531 return new PrimitiveValue (this, v.Value);
534 case ElementType.Void:
536 case ElementType.SzArray:
537 case ElementType.Array:
538 return GetObject<ArrayMirror> (v.Objid);
539 case ElementType.String:
540 return GetObject<StringMirror> (v.Objid);
541 case ElementType.Class:
542 case ElementType.Object:
543 return GetObject (v.Objid);
544 case ElementType.ValueType:
546 return new EnumMirror (this, GetType (v.Klass), DecodeValues (v.Fields));
548 return new StructMirror (this, GetType (v.Klass), DecodeValues (v.Fields));
549 case (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL:
550 return new PrimitiveValue (this, null);
552 throw new NotImplementedException ("" + v.Type);
556 internal Value[] DecodeValues (ValueImpl[] values) {
557 Value[] res = new Value [values.Length];
558 for (int i = 0; i < values.Length; ++i)
559 res [i] = DecodeValue (values [i]);
563 internal ValueImpl EncodeValue (Value v) {
564 if (v is PrimitiveValue) {
565 object val = (v as PrimitiveValue).Value;
567 return new ValueImpl { Type = (ElementType)ValueTypeId.VALUE_TYPE_ID_NULL, Objid = 0 };
569 return new ValueImpl { Value = val };
570 } else if (v is ObjectMirror) {
571 return new ValueImpl { Type = ElementType.Object, Objid = (v as ObjectMirror).Id };
572 } else if (v is StructMirror) {
573 return new ValueImpl { Type = ElementType.ValueType, Klass = (v as StructMirror).Type.Id, Fields = EncodeValues ((v as StructMirror).Fields) };
575 throw new NotSupportedException ();
579 internal ValueImpl[] EncodeValues (IList<Value> values) {
580 ValueImpl[] res = new ValueImpl [values.Count];
581 for (int i = 0; i < values.Count; ++i)
582 res [i] = EncodeValue (values [i]);
587 class EventHandler : MarshalByRefObject, IEventHandler
591 public EventHandler (VirtualMachine vm) {
595 public void Events (SuspendPolicy suspend_policy, EventInfo[] events) {
596 var l = new List<Event> ();
598 for (int i = 0; i < events.Length; ++i) {
599 EventInfo ei = events [i];
600 int req_id = ei.ReqId;
601 long thread_id = ei.ThreadId;
603 long loc = ei.Location;
605 switch (ei.EventType) {
606 case EventType.VMStart:
607 vm.notify_vm_event (EventType.VMStart, suspend_policy, req_id, thread_id, null);
609 case EventType.VMDeath:
610 vm.notify_vm_event (EventType.VMDeath, suspend_policy, req_id, thread_id, null);
612 case EventType.ThreadStart:
613 l.Add (new ThreadStartEvent (vm, req_id, id));
615 case EventType.ThreadDeath:
616 l.Add (new ThreadDeathEvent (vm, req_id, id));
618 case EventType.AssemblyLoad:
619 l.Add (new AssemblyLoadEvent (vm, req_id, thread_id, id));
621 case EventType.AssemblyUnload:
622 l.Add (new AssemblyUnloadEvent (vm, req_id, thread_id, id));
624 case EventType.TypeLoad:
625 l.Add (new TypeLoadEvent (vm, req_id, thread_id, id));
627 case EventType.MethodEntry:
628 l.Add (new MethodEntryEvent (vm, req_id, thread_id, id));
630 case EventType.MethodExit:
631 l.Add (new MethodExitEvent (vm, req_id, thread_id, id));
633 case EventType.Breakpoint:
634 l.Add (new BreakpointEvent (vm, req_id, thread_id, id, loc));
637 l.Add (new StepEvent (vm, req_id, thread_id, id, loc));
639 case EventType.Exception:
640 l.Add (new ExceptionEvent (vm, req_id, thread_id, id, loc));
642 case EventType.AppDomainCreate:
643 l.Add (new AppDomainCreateEvent (vm, req_id, thread_id, id));
645 case EventType.AppDomainUnload:
646 l.Add (new AppDomainUnloadEvent (vm, req_id, thread_id, id));
648 case EventType.UserBreak:
649 l.Add (new UserBreakEvent (vm, req_id, thread_id));
651 case EventType.UserLog:
652 l.Add (new UserLogEvent (vm, req_id, thread_id, ei.Level, ei.Category, ei.Message));
660 vm.queue_event_set (new EventSet (vm, suspend_policy, l.ToArray ()));
663 public void VMDisconnect (int req_id, long thread_id, string vm_uri) {
664 vm.notify_vm_event (EventType.VMDisconnect, SuspendPolicy.None, req_id, thread_id, vm_uri);
668 internal class CommandException : Exception {
670 public CommandException (ErrorCode error_code) : base ("Debuggee returned error code " + error_code + ".") {
671 ErrorCode = error_code;
674 public ErrorCode ErrorCode {