Exemplo n.º 1
1
		public override void OnUpdateList ()
		{
			base.OnUpdateList ();
			StackFrame frame = DebuggingService.CurrentFrame;
			
			if (frame == null || !FrameEquals (frame, lastFrame)) {
				tree.ClearExpressions ();
				lastExpressions = null;
			}
			lastFrame = frame;
			
			if (frame == null)
				return;
			
			//FIXME: tree should use the local refs rather than expressions. ATM we exclude items without names
			var expr = new HashSet<string> (frame.GetAllLocals ().Select (i => i.Name)
				.Where (n => !string.IsNullOrEmpty (n) && n != "?"));
			
			//add expressions not in tree already, remove expressions that are longer valid
			if (lastExpressions != null) {
				foreach (string rem in lastExpressions.Except (expr))
					tree.RemoveExpression (rem);
				foreach (string rem in expr.Except (lastExpressions))
					tree.AddExpression (rem);
			} else {
				tree.AddExpressions (expr);
			}
			
			lastExpressions = expr;
		}
Exemplo n.º 2
0
		static bool FrameEquals (StackFrame a, StackFrame z)
		{
			if (null == a || null == z)
				return a == z;
			return a.SourceLocation.FileName.Equals (z.SourceLocation.FileName, StringComparison.Ordinal) &&
			       a.SourceLocation.MethodName.Equals (z.SourceLocation.MethodName, StringComparison.Ordinal);
		}
Exemplo n.º 3
0
 // Token: 0x06000138 RID: 312 RVA: 0x00005888 File Offset: 0x00003A88
 private Client.ExceptionInfo GetExceptionInfo(Backtrace backTrace, EvaluationOptions options = null, bool isUnhandled = false)
 {
     Client.ExceptionInfo exceptionInfo = null;
     if (backTrace != null && backTrace.FrameCount > 0)
     {
         for (int i = 0; i < backTrace.FrameCount; i++)
         {
             Mono.Debugging.Client.StackFrame frame = backTrace.GetFrame(i);
             if (isUnhandled || !frame.IsExternalCode)
             {
                 try
                 {
                     exceptionInfo = ((options == null) ? frame.GetException() : frame.GetException(options));
                 }
                 catch (AbsentInformationException)
                 {
                     goto IL_4A;
                 }
                 if (exceptionInfo != null)
                 {
                     this.ResolveFullException(exceptionInfo);
                     break;
                 }
             }
             IL_4A :;
         }
     }
     return(exceptionInfo);
 }
Exemplo n.º 4
0
		static bool FrameEquals (StackFrame a, StackFrame z)
		{
			if (null == a || null == z)
				return a == z;

			if (a.SourceLocation == null || z.SourceLocation == null)
				return a.SourceLocation == z.SourceLocation;

			if (a.SourceLocation.FileName == null) {
				if (z.SourceLocation.FileName != null)
					return false;
			} else {
				if (!a.SourceLocation.FileName.Equals (z.SourceLocation.FileName, StringComparison.Ordinal))
					return false;
			}

			if (a.SourceLocation.MethodName == null) {
				if (z.SourceLocation.MethodName != null)
					return false;

				return true;
			} else {
				return a.SourceLocation.MethodName.Equals (z.SourceLocation.MethodName, StringComparison.Ordinal);
			}
		}
Exemplo n.º 5
0
		public GdbBacktrace (GdbSession session, long threadId, int count, ResultData firstFrame)
		{
			fcount = count;
			this.threadId = threadId;
			if (firstFrame != null)
				this.firstFrame = CreateFrame (firstFrame);
			this.session = session;
		}
Exemplo n.º 6
0
//		PinWindow pinWindow;
//		TreeIter currentPinIter;
		
		public DebugValueWindow (Mono.TextEditor.TextEditor editor, int offset, StackFrame frame, ObjectValue value, PinnedWatch watch): base (Gtk.WindowType.Toplevel)
		{
			this.TypeHint = WindowTypeHint.PopupMenu;
			this.AllowShrink = false;
			this.AllowGrow = false;
			this.Decorated = false;

			TransientFor = (Gtk.Window) editor.Toplevel;
			
			// Avoid getting the focus when the window is shown. We'll get it when the mouse enters the window
			AcceptFocus = false;
			
			sw = new ScrolledWindow ();
			sw.HscrollbarPolicy = PolicyType.Never;
			sw.VscrollbarPolicy = PolicyType.Never;
			
			tree = new ObjectValueTreeView ();
			sw.Add (tree);
			ContentBox.Add (sw);
			
			tree.Frame = frame;
			tree.CompactView = true;
			tree.AllowAdding = false;
			tree.AllowEditing = true;
			tree.HeadersVisible = false;
			tree.AllowPinning = true;
			tree.RootPinAlwaysVisible = true;
			tree.PinnedWatch = watch;
			DocumentLocation location = editor.Document.OffsetToLocation (offset);
			tree.PinnedWatchLine = location.Line;
			tree.PinnedWatchFile = ((ExtensibleTextEditor)editor).View.ContentName;
			
			tree.AddValue (value);
			tree.Selection.UnselectAll ();
			tree.SizeAllocated += OnTreeSizeChanged;
			tree.PinStatusChanged += delegate {
				Destroy ();
			};
			
//			tree.MotionNotifyEvent += HandleTreeMotionNotifyEvent;
			
			sw.ShowAll ();
			
//			pinWindow = new PinWindow (this);
//			pinWindow.SetPinned (false);
//			pinWindow.ButtonPressEvent += HandlePinWindowButtonPressEvent;
			
			tree.StartEditing += delegate {
				Modal = true;
			};
			
			tree.EndEditing += delegate {
				Modal = false;
			};

			ShowArrow = true;
			Theme.CornerRadius = 3;
		}
Exemplo n.º 7
0
 public DDebugBacktrace(DDebugSession session, long threadId, DEW.DBGEngine engine)
 {
     this.session = session;
     this.Engine = engine;
     fcount = engine.CallStack.Length;
     this.threadId = threadId;
     if (firstFrame != null)
         this.firstFrame = CreateFrame(Engine.CallStack[0]);
 }
Exemplo n.º 8
0
		public override StackFrame[] GetStackFrames (int firstIndex, int lastIndex)
		{
			if (lastIndex >= FrameList.Count)
				lastIndex = FrameList.Count - 1;
			StackFrame[] array = new StackFrame[lastIndex - firstIndex + 1];
			for (int n = 0; n < array.Length; n++)
				array [n] = CreateFrame (session, FrameList [n + firstIndex]);
			return array;
		}
Exemplo n.º 9
0
		public override void SetUp ()
		{
			base.SetUp ();
			ds = Start ("TestEvaluation");
			if (ds == null)
				Assert.Ignore ("Engine not found: {0}", EngineId);

			frame = ds.ActiveThread.Backtrace.GetFrame (0);
		}
		public PlainDbgEngBasedBacktrace(DDebugSession session, long threadId, DEW.DBGEngine engine)
		{
			BacktraceHelper = new DLocalExamBacktrace(this);
			this.session = session;
			this.Engine = engine;
			fcount = engine.CallStack.Length;
			this.threadId = threadId;
			if (firstFrame != null)
				this.firstFrame = CreateFrame(Engine.CallStack[0]);
		}
Exemplo n.º 11
0
		public override void OnUpdateList ()
		{
			base.OnUpdateList ();
			StackFrame frame = DebuggingService.CurrentFrame;
			if (frame != null && !FrameEquals (frame, lastFrame)) {
				tree.ClearExpressions ();
				tree.AddExpressions (frame.GetAllLocals ().Select (i => i.Name));
				lastFrame = frame;
			}
		}
Exemplo n.º 12
0
		public override void OnUpdateList ()
		{
			base.OnUpdateList ();
			StackFrame frame = DebuggingService.CurrentFrame;
			
			if (frame == null || !FrameEquals (frame, lastFrame)) {
				tree.ClearExpressions ();
				lastLookup = null;
			}
			lastFrame = frame;
			
			if (frame == null)
				return;

			//add expressions not in tree already, remove expressions that are longer valid
			var frameLocals = frame.GetAllLocals();
			var frameLocalLookup = new Dictionary<string, ObjectValue>(frameLocals.Length);
			foreach (var local in frameLocals) {
				var variableName = local.Name;
				//not sure if there is a use case for duplicate variable names, or blanks 
				if (string.IsNullOrWhiteSpace(variableName) ||
					variableName == "?" ||
					frameLocalLookup.ContainsKey(variableName)) {
					continue;
				}
				else
					frameLocalLookup.Add(variableName, local);

				if (lastLookup != null) {
					ObjectValue priorValue;
					if (lastLookup.TryGetValue(variableName, out priorValue))
						tree.ReplaceValue(priorValue, local);
					else
						tree.AddValue(local);
				}
			}

			if (lastLookup != null) {
				//get rid of the values that didnt survive from the last refresh
				foreach (var prior in lastLookup) {
					if (!frameLocalLookup.ContainsKey(prior.Key))
						tree.RemoveValue(prior.Value);
				}
			}
			else {
				tree.ClearValues();
				tree.AddValues(frameLocalLookup.Values);
			}

			lastLookup = frameLocalLookup;
		}
Exemplo n.º 13
0
        public MonoStackFrame(MonoEngine engine, MonoThread thread, StackFrame frame)
        {
            this.engine = engine;
            this.thread = thread;
            this.frame  = frame;

            var allLocals = frame.GetAllLocals(EvaluationOptions.DefaultOptions);

            parameters   = frame.GetParameters(EvaluationOptions.DefaultOptions);
            locals       = allLocals.Where(x => !parameters.Any(y => y.Name == x.Name)).ToArray();
            lineNumber   = (uint)frame.SourceLocation.Line;
            hasSource    = frame.HasDebugInfo;
            functionName = frame.SourceLocation.MethodName;
            documentName = frame.SourceLocation.FileName;
        }
        private Mono.Debugging.Client.StackFrame DebuggerActiveFrame()
        {
            if (_activeFrame != null)
            {
                return(_activeFrame);
            }

            var bt = DebuggerActiveBacktrace();

            if (bt != null)
            {
                return(_activeFrame = bt.GetFrame(0));
            }

            return(null);
        }
Exemplo n.º 15
0
        public Mono.Debugging.Client.StackFrame [] GetStackFrames(int firstIndex, int lastIndex)
        {
            //Optimisation for getting 1st frame of thread(used for ThreadPad)
            if (firstIndex == 0 && lastIndex == 1 && totalFramesCount > 0)
            {
                return(new Mono.Debugging.Client.StackFrame [] { new VsCodeStackFrame(frame0Format, threadId, 0, frames [0]) });
            }
            var stackFrames = new Mono.Debugging.Client.StackFrame [Math.Min(lastIndex - firstIndex, totalFramesCount - firstIndex)];
            var format      = VsCodeStackFrame.GetStackFrameFormat(vsCodeDebuggerSession.EvaluationOptions);
            var body        = vsCodeDebuggerSession.protocolClient.SendRequestSync(new StackTraceRequest(threadId, firstIndex, stackFrames.Length, format));

            for (int i = 0; i < stackFrames.Length; i++)
            {
                frames [i + firstIndex] = body.StackFrames [i];
                stackFrames [i]         = new VsCodeStackFrame(format, threadId, i, body.StackFrames [i]);
            }
            return(stackFrames);
        }
Exemplo n.º 16
0
		public DebugValueWindow (TextEditor editor, int offset, StackFrame frame, ObjectValue value, PinnedWatch watch) : base (Gtk.WindowType.Toplevel)
		{
			this.TypeHint = WindowTypeHint.PopupMenu;
			this.AllowShrink = false;
			this.AllowGrow = false;
			this.Decorated = false;

			TransientFor = (Gtk.Window) ((Gtk.Widget)editor).Toplevel;
			// Avoid getting the focus when the window is shown. We'll get it when the mouse enters the window
			AcceptFocus = false;

			sw = new ScrolledWindow ();
			sw.HscrollbarPolicy = PolicyType.Never;
			sw.VscrollbarPolicy = PolicyType.Never;

			tree = new ObjectValueTreeView ();
			sw.Add (tree);
			ContentBox.Add (sw);

			tree.Frame = frame;
			tree.CompactView = true;
			tree.AllowAdding = false;
			tree.AllowEditing = true;
			tree.HeadersVisible = false;
			tree.AllowPinning = true;
			tree.RootPinAlwaysVisible = true;
			tree.PinnedWatch = watch;
			var location = editor.OffsetToLocation (offset);
			tree.PinnedWatchLine = location.Line;
			tree.PinnedWatchFile = editor.FileName;

			tree.AddValue (value);
			tree.Selection.UnselectAll ();
			tree.SizeAllocated += OnTreeSizeChanged;
			tree.PinStatusChanged += OnPinStatusChanged;

			sw.ShowAll ();

			tree.StartEditing += OnStartEditing;
			tree.EndEditing += OnEndEditing;

			ShowArrow = true;
			Theme.CornerRadius = 3;
		}
		public DebugValueWindow (Mono.TextEditor.TextEditor editor, int offset, StackFrame frame, ObjectValue value, PinnedWatch watch)
		{
			TransientFor = (Gtk.Window) editor.Toplevel;
			
			// Avoid getting the focus when the window is shown. We'll get it when the mouse enters the window
			AcceptFocus = false;
			
			sw = new ScrolledWindow ();
			sw.HscrollbarPolicy = PolicyType.Never;
			sw.VscrollbarPolicy = PolicyType.Never;
			
			tree = new ObjectValueTreeView ();
			sw.Add (tree);
			Add (sw);
			
			tree.Frame = frame;
			tree.CompactView = true;
			tree.AllowAdding = false;
			tree.AllowEditing = true;
			tree.HeadersVisible = false;
			tree.AllowPinning = true;
			tree.PinnedWatch = watch;
			DocumentLocation location = editor.Document.OffsetToLocation (offset);
			tree.PinnedWatchLine = location.Line + 1;
			tree.PinnedWatchFile = ((ExtensibleTextEditor)editor).View.ContentName;
			
			tree.AddValue (value);
			tree.Selection.UnselectAll ();
			tree.SizeAllocated += OnTreeSizeChanged;
			tree.PinStatusChanged += delegate {
				Destroy ();
			};
			
			sw.ShowAll ();
			
			tree.StartEditing += delegate {
				Modal = true;
			};
			
			tree.EndEditing += delegate {
				Modal = false;
			};
		}
Exemplo n.º 18
0
 public Mono.Debugging.Client.StackFrame[] GetStackFrames(int firstIndex, int lastIndex)
 {
     if (stackFrames == null)
     {
         stackFrames = new Mono.Debugging.Client.StackFrame[Math.Min(lastIndex - firstIndex, frames.Length - firstIndex)];
         for (int i = firstIndex; i < stackFrames.Length + firstIndex; i++)
         {
             stackFrames[i] = new Mono.Debugging.Client.StackFrame(frames[i].id,
                                                                   new SourceLocation(
                                                                       frames[i].name,
                                                                       frames[i].source?.path,
                                                                       frames[i].line,
                                                                       frames[i].column,
                                                                       -1, -1),
                                                                   "C#");
         }
     }
     return(stackFrames);
 }
Exemplo n.º 19
0
        public StackFrame [] GetStackFrames(int firstIndex, int lastIndex)
        {
            //Optimisation for getting 1st frame of thread(used for ThreadPad)
            if (firstIndex == 0 && lastIndex == 1 && FrameCount > 0)
            {
                return new StackFrame[] { new VsCodeStackFrame(this.format, threadId, 0, frames[0]) }
            }
            ;

            var stackFrames = new StackFrame [Math.Min(lastIndex - firstIndex, FrameCount - firstIndex)];
            var format      = VsCodeStackFrame.GetStackFrameFormat(session.EvaluationOptions);
            var body        = session.protocolClient.SendRequestSync(new StackTraceRequest(threadId)
            {
                StartFrame = firstIndex, Levels = stackFrames.Length, Format = format
            });

            for (int i = 0; i < stackFrames.Length; i++)
            {
                frames[i + firstIndex] = body.StackFrames [i];
                stackFrames[i]         = new VsCodeStackFrame(format, threadId, i, body.StackFrames [i]);
            }
            return(stackFrames);
        }
Exemplo n.º 20
0
		internal static void ConnectCallbacks (StackFrame parentFrame, params ObjectValue[] values)
		{
			Dictionary<IObjectValueUpdater, List<UpdateCallback>> callbacks = null;
			List<ObjectValue> valueList = new List<ObjectValue> (values);
			for (int n=0; n<valueList.Count; n++) {
				ObjectValue val = valueList [n];
				val.parentFrame = parentFrame;
				UpdateCallback cb = val.GetUpdateCallback ();
				if (cb != null) {
					if (callbacks == null)
						callbacks = new Dictionary<IObjectValueUpdater, List<UpdateCallback>> ();
					List<UpdateCallback> list;
					if (!callbacks.TryGetValue (val.Updater, out list)) {
						list = new List<UpdateCallback> ();
						callbacks [val.Updater] = list;
					}
					list.Add (cb);
				}
				if (val.children != null)
					valueList.AddRange (val.children);
			}
			if (callbacks != null) {
				// Do the callback connection in a background thread
				System.Threading.ThreadPool.QueueUserWorkItem (delegate {
					foreach (KeyValuePair<IObjectValueUpdater, List<UpdateCallback>> cbs in callbacks) {
						cbs.Key.RegisterUpdateCallbacks (cbs.Value.ToArray ());
					}
				});
			}
		}
Exemplo n.º 21
0
		string EvaluateMethodName (StackFrame frame)
		{
			var methodNameBuilder = new StringBuilder (frame.SourceLocation.MethodName);
			var options = DebuggingService.DebuggerSession.Options.EvaluationOptions.Clone ();
			if (ShowParameterValue) {
				options.AllowMethodEvaluation = true;
				options.AllowToStringCalls = true;
				options.AllowTargetInvoke = true;
			} else {
				options.AllowMethodEvaluation = false;
				options.AllowToStringCalls = false;
				options.AllowTargetInvoke = false;
			}

			var args = frame.GetParameters (options);

			//MethodName starting with "["... it's something like [ExternalCode]
			if (!frame.SourceLocation.MethodName.StartsWith ("[", StringComparison.Ordinal)) {
				if (ShowModuleName && !string.IsNullOrEmpty (frame.FullModuleName)) {
					methodNameBuilder.Insert (0, System.IO.Path.GetFileName (frame.FullModuleName) + "!");
				}
				if (ShowParameterType || ShowParameterName || ShowParameterValue) {
					methodNameBuilder.Append ("(");
					for (int n = 0; n < args.Length; n++) {
						if (n > 0)
							methodNameBuilder.Append (", ");
						if (ShowParameterType) {
							methodNameBuilder.Append (args [n].TypeName);
							if (ShowParameterName)
								methodNameBuilder.Append (" ");
						}
						if (ShowParameterName)
							methodNameBuilder.Append (args [n].Name);
						if (ShowParameterValue) {
							if (ShowParameterType || ShowParameterName)
								methodNameBuilder.Append (" = ");
							var val = args [n].Value ?? "";
							methodNameBuilder.Append (val.Replace ("\r\n", " ").Replace ("\n", " "));
						}
					}
					methodNameBuilder.Append (")");
				}
			}

			return methodNameBuilder.ToString ();
		}
		public override void Setup ()
		{
			base.Setup ();
			ds = Start ("TestEvaluation");
			frame = ds.ActiveThread.Backtrace.GetFrame (0);
		}
Exemplo n.º 23
0
		static void EnsureCreated()
		{
			lock (_lock)
			{
				if (_session != null)
					return;

				_session = new SoftDebuggerSession();
				_session.Breakpoints = BreakEvents;

				_session.ExceptionHandler = ex =>
				{
					if (Configuration.Current.LogInternalErrors)
					{
						Log.Error("Internal debugger error:", ex.GetType());
						Log.Error(ex.ToString());
					}

					return true;
				};

				_session.LogWriter = (isStdErr, text) =>
				{
					if (Configuration.Current.LogRuntimeSpew)
						Log.NoticeSameLine("[Mono] {0}", text); // The string already has a line feed.
				};

				_session.OutputWriter = (isStdErr, text) =>
				{
					//lock (Log.Lock)
					//{
						if (Callback != null)
						{
							Callback.Invoke(isStdErr ? "ErrorOutput" : "Output", null, null, text);
						}
						else
						{
							if (isStdErr)
								Console.Error.Write(text);
							else
								Console.Write(text);
						}
					//}
				};

				_session.TypeResolverHandler += (identifier, location) =>
				{
					// I honestly have no idea how correct this is. I suspect you
					// could probably break it in some corner cases. It does make
					// something like `p Android.Runtime.JNIEnv.Handle` work,
					// though, which would otherwise have required `global::` to
					// be explicitly prepended.

					if (identifier == "__EXCEPTION_OBJECT__")
						return null;

					foreach (var loc in ActiveFrame.GetAllLocals())
						if (loc.Name == identifier)
							return null;

					return identifier;
				};

				_session.TargetEvent += (sender, e) =>
				{
					Log.Debug("Event: '{0}'", e.Type);
				};

				_session.TargetStarted += (sender, e) =>
				{
					_activeFrame = null;

					/*
					if (_showResumeMessage)
						Log.Notice("Inferior process '{0}' ('{1}') resumed",
							ActiveProcess.Id, StringizeTarget());
					*/
				};

				_session.TargetReady += (sender, e) =>
				{
					_activeProcess = _session.GetProcesses().SingleOrDefault();

					// The inferior process has launched, so we can safely
					// set our `SIGINT` handler without it interfering with
					// the inferior.
					CommandLine.SetControlCHandler();

					/*
					Log.Notice("Inferior process '{0}' ('{1}') started",
						ActiveProcess.Id, StringizeTarget());
					*/
				};

				_session.TargetStopped += (sender, e) =>
				{
					//Log.Notice("Inferior process '{0}' ('{1}') suspended",
					//	ActiveProcess.Id, StringizeTarget());
					//Log.Emphasis(Utilities.StringizeFrame(ActiveFrame, true));

					if (Callback != null)
					{
						Callback.Invoke("TargetStopped", ActiveFrame.SourceLocation, e.Thread, null);
					}

					CommandLine.ResumeEvent.Set();
				};

				_session.TargetInterrupted += (sender, e) =>
				{
					Log.Notice("Inferior process '{0}' ('{1}') interrupted",
						ActiveProcess.Id, StringizeTarget());
					Log.Emphasis(Utilities.StringizeFrame(ActiveFrame, true));

					CommandLine.ResumeEvent.Set();
				};

				_session.TargetHitBreakpoint += (sender, e) =>
				{
					// var bp = e.BreakEvent as Breakpoint;
					// var fbp = e.BreakEvent as FunctionBreakpoint;

					/*
					if (fbp != null)
						Log.Notice("Hit method breakpoint on '{0}'", fbp.FunctionName);
					else
					{
						var cond = bp.ConditionExpression != null ?
							string.Format(" (condition '{0}' met)", bp.ConditionExpression) :
							string.Empty;

						Log.Notice("Hit breakpoint at '{0}:{1}'{2}", bp.FileName, bp.Line, cond);
					}

					Log.Emphasis(Utilities.StringizeFrame(ActiveFrame, true));
					*/

					if (Callback != null)
					{
						Callback.Invoke("TargetHitBreakpoint", ActiveFrame.SourceLocation, e.Thread, null);
					}

					CommandLine.ResumeEvent.Set();
				};

				_session.TargetExited += (sender, e) =>
				{
					var p = ActiveProcess;

					/*
					// Can happen when a remote connection attempt fails.
					if (p == null)
					{
						if (_kind == SessionKind.Listening)
							Log.Notice("Listening socket closed");
						else if (_kind == SessionKind.Connected)
							Log.Notice("Connection attempt terminated");
						else
							Log.Notice("Failed to connect to '{0}'", StringizeTarget());
					}
					else
						Log.Notice("Inferior process '{0}' ('{1}') exited", ActiveProcess.Id, StringizeTarget());
					*/

					// Make sure we clean everything up on a normal exit.
					Kill();

					_debuggeeKilled = true;
					_kind = SessionKind.Disconnected;

					if (Callback != null)
					{
						Callback.Invoke("TargetExited", null, null, null);
					}

					CommandLine.ResumeEvent.Set();
				};

				_session.TargetExceptionThrown += (sender, e) =>
				{
					var ex = ActiveException;

					//Log.Notice("Trapped first-chance exception of type '{0}'", ex.Type);
					//Log.Emphasis(Utilities.StringizeFrame(ActiveFrame, true));

					PrintException(ex);

					if (Callback != null)
					{
						Callback.Invoke("TargetExceptionThrown", ActiveFrame.SourceLocation, e.Thread, null);
					}

					CommandLine.ResumeEvent.Set();
				};

				_session.TargetUnhandledException += (sender, e) =>
				{
					var ex = ActiveException;

					//Log.Notice("Trapped unhandled exception of type '{0}'", ex.Type);
					//Log.Emphasis(Utilities.StringizeFrame(ActiveFrame, true));

					PrintException(ex);

					if (Callback != null)
					{
						Callback.Invoke("TargetUnhandledException", ActiveFrame.SourceLocation, e.Thread, null);
					}

					CommandLine.ResumeEvent.Set();
				};

				_session.TargetThreadStarted += (sender, e) =>
				{
					//Log.Notice("Inferior thread '{0}' ('{1}') started",
					//	e.Thread.Id, e.Thread.Name);

					if (Callback != null)
					{
						Callback.Invoke("TargetThreadStarted", null, e.Thread, null);
					}
				};

				_session.TargetThreadStopped += (sender, e) =>
				{
					//Log.Notice("Inferior thread '{0}' ('{1}') exited",
					//	e.Thread.Id, e.Thread.Name);

					if (Callback != null)
					{
						Callback.Invoke("TargetThreadStopped", null, e.Thread, null);
					}
				};
			}
		}
Exemplo n.º 24
0
		protected void Start (string test)
		{
			TargetRuntime runtime;

			switch (EngineId) {
			case "MonoDevelop.Debugger.Win32":
				runtime = Runtime.SystemAssemblyService.GetTargetRuntime ("MS.NET");
				break;
			case "Mono.Debugger.Soft":
				runtime = Runtime.SystemAssemblyService.GetTargetRuntimes ()
					.OfType<MonoTargetRuntime> ()
					.OrderByDescending ((o) => {
					//Attempt to find latest version of Mono registred in IDE and use that for unit tests
					if (string.IsNullOrWhiteSpace (o.Version) || o.Version == "Unknown")
						return new Version (0, 0, 0, 0);
					int indexOfBeforeDetails = o.Version.IndexOf (" (", StringComparison.Ordinal);
					if (indexOfBeforeDetails == -1)
						return new Version (0, 0, 0, 0);
					string hopefullyVersion = o.Version.Remove (indexOfBeforeDetails);
					Version version;
					if (Version.TryParse (hopefullyVersion, out version)) {
						return version;
					} else {
						return new Version (0, 0, 0, 0);
					}
				}).FirstOrDefault ();
				break;
			default:
				runtime = Runtime.SystemAssemblyService.DefaultRuntime;
				break;
			}

			if (runtime == null) {
				Assert.Ignore ("Runtime not found for: {0}", EngineId);
				return;
			}

			Console.WriteLine ("Target Runtime: " + runtime.DisplayRuntimeName + " " + runtime.Version);

			// main/build/tests
			FilePath path = Path.GetDirectoryName (GetType ().Assembly.Location);
			var exe = Path.Combine (path, "MonoDevelop.Debugger.Tests.TestApp.exe");

			var cmd = new DotNetExecutionCommand ();
			cmd.TargetRuntime = runtime;
			cmd.Command = exe;
			cmd.Arguments = test;

			if (Platform.IsWindows) {
				var monoRuntime = runtime as MonoTargetRuntime;
				if (monoRuntime != null) {
					var psi = new System.Diagnostics.ProcessStartInfo (Path.Combine (monoRuntime.Prefix, "bin", "pdb2mdb.bat"), cmd.Command);
					psi.UseShellExecute = false;
					psi.CreateNoWindow = true;
					System.Diagnostics.Process.Start (psi).WaitForExit ();
				}
			}

			var dsi = engine.CreateDebuggerStartInfo (cmd);
			var soft = dsi as SoftDebuggerStartInfo;

			if (soft != null) {
				var assemblyName = AssemblyName.GetAssemblyName (exe);

				soft.UserAssemblyNames = new List<AssemblyName> ();
				soft.UserAssemblyNames.Add (assemblyName);
			}

			Session = engine.CreateSession ();
			var ops = new DebuggerSessionOptions ();
			ops.ProjectAssembliesOnly = true;
			ops.EvaluationOptions = EvaluationOptions.DefaultOptions;
			ops.EvaluationOptions.AllowTargetInvoke = AllowTargetInvokes;
			ops.EvaluationOptions.EvaluationTimeout = 100000;

			path = path.ParentDirectory.ParentDirectory.Combine ("src", "addins", "MonoDevelop.Debugger", "MonoDevelop.Debugger.Tests.TestApp", test + ".cs").FullPath;
			SourceFile = TextFile.ReadFile (path);
			TestName = test;
			AddBreakpoint ("break");
			
			var done = new ManualResetEvent (false);

			Session.TargetHitBreakpoint += (sender, e) => {
				Frame = e.Backtrace.GetFrame (0);
				lastStoppedPosition = Frame.SourceLocation;
				targetStoppedEvent.Set ();
				done.Set ();
			};

			Session.TargetExceptionThrown += (sender, e) => {
				Frame = e.Backtrace.GetFrame (0);
				for (int i = 0; i < e.Backtrace.FrameCount; i++) {
					if (!e.Backtrace.GetFrame (i).IsExternalCode) {
						Frame = e.Backtrace.GetFrame (i);
						break;
					}
				}
				lastStoppedPosition = Frame.SourceLocation;
				targetStoppedEvent.Set ();
			};

			Session.TargetStopped += (sender, e) => {
				//This can be null in case of ForcedStop
				//which is called when exception is thrown
				//when Continue & Stepping is executed
				if (e.Backtrace != null) {
					Frame = e.Backtrace.GetFrame (0);
					lastStoppedPosition = Frame.SourceLocation;
					targetStoppedEvent.Set ();
				} else {
					Console.WriteLine ("e.Backtrace is null");
				}
			};

			var targetExited = new ManualResetEvent (false);
			Session.TargetExited += delegate {
				targetExited.Set ();
			};

			Session.Run (dsi, ops);
			Session.ExceptionHandler = (ex) => {
				Console.WriteLine ("Session.ExceptionHandler:" + Environment.NewLine + ex.ToString ());
				return true;
			};
			switch (WaitHandle.WaitAny (new WaitHandle[]{ done, targetExited }, 30000)) {
			case 0:
				//Breakpoint is hit good... run tests now
				break;
			case 1:
				throw new Exception ("Test application exited before hitting breakpoint");
			default:
				throw new Exception ("Timeout while waiting for initial breakpoint");
			}
			if (Session is SoftDebuggerSession) {
				Console.WriteLine ("SDB protocol version:" + ((SoftDebuggerSession)Session).ProtocolVersion);
			}
		}
Exemplo n.º 25
0
 internal void ConnectCallback(StackFrame parentFrame)
 {
     ObjectValue.ConnectCallbacks(parentFrame, exception);
 }
Exemplo n.º 26
0
		internal void ConnectCallback (StackFrame parentFrame)
		{
			ObjectValue.ConnectCallbacks (parentFrame, exception);
		}
Exemplo n.º 27
0
		string EvaluateMethodName (StackFrame frame, EvaluationOptions options)
		{
			StringBuilder method = new StringBuilder (frame.SourceLocation.MethodName);
			ObjectValue[] args = frame.GetParameters (options);

			if (args.Length != 0 || !frame.SourceLocation.MethodName.StartsWith ("[", StringComparison.Ordinal)) {
				method.Append (" (");
				for (int n = 0; n < args.Length; n++) {
					if (n > 0)
						method.Append (", ");
					method.Append (args[n].Name).Append ("=").Append (args[n].Value);
				}
				method.Append (")");
			}

			return method.ToString ();
		}
Exemplo n.º 28
0
		StackFrame CheckFrameIsInFile (StackFrame frame)
		{
			if (!string.IsNullOrEmpty (ContentName) && frame != null && !string.IsNullOrEmpty (frame.SourceLocation.FileName)
				&& ((FilePath)frame.SourceLocation.FileName).FullPath == ((FilePath)ContentName).FullPath)
				return frame;
			return null;
		}
Exemplo n.º 29
0
		SourceLocation CheckFrameIsInFile (StackFrame frame)
		{
			return frame != null ? CheckLocationIsInFile (frame.SourceLocation) : null;
		}
Exemplo n.º 30
0
 public void Setup()
 {
     mDebuggerSession = Start(string.Empty);
     frame = mDebuggerSession.ActiveThread.Backtrace.GetFrame(0);
 }
Exemplo n.º 31
0
 public DecompilerFormatter(StackFrame frame)
 {
     _frame = frame;
     _writer = Logger.WriteInfoString;
     IndentationString = "    ";
 }
Exemplo n.º 32
0
		void ShowLoadSourceFile (StackFrame sf)
		{
			if (messageOverlayWindow != null) {
				messageOverlayWindow.Destroy ();
				messageOverlayWindow = null;
			}
			messageOverlayWindow = new OverlayMessageWindow ();

			var hbox = new HBox ();
			hbox.Spacing = 8;
			var label = new Label (string.Format ("{0} not found. Find source file at alternative location.", Path.GetFileName (sf.SourceLocation.FileName)));
			hbox.TooltipText = sf.SourceLocation.FileName;
			var color = (HslColor)editor.ColorStyle.NotificationText.Foreground;
			label.ModifyFg (StateType.Normal, color);

			int w, h;
			label.Layout.GetPixelSize (out w, out h);

			hbox.PackStart (label, true, true, 0);
			var openButton = new Button (Gtk.Stock.Open);
			openButton.WidthRequest = 60;
			hbox.PackEnd (openButton, false, false, 0); 

			var container = new HBox ();
			const int containerPadding = 8;
			container.PackStart (hbox, true, true, containerPadding); 
			messageOverlayWindow.Child = container; 
			messageOverlayWindow.ShowOverlay (editor);

			messageOverlayWindow.SizeFunc = () => openButton.SizeRequest ().Width + w + hbox.Spacing * 5 + containerPadding * 2;
			openButton.Clicked += delegate {
				var dlg = new OpenFileDialog (GettextCatalog.GetString ("File to Open"), SelectFileDialogAction.Open) {
					TransientFor = IdeApp.Workbench.RootWindow,
					ShowEncodingSelector = true,
					ShowViewerSelector = true
				};
				if (!dlg.Run ())
					return;
				var newFilePath = dlg.SelectedFile;
				try {
					if (File.Exists (newFilePath)) {
						if (SourceCodeLookup.CheckFileMd5 (newFilePath, sf.SourceLocation.FileHash)) {
							SourceCodeLookup.AddLoadedFile (newFilePath, sf.SourceLocation.FileName);
							sf.UpdateSourceFile (newFilePath);
							if (IdeApp.Workbench.OpenDocument (newFilePath, null, sf.SourceLocation.Line, 1, OpenDocumentOptions.Debugger) != null) {
								this.WorkbenchWindow.CloseWindow (false);
							}
						} else {
							MessageService.ShowWarning ("File checksum doesn't match.");
						}
					} else {
						MessageService.ShowWarning ("File not found.");
					}
				} catch (Exception) {
					MessageService.ShowWarning ("Error opening file");
				}
			};
		}
		protected virtual void OnDebuggerStopped (object s, EventArgs a)
		{
			tree.ResetChangeTracking ();
			tree.ClearAll ();
			lastFrame = null;
			initialResume = true;
		}
        public MonoDebugSession() : base()
        {
            _variableHandles = new Handles <ObjectValue[]>();
            _frameHandles    = new Handles <Mono.Debugging.Client.StackFrame>();
            _seenThreads     = new Dictionary <int, Thread>();

            _debuggerSessionOptions = new DebuggerSessionOptions {
                EvaluationOptions = EvaluationOptions.DefaultOptions
            };

            _session             = new XamarinDebuggerSession();
            _session.Breakpoints = new BreakpointStore();

            _breakpoints = new SortedDictionary <long, BreakEvent>();
            _catchpoints = new List <Catchpoint>();

            DebuggerLoggingService.CustomLogger = new CustomLogger();

            _session.ExceptionHandler = ex => {
                return(true);
            };

            _session.LogWriter = (isStdErr, text) => {
            };

            _session.TargetStopped += (sender, e) => {
                Stopped();
                SendEvent(CreateStoppedEvent("step", e.Thread));
                _resumeEvent.Set();
            };

            _session.TargetHitBreakpoint += (sender, e) => {
                Stopped();
                SendEvent(CreateStoppedEvent("breakpoint", e.Thread));
                _resumeEvent.Set();
            };

            _session.TargetExceptionThrown += (sender, e) => {
                Stopped();
                var ex = DebuggerActiveException();
                if (ex != null)
                {
                    _exception = ex.Instance;
                    SendEvent(CreateStoppedEvent("exception", e.Thread, ex.Message));
                }
                _resumeEvent.Set();
            };

            _session.TargetUnhandledException += (sender, e) => {
                Stopped();
                var ex = DebuggerActiveException();
                if (ex != null)
                {
                    _exception = ex.Instance;
                    SendEvent(CreateStoppedEvent("exception", e.Thread, ex.Message));
                }
                _resumeEvent.Set();
            };

            _session.TargetStarted += (sender, e) => {
                _activeFrame = null;
            };

            _session.TargetReady += (sender, e) => {
                _activeProcess = _session.GetProcesses().SingleOrDefault();
            };

            _session.TargetExited += (sender, e) => {
                DebuggerKill();

                _debuggeeKilled = true;

                Terminate("target exited");

                _resumeEvent.Set();
            };

            _session.TargetInterrupted += (sender, e) => {
                _resumeEvent.Set();
            };

            _session.TargetEvent += (sender, e) => {
            };

            _session.TargetThreadStarted += (sender, e) => {
                int tid = (int)e.Thread.Id;
                lock (_seenThreads) {
                    _seenThreads[tid] = new Thread(tid, e.Thread.Name);
                }
                SendEvent(new ThreadEvent("started", tid));
            };

            _session.TargetThreadStopped += (sender, e) => {
                int tid = (int)e.Thread.Id;
                lock (_seenThreads) {
                    _seenThreads.Remove(tid);
                }
                SendEvent(new ThreadEvent("exited", tid));
            };

            _session.OutputWriter = (isStdErr, text) => {
                SendOutput(isStdErr ? "stderr" : "stdout", text);
            };
        }
		public virtual void OnUpdateList ()
		{
			needsUpdate = false;
			if (DebuggingService.CurrentFrame != lastFrame)
				tree.Frame = DebuggingService.CurrentFrame;
			lastFrame = DebuggingService.CurrentFrame;
		}
Exemplo n.º 36
0
		public void Setup ()
		{
			ds = Start ("TestEvaluation");
			frame = ds.ActiveThread.Backtrace.GetFrame (0);
		}
		protected virtual void OnEvaluationOptionsChanged (object s, EventArgs a)
		{
			if (!DebuggingService.IsRunning) {
				lastFrame = null;
				if (container != null && container.ContentVisible)
					OnUpdateList ();
				else
					needsUpdate = true;
			}
		}
Exemplo n.º 38
0
		protected void Start (string test)
		{
			TargetRuntime runtime;

			switch (EngineId) {
			case "MonoDevelop.Debugger.Win32":
				runtime = Runtime.SystemAssemblyService.GetTargetRuntime ("MS.NET");
				break;
			case "Mono.Debugger.Soft":
				runtime = Runtime.SystemAssemblyService.GetTargetRuntimes ()
					.OfType<MonoTargetRuntime> ()
					.OrderByDescending(o => o.Version)
					.FirstOrDefault ();
				break;
			default:
				runtime = Runtime.SystemAssemblyService.DefaultRuntime;
				break;
			}

			if (runtime == null) {
				Assert.Ignore ("Runtime not found for: {0}", EngineId);
				return;
			}

			Console.WriteLine ("Target Runtime: " + runtime.DisplayRuntimeName + " " + runtime.Version);

			// main/build/tests
			FilePath path = Path.GetDirectoryName (GetType ().Assembly.Location);
			var exe = Path.Combine (path, "MonoDevelop.Debugger.Tests.TestApp.exe");

			var cmd = new DotNetExecutionCommand ();
			cmd.TargetRuntime = runtime;
			cmd.Command = exe;
			cmd.Arguments = test;

			if (Platform.IsWindows) {
				var monoRuntime = runtime as MonoTargetRuntime;
				if (monoRuntime != null) {
					var psi = new System.Diagnostics.ProcessStartInfo (Path.Combine (monoRuntime.Prefix, "bin", "pdb2mdb.bat"), cmd.Command);
					psi.UseShellExecute = false;
					psi.CreateNoWindow = true;
					System.Diagnostics.Process.Start (psi).WaitForExit ();
				}
			}

			var dsi = engine.CreateDebuggerStartInfo (cmd);
			var soft = dsi as SoftDebuggerStartInfo;

			if (soft != null) {
				var assemblyName = AssemblyName.GetAssemblyName (exe);

				soft.UserAssemblyNames = new List<AssemblyName> ();
				soft.UserAssemblyNames.Add (assemblyName);
			}

			Session = engine.CreateSession ();
			var ops = new DebuggerSessionOptions ();
			ops.EvaluationOptions = EvaluationOptions.DefaultOptions;
			ops.EvaluationOptions.AllowTargetInvoke = AllowTargetInvokes;
			ops.EvaluationOptions.EvaluationTimeout = 100000;

			path = path.ParentDirectory.ParentDirectory.Combine ("src", "addins", "MonoDevelop.Debugger", "MonoDevelop.Debugger.Tests.TestApp", test + ".cs").FullPath;
			SourceFile = TextFile.ReadFile (path);
			TestName = test;
			AddBreakpoint ("break");
			
			var done = new ManualResetEvent (false);
			
			Session.OutputWriter = (isStderr, text) => Console.WriteLine ("PROC:" + text);

			Session.TargetHitBreakpoint += (sender, e) => {
				done.Set ();
				Frame = e.Backtrace.GetFrame (0);
				lastStoppedPosition = Frame.SourceLocation;
				targetStoppedEvent.Set ();
			};

			Session.TargetExceptionThrown += (sender, e) => {
				Frame = e.Backtrace.GetFrame (0);
				for (int i = 0; i < e.Backtrace.FrameCount; i++) {
					if (!e.Backtrace.GetFrame (i).IsExternalCode) {
						Frame = e.Backtrace.GetFrame (i);
						break;
					}
				}
				lastStoppedPosition = Frame.SourceLocation;
				targetStoppedEvent.Set ();
			};

			Session.TargetStopped += (sender, e) => {
				Frame = e.Backtrace.GetFrame (0);
				lastStoppedPosition = Frame.SourceLocation;
				targetStoppedEvent.Set ();
			};

			var targetExited = new ManualResetEvent (false);
			Session.TargetExited += delegate {
				targetExited.Set ();
			};

			Session.Run (dsi, ops);
			switch (WaitHandle.WaitAny (new WaitHandle[]{ done, targetExited }, 30000)) {
			case 0:
				//Breakpoint is hit good... run tests now
				break;
			case 1:
				throw new Exception ("Test application exited before hitting breakpoint");
			default:
				throw new Exception ("Timeout while waiting for initial breakpoint");
			}
		}