Esempio n. 1
0
        public void AttachToProcess(long pid, DebuggerSessionOptions sessionOptions)
        {
            Report.Initialize();

            this.SessionOptions = sessionOptions;
            DebuggerConfiguration config = new DebuggerConfiguration();

            mdbAdaptor.Configuration = config;
            mdbAdaptor.InitializeConfiguration();
            config.LoadConfiguration();
            debugger = new MD.Debugger(config);

            DebuggerOptions options = DebuggerOptions.ParseCommandLine(new string[0]);

            options.StopInMain = false;
            session            = new MD.DebuggerSession(config, options, "main", (IExpressionParser)null);
            mdbAdaptor.Session = session;

            Process proc = debugger.Attach(session, (int)pid);

            OnInitialized(debugger, proc);

            ST.ThreadPool.QueueUserWorkItem(delegate {
                NotifyStarted();
            });
        }
        public DebuggerOptionsPanelWidget()
        {
            this.Build();
            options = DebuggingService.GetUserOptions();
            projectCodeOnly.Active    = options.ProjectAssembliesOnly;
            checkAllowEval.Active     = options.EvaluationOptions.AllowTargetInvoke;
            checkToString.Active      = options.EvaluationOptions.AllowToStringCalls;
            checkShowBaseGroup.Active = !options.EvaluationOptions.FlattenHierarchy;
            checkGroupPrivate.Active  = options.EvaluationOptions.GroupPrivateMembers;
            checkGroupStatic.Active   = options.EvaluationOptions.GroupStaticMembers;
            checkToString.Sensitive   = checkAllowEval.Active;
            spinTimeout.Value         = options.EvaluationOptions.EvaluationTimeout;

            // Debugger priorities
            engineStore      = new Gtk.ListStore(typeof(string), typeof(string));
            engineList.Model = engineStore;
            engineList.AppendColumn("", new Gtk.CellRendererText(), "text", 1);

            foreach (DebuggerEngine engine in DebuggingService.GetDebuggerEngines())
            {
                engineStore.AppendValues(engine.Id, engine.Name);
            }
            UpdatePriorityButtons();
            engineList.Selection.Changed += HandleEngineListSelectionChanged;
        }
        protected DebuggerSession Start(string test)
        {
            DotNetExecutionCommand cmd = new DotNetExecutionCommand();

            cmd.Command   = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), "MonoDevelop.Debugger.Tests.TestApp.exe");
            cmd.Arguments = test;

            DebuggerStartInfo      si      = engine.CreateDebuggerStartInfo(cmd);
            DebuggerSession        session = engine.CreateSession();
            DebuggerSessionOptions ops     = new DebuggerSessionOptions();

            ops.EvaluationOptions = EvaluationOptions.DefaultOptions;
            ops.EvaluationOptions.EvaluationTimeout = 100000;

            FilePath path = Util.TestsRootDir;

            path = path.ParentDirectory.Combine("src", "addins", "MonoDevelop.Debugger", "MonoDevelop.Debugger.Tests.TestApp", "Main.cs").FullPath;
            TextFile file = TextFile.ReadFile(path);
            int      i    = file.Text.IndexOf("void " + test);

            if (i == -1)
            {
                throw new Exception("Test not found: " + test);
            }
            i = file.Text.IndexOf("/*break*/", i);
            if (i == -1)
            {
                throw new Exception("Break marker not found: " + test);
            }
            int line, col;

            file.GetLineColumnFromPosition(i, out line, out col);
            Breakpoint bp = session.Breakpoints.Add(path, line);

            bp.Enabled = true;

            ManualResetEvent done = new ManualResetEvent(false);

            session.OutputWriter = delegate(bool isStderr, string text)
            {
                Console.WriteLine("PROC:" + text);
            };

            session.TargetHitBreakpoint += delegate
            {
                done.Set();
            };

            session.Run(si, ops);
            if (!done.WaitOne(3000))
            {
                throw new Exception("Timeout while waiting for initial breakpoint");
            }

            return(session);
        }
Esempio n. 4
0
        static void AttachStackFrame(ObjectValue value, DebuggerSessionOptions sessionOptions)
        {
            var location   = new SourceLocation(string.Empty, "test.cs", 1, 1, 1, 1);
            var stackFrame = new StackFrame(0, location, "C#", false, true);
            var session    = new CSharpInteractiveDebuggerSession();

            session.Run(new DebuggerStartInfo(), sessionOptions);

            stackFrame.Attach(session);
            stackFrame.ConnectCallbacks(value);
        }
Esempio n. 5
0
        public static void ResetOptions()
        {
            // No need to lock on this data.

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

            Options.EvaluationOptions.UseExternalTypeResolver = true;
        }
        public DebuggerOptionsPanelWidget()
        {
            Build();

            options = DebuggingService.GetUserOptions();
            checkProjectCodeOnly.Active = options.ProjectAssembliesOnly;
            checkStepOverPropertiesAndOperators.Active = options.StepOverPropertiesAndOperators;
            checkAllowEval.Active        = options.EvaluationOptions.AllowTargetInvoke;
            checkAllowToString.Active    = options.EvaluationOptions.AllowToStringCalls;
            checkShowBaseGroup.Active    = !options.EvaluationOptions.FlattenHierarchy;
            checkGroupPrivate.Active     = options.EvaluationOptions.GroupPrivateMembers;
            checkGroupStatic.Active      = options.EvaluationOptions.GroupStaticMembers;
            checkAllowToString.Sensitive = checkAllowEval.Active;
            spinTimeout.Value            = options.EvaluationOptions.EvaluationTimeout;
        }
Esempio n. 7
0
        public DebuggerOptionsPanelWidget()
        {
            Build();

            options = DebuggingService.GetUserOptions();
            checkStepIntoExternalCode.Active          = !options.ProjectAssembliesOnly;
            comboAutomaticSourceDownload.SelectedItem = PropertyService.Get("MonoDevelop.Debugger.DebuggingService.AutomaticSourceDownload", AutomaticSourceDownload.Ask);

            checkStepOverPropertiesAndOperators.Active = options.StepOverPropertiesAndOperators;
            checkAllowEval.Active        = options.EvaluationOptions.AllowTargetInvoke;
            checkAllowToString.Active    = options.EvaluationOptions.AllowToStringCalls;
            checkShowBaseGroup.Active    = !options.EvaluationOptions.FlattenHierarchy;
            checkGroupPrivate.Active     = options.EvaluationOptions.GroupPrivateMembers;
            checkGroupStatic.Active      = options.EvaluationOptions.GroupStaticMembers;
            checkAllowToString.Sensitive = checkAllowEval.Active;
            spinTimeout.Value            = options.EvaluationOptions.EvaluationTimeout;
            enableLogging.Active         = PropertyService.Get("MonoDevelop.Debugger.DebuggingService.DebuggerLogging", false);
            useNewTreeView.Active        = PropertyService.Get("MonoDevelop.Debugger.UseNewTreeView", true);
        }
Esempio n. 8
0
        public static void SetUserOptions(DebuggerSessionOptions options)
        {
            PropertyService.Set("MonoDevelop.Debugger.DebuggingService.ProjectAssembliesOnly", options.ProjectAssembliesOnly);
            PropertyService.Set("MonoDevelop.Debugger.DebuggingService.AllowTargetInvoke", options.EvaluationOptions.AllowTargetInvoke);
            PropertyService.Set("MonoDevelop.Debugger.DebuggingService.AllowToStringCalls", options.EvaluationOptions.AllowToStringCalls);
            PropertyService.Set("MonoDevelop.Debugger.DebuggingService.EvaluationTimeout", options.EvaluationOptions.EvaluationTimeout);
            PropertyService.Set("MonoDevelop.Debugger.DebuggingService.FlattenHierarchy", options.EvaluationOptions.FlattenHierarchy);
            PropertyService.Set("MonoDevelop.Debugger.DebuggingService.GroupPrivateMembers", options.EvaluationOptions.GroupPrivateMembers);
            PropertyService.Set("MonoDevelop.Debugger.DebuggingService.GroupStaticMembers", options.EvaluationOptions.GroupStaticMembers);

            if (session != null)
            {
                session.Options.EvaluationOptions = GetUserOptions().EvaluationOptions;
                if (EvaluationOptionsChanged != null)
                {
                    EvaluationOptionsChanged(null, EventArgs.Empty);
                }
            }
        }
Esempio n. 9
0
        public SoftDebugger(MonoEngine engine)
        {
            _debugEngine = engine;

            _options = new DebuggerSessionOptions()
            {
                EvaluationOptions = EvaluationOptions.DefaultOptions
            };
            _options.EvaluationOptions.UseExternalTypeResolver = true;

            _session             = new SoftDebuggerSession();
            _session.Breakpoints = (_breakEvents = new BreakpointStore());

            _session.TypeResolverHandler      += event_TypeResolverHandler;
            _session.TargetReady              += event_TargetReady;
            _session.TargetExited             += event_TargetExited;
            _session.TargetThreadStarted      += event_TargetThreadStarted;
            _session.TargetThreadStopped      += event_TargetThreadStopped;
            _session.TargetHitBreakpoint      += event_TargetHitBreakpoint;
            _session.TargetUnhandledException += event_TargetUnhandledException;
        }
Esempio n. 10
0
        protected DebuggerSession Start(string test)
        {
            try {
                DebuggerStartInfo si = CreateDebuggerStartInfo();
                si.Command   = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), "UnitTests.TestApp.exe");
                si.Arguments = test;

                DebuggerSessionOptions ops = new DebuggerSessionOptions();
                ops.EvaluationOptions = EvaluationOptions.DefaultOptions;
                ops.EvaluationOptions.EvaluationTimeout = 100000;

                DebuggerSession session = CreateDebuggerSession();
                string          path    = Path.Combine(GetTestsDir(), "UnitTests.TestApp", "Main.cs");
                path = Path.GetFullPath(path);

                ManualResetEvent done = new ManualResetEvent(false);

                session.OutputWriter = delegate(bool isStderr, string text) {
                    Console.WriteLine("PROC:" + text);
                };

                session.TargetStopped += delegate {
                    done.Set();
                };

                session.Run(si, ops);
                if (!done.WaitOne(3000))
                {
                    throw new Exception("Timeout while waiting for initial breakpoint");
                }

                return(session);
            } catch (Exception ex) {
                Console.WriteLine(ex);
                throw;
            }
        }
Esempio n. 11
0
		public void Update (DebuggerSessionOptions options, StackFrame frame, bool disassemblySupported)
		{
			scrollView.Content = CreateContent (options, frame, disassemblySupported);
		}
Esempio n. 12
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.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) => {
                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");
            }
        }
        public UnityDebugSession()
        {
            Log.Write("Constructing UnityDebugSession");
            m_ResumeEvent     = new AutoResetEvent(false);
            m_Breakpoints     = new Dictionary <string, Dictionary <int, Breakpoint> >();
            m_VariableHandles = new Handles <ObjectValue[]>();
            m_FrameHandles    = new Handles <StackFrame>();
            m_SeenThreads     = new Dictionary <int, Thread>();

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

            m_Session             = new UnityDebuggerSession();
            m_Session.Breakpoints = new BreakpointStore();

            m_Catchpoints = new List <Catchpoint>();

            DebuggerLoggingService.CustomLogger = new CustomLogger();

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

            m_Session.LogWriter = (isStdErr, text) =>
            {
                SendOutput(isStdErr ? "stderr" : "stdout", text);
            };

            m_Session.TargetStopped += (sender, e) =>
            {
                if (e.Backtrace != null)
                {
                    Frame = e.Backtrace.GetFrame(0);
                }
                else
                {
                    SendOutput("stdout", "e.Bracktrace is null");
                }

                Stopped();
                SendEvent(CreateStoppedEvent("step", e.Thread));
                m_ResumeEvent.Set();
            };

            m_Session.TargetHitBreakpoint += (sender, e) =>
            {
                Frame = e.Backtrace.GetFrame(0);
                Stopped();
                SendEvent(CreateStoppedEvent("breakpoint", e.Thread));
                m_ResumeEvent.Set();
            };

            m_Session.TargetExceptionThrown += (sender, e) =>
            {
                Frame = e.Backtrace.GetFrame(0);
                for (var i = 0; i < e.Backtrace.FrameCount; i++)
                {
                    if (!e.Backtrace.GetFrame(i).IsExternalCode)
                    {
                        Frame = e.Backtrace.GetFrame(i);
                        break;
                    }
                }

                Stopped();
                var ex = DebuggerActiveException();
                if (ex != null)
                {
                    m_Exception = ex.Instance;
                    SendEvent(CreateStoppedEvent("exception", e.Thread, ex.Message));
                }

                m_ResumeEvent.Set();
            };

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

                m_ResumeEvent.Set();
            };

            m_Session.TargetStarted += (sender, e) =>
            {
            };

            m_Session.TargetReady += (sender, e) =>
            {
                m_ActiveProcess = m_Session.GetProcesses().SingleOrDefault();
            };

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

                Terminate("target exited");

                m_ResumeEvent.Set();
            };

            m_Session.TargetInterrupted += (sender, e) =>
            {
                m_ResumeEvent.Set();
            };

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

            m_Session.TargetThreadStarted += (sender, e) =>
            {
                var tid = (int)e.Thread.Id;
                lock (m_SeenThreads)
                {
                    m_SeenThreads[tid] = new Thread(tid, e.Thread.Name);
                }

                SendEvent(new ThreadEvent("started", tid));
            };

            m_Session.TargetThreadStopped += (sender, e) =>
            {
                var tid = (int)e.Thread.Id;
                lock (m_SeenThreads)
                {
                    m_SeenThreads.Remove(tid);
                }

                SendEvent(new ThreadEvent("exited", tid));
            };

            m_Session.OutputWriter = (isStdErr, text) =>
            {
                SendOutput(isStdErr ? "stderr" : "stdout", text);
            };

            Log.Write("Done constructing UnityDebugSession");
        }
Esempio n. 14
0
        public void ApplicationRunsWithDebuggerAndBreaks(bool useSharedRuntime, bool embedAssemblies, string fastDevType, bool allowDeltaInstall)
        {
            AssertCommercialBuild();
            AssertHasDevices();
            var proj = new XamarinFormsAndroidApplicationProject()
            {
                IsRelease = false,
                AndroidUseSharedRuntime   = useSharedRuntime,
                EmbedAssembliesIntoApk    = embedAssemblies,
                AndroidFastDeploymentType = fastDevType
            };
            var abis = new string [] { "armeabi-v7a", "x86" };

            proj.SetProperty(KnownProperties.AndroidSupportedAbis, string.Join(";", abis));
            if (allowDeltaInstall)
            {
                proj.SetProperty(KnownProperties._AndroidAllowDeltaInstall, "true");
            }
            proj.SetDefaultTargetDevice();
            using (var b = CreateApkBuilder(Path.Combine("temp", TestName))) {
                SetTargetFrameworkAndManifest(proj, b);
                Assert.True(b.Install(proj), "Project should have installed.");

                int breakcountHitCount      = 0;
                ManualResetEvent resetEvent = new ManualResetEvent(false);
                var sw = new Stopwatch();
                // setup the debugger
                var session = new SoftDebuggerSession();
                session.Breakpoints = new BreakpointStore {
                    { Path.Combine(Root, b.ProjectDirectory, "MainActivity.cs"), 20 },
                    { Path.Combine(Root, b.ProjectDirectory, "MainPage.xaml.cs"), 14 },
                    { Path.Combine(Root, b.ProjectDirectory, "MainPage.xaml.cs"), 19 },
                    { Path.Combine(Root, b.ProjectDirectory, "App.xaml.cs"), 12 },
                };
                session.TargetHitBreakpoint += (sender, e) => {
                    TestContext.WriteLine($"BREAK {e.Type}, {e.Backtrace.GetFrame (0)}");
                    breakcountHitCount++;
                    session.Continue();
                };
                var rnd  = new Random();
                int port = rnd.Next(10000, 20000);
                TestContext.Out.WriteLine($"{port}");
                var args = new SoftDebuggerConnectArgs("", IPAddress.Loopback, port)
                {
                    MaxConnectionAttempts = 10,
                };
                var startInfo = new SoftDebuggerStartInfo(args)
                {
                    WorkingDirectory = Path.Combine(b.ProjectDirectory, proj.IntermediateOutputPath, "android", "assets"),
                };
                var options = new DebuggerSessionOptions()
                {
                    EvaluationOptions = EvaluationOptions.DefaultOptions,
                };
                options.EvaluationOptions.UseExternalTypeResolver = true;
                ClearAdbLogcat();
                Assert.True(b.RunTarget(proj, "_Run", parameters: new string [] {
                    $"AndroidSdbTargetPort={port}",
                    $"AndroidSdbHostPort={port}",
                    "AndroidAttachDebugger=True",
                }), "Project should have run.");

                Assert.IsTrue(WaitForDebuggerToStart(Path.Combine(Root, b.ProjectDirectory, "logcat.log")), "Activity should have started");
                // we need to give a bit of time for the debug server to start up.
                WaitFor(2000);
                session.LogWriter    += (isStderr, text) => { Console.WriteLine(text); };
                session.OutputWriter += (isStderr, text) => { Console.WriteLine(text); };
                session.DebugWriter  += (level, category, message) => { Console.WriteLine(message); };
                session.Run(startInfo, options);
                WaitFor(TimeSpan.FromSeconds(30), () => session.IsConnected);
                Assert.True(session.IsConnected, "Debugger should have connected but it did not.");
                // we need to wait here for a while to allow the breakpoints to hit
                // but we need to timeout
                TimeSpan timeout  = TimeSpan.FromSeconds(60);
                int      expected = 3;
                while (session.IsConnected && breakcountHitCount < 3 && timeout >= TimeSpan.Zero)
                {
                    Thread.Sleep(10);
                    timeout = timeout.Subtract(TimeSpan.FromMilliseconds(10));
                }
                WaitFor(2000);
                Assert.AreEqual(expected, breakcountHitCount, $"Should have hit {expected} breakpoints. Only hit {breakcountHitCount}");
                breakcountHitCount = 0;
                ClearAdbLogcat();
                ClickButton(proj.PackageName, "myXFButton", "CLICK ME");
                while (session.IsConnected && breakcountHitCount < 1 && timeout >= TimeSpan.Zero)
                {
                    Thread.Sleep(10);
                    timeout = timeout.Subtract(TimeSpan.FromMilliseconds(10));
                }
                expected = 1;
                Assert.AreEqual(expected, breakcountHitCount, $"Should have hit {expected} breakpoints. Only hit {breakcountHitCount}");
                Assert.True(b.Uninstall(proj), "Project should have uninstalled.");
                session.Exit();
            }
        }
Esempio n. 15
0
        public void CustomApplicationRunsWithDebuggerAndBreaks(bool useSharedRuntime, bool embedAssemblies, string fastDevType, bool activityStarts)
        {
            AssertCommercialBuild();
            AssertHasDevices();
            var proj = new XamarinAndroidApplicationProject()
            {
                IsRelease = false,
                AndroidFastDeploymentType = fastDevType,
            };
            var abis = new string [] { "armeabi-v7a", "x86" };

            proj.SetProperty(KnownProperties.AndroidSupportedAbis, string.Join(";", abis));
            proj.SetProperty(KnownProperties.AndroidUseSharedRuntime, useSharedRuntime.ToString());
            proj.SetProperty("EmbedAssembliesIntoApk", embedAssemblies.ToString());
            proj.SetDefaultTargetDevice();
            proj.Sources.Add(new BuildItem.Source("MyApplication.cs")
            {
                TextContent = () => proj.ProcessSourceTemplate(@"using System;
using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Widget;

namespace ${ROOT_NAMESPACE} {
	[Application]
	public class MyApplication : Application {
		public MyApplication (IntPtr handle, JniHandleOwnership jniHandle)
			: base (handle, jniHandle)
		{
		}

		public override void OnCreate ()
		{
			base.OnCreate ();
	    }
	}
}
"),
            });
            using (var b = CreateApkBuilder(Path.Combine("temp", TestName))) {
                SetTargetFrameworkAndManifest(proj, b);
                Assert.True(b.Install(proj), "Project should have installed.");

                int breakcountHitCount      = 0;
                ManualResetEvent resetEvent = new ManualResetEvent(false);
                var sw = new Stopwatch();
                // setup the debugger
                var session = new SoftDebuggerSession();
                session.Breakpoints = new BreakpointStore {
                    { Path.Combine(Root, b.ProjectDirectory, "MainActivity.cs"), 19 },
                    { Path.Combine(Root, b.ProjectDirectory, "MyApplication.cs"), 17 },
                };
                session.TargetHitBreakpoint += (sender, e) => {
                    TestContext.WriteLine($"BREAK {e.Type}, {e.Backtrace.GetFrame (0)}");
                    breakcountHitCount++;
                    session.Continue();
                };
                var rnd  = new Random();
                int port = rnd.Next(10000, 20000);
                TestContext.Out.WriteLine($"{port}");
                var args = new SoftDebuggerConnectArgs("", IPAddress.Loopback, port)
                {
                    MaxConnectionAttempts = 10,
                };
                var startInfo = new SoftDebuggerStartInfo(args)
                {
                    WorkingDirectory = Path.Combine(b.ProjectDirectory, proj.IntermediateOutputPath, "android", "assets"),
                };
                var options = new DebuggerSessionOptions()
                {
                    EvaluationOptions = EvaluationOptions.DefaultOptions,
                };
                options.EvaluationOptions.UseExternalTypeResolver = true;
                ClearAdbLogcat();
                Assert.True(b.RunTarget(proj, "_Run", parameters: new string [] {
                    $"AndroidSdbTargetPort={port}",
                    $"AndroidSdbHostPort={port}",
                    "AndroidAttachDebugger=True",
                }), "Project should have run.");

                // do we expect the app to start?
                Assert.AreEqual(activityStarts, WaitForDebuggerToStart(Path.Combine(Root, b.ProjectDirectory, "logcat.log")), "Activity should have started");
                if (!activityStarts)
                {
                    return;
                }
                // we need to give a bit of time for the debug server to start up.
                WaitFor(2000);
                session.LogWriter    += (isStderr, text) => { Console.WriteLine(text); };
                session.OutputWriter += (isStderr, text) => { Console.WriteLine(text); };
                session.DebugWriter  += (level, category, message) => { Console.WriteLine(message); };
                session.Run(startInfo, options);
                var expectedTime = TimeSpan.FromSeconds(1);
                var actualTime   = ProfileFor(() => session.IsConnected);
                TestContext.Out.WriteLine($"Debugger connected in {actualTime}");
                Assert.LessOrEqual(actualTime, expectedTime, $"Debugger should have connected within {expectedTime} but it took {actualTime}.");
                // we need to wait here for a while to allow the breakpoints to hit
                // but we need to timeout
                TimeSpan timeout = TimeSpan.FromSeconds(60);
                while (session.IsConnected && breakcountHitCount < 2 && timeout >= TimeSpan.Zero)
                {
                    Thread.Sleep(10);
                    timeout = timeout.Subtract(TimeSpan.FromMilliseconds(10));
                }
                WaitFor(2000);
                int expected = 2;
                Assert.AreEqual(expected, breakcountHitCount, $"Should have hit {expected} breakpoints. Only hit {breakcountHitCount}");
                Assert.True(b.Uninstall(proj), "Project should have uninstalled.");
                session.Exit();
            }
        }
Esempio n. 16
0
        protected virtual void Start(string test)
        {
            TestName = test;
            Session  = CreateSession(test, EngineId);

            var dsi  = CreateStartInfo(test, EngineId);
            var soft = dsi as SoftDebuggerStartInfo;

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

                soft.UserAssemblyNames = new List <AssemblyName> {
                    assemblyName
                };
            }
            var ops = new DebuggerSessionOptions {
                ProjectAssembliesOnly = true,
                EvaluationOptions     = EvaluationOptions.DefaultOptions
            };

            ops.EvaluationOptions.AllowTargetInvoke = AllowTargetInvokes;
            ops.EvaluationOptions.EvaluationTimeout = 100000;


            var sourcePath = Path.Combine(TargetProjectSourceDir, test + ".cs");

            SourceFile = ReadFile(sourcePath);
            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());
                HandleAnyException(ex);
                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);
            }
        }
Esempio n. 17
0
 bool GetExternalCodeValue(DebuggerSessionOptions options)
 {
     return(options.EvaluationOptions.StackFrameFormat.ExternalCode ?? options.ProjectAssembliesOnly);
 }
Esempio n. 18
0
        public void ApplicationRunsWithDebuggerAndBreaks(bool useSharedRuntime, bool embedAssemblies, string fastDevType)
        {
            if (!CommercialBuildAvailable)
            {
                Assert.Ignore("Test does not run on the Open Source Builds.");
                return;
            }
            if (!HasDevices)
            {
                Assert.Ignore("Test needs a device attached.");
                return;
            }
            var proj = new XamarinFormsAndroidApplicationProject()
            {
                IsRelease = false,
                AndroidFastDeploymentType = fastDevType
            };
            var abis = new string [] { "armeabi-v7a", "x86" };

            proj.SetProperty(KnownProperties.AndroidSupportedAbis, string.Join(";", abis));
            proj.SetProperty(KnownProperties.AndroidUseSharedRuntime, useSharedRuntime.ToString());
            proj.SetProperty("EmbedAssembliesIntoApk", embedAssemblies.ToString());
            proj.SetDefaultTargetDevice();
            using (var b = CreateApkBuilder(Path.Combine("temp", TestName))) {
                string apiLevel;
                proj.TargetFrameworkVersion = b.LatestTargetFrameworkVersion(out apiLevel);
                proj.AndroidManifest        = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<manifest xmlns:android=""http://schemas.android.com/apk/res/android"" android:versionCode=""1"" android:versionName=""1.0"" package=""UnnamedProject.UnnamedProject"">
	<uses-sdk android:minSdkVersion=""24"" android:targetSdkVersion=""{apiLevel}"" />
	<application android:label=""${{PROJECT_NAME}}"">
	</application >
</manifest>";
                b.Save(proj, saveProject: true);
                proj.NuGetRestore(Path.Combine(Root, b.ProjectDirectory), b.PackagesDirectory);
                Assert.True(b.Build(proj), "Project should have built.");
                Assert.True(b.Install(proj), "Project should have installed.");

                int breakcountHitCount      = 0;
                ManualResetEvent resetEvent = new ManualResetEvent(false);
                var sw = new Stopwatch();
                // setup the debugger
                var session = new SoftDebuggerSession();
                session.Breakpoints = new BreakpointStore {
                    { Path.Combine(Root, b.ProjectDirectory, "MainActivity.cs"), 19 },
                    { Path.Combine(Root, b.ProjectDirectory, "MainPage.xaml.cs"), 14 },
                    { Path.Combine(Root, b.ProjectDirectory, "MainPage.xaml.cs"), 19 },
                    { Path.Combine(Root, b.ProjectDirectory, "App.xaml.cs"), 12 },
                };
                session.TargetHitBreakpoint += (sender, e) => {
                    Console.WriteLine($"BREAK {e.Type}");
                    breakcountHitCount++;
                    session.Continue();
                };
                var rnd  = new Random();
                int port = rnd.Next(10000, 20000);
                TestContext.Out.WriteLine($"{port}");
                var args = new SoftDebuggerConnectArgs("", IPAddress.Loopback, port)
                {
                    MaxConnectionAttempts = 10,
                };
                var startInfo = new SoftDebuggerStartInfo(args)
                {
                    WorkingDirectory = Path.Combine(b.ProjectDirectory, proj.IntermediateOutputPath, "android", "assets"),
                };
                var options = new DebuggerSessionOptions()
                {
                    EvaluationOptions = EvaluationOptions.DefaultOptions,
                };
                options.EvaluationOptions.UseExternalTypeResolver = true;
                ClearAdbLogcat();
                Assert.True(b.RunTarget(proj, "_Run", parameters: new string [] {
                    $"AndroidSdbTargetPort={port}",
                    $"AndroidSdbHostPort={port}",
                    "AndroidAttachDebugger=True",
                }), "Project should have run.");

                Assert.IsTrue(WaitForDebuggerToStart(output: out string logcat), "Activity should have started");
                // we need to give a bit of time for the debug server to start up.
                WaitFor(2000);
                session.LogWriter    += (isStderr, text) => { Console.WriteLine(text); };
                session.OutputWriter += (isStderr, text) => { Console.WriteLine(text); };
                session.DebugWriter  += (level, category, message) => { Console.WriteLine(message); };
                session.Run(startInfo, options);
                WaitFor(TimeSpan.FromSeconds(30), () => session.IsConnected);
                Assert.True(session.IsConnected, "Debugger should have connected but it did not.");
                // we need to wait here for a while to allow the breakpoints to hit
                // but we need to timeout
                TimeSpan timeout = TimeSpan.FromSeconds(60);
                while (session.IsConnected && breakcountHitCount < 3)
                {
                    Thread.Sleep(10);
                    timeout = timeout.Subtract(TimeSpan.FromMilliseconds(10));
                }
                WaitFor(2000);
                ClearAdbLogcat();
                ClickButton(proj.PackageName, "myXFButton", "CLICK ME");
                while (session.IsConnected && breakcountHitCount < 4)
                {
                    Thread.Sleep(10);
                    timeout = timeout.Subtract(TimeSpan.FromMilliseconds(10));
                }
                int expected = 4;
                Assert.AreEqual(expected, breakcountHitCount, $"Should have hit {expected} breakpoints. Only hit {breakcountHitCount}");
                Assert.True(b.Uninstall(proj), "Project should have uninstalled.");
                session.Exit();
            }
        }
Esempio n. 19
0
        public void Run(MonoDebuggerStartInfo startInfo, DebuggerSessionOptions sessionOptions)
        {
            try {
                if (startInfo == null)
                {
                    throw new ArgumentNullException("startInfo");
                }

                Console.WriteLine("MDB version: " + mdbAdaptor.MdbVersion);

                this.SessionOptions  = sessionOptions;
                mdbAdaptor.StartInfo = startInfo;

                Report.Initialize();

                DebuggerConfiguration config = new DebuggerConfiguration();
                config.LoadConfiguration();
                mdbAdaptor.Configuration = config;
                mdbAdaptor.InitializeConfiguration();

                debugger = new MD.Debugger(config);

                debugger.ModuleLoadedEvent   += OnModuleLoadedEvent;
                debugger.ModuleUnLoadedEvent += OnModuleUnLoadedEvent;

                debugger.ProcessReachedMainEvent += delegate(MD.Debugger deb, MD.Process proc) {
                    OnInitialized(deb, proc);
                };

                if (startInfo.IsXsp)
                {
                    mdbAdaptor.SetupXsp();
                    config.FollowFork = false;
                }
                config.OpaqueFileNames = false;

                DebuggerOptions options = DebuggerOptions.ParseCommandLine(new string[] { startInfo.Command });
                options.WorkingDirectory     = startInfo.WorkingDirectory;
                Environment.CurrentDirectory = startInfo.WorkingDirectory;
                options.StopInMain           = false;

                if (!string.IsNullOrEmpty(startInfo.Arguments))
                {
                    options.InferiorArgs = ToArgsArray(startInfo.Arguments);
                }

                if (startInfo.EnvironmentVariables != null)
                {
                    foreach (KeyValuePair <string, string> env in startInfo.EnvironmentVariables)
                    {
                        options.SetEnvironment(env.Key, env.Value);
                    }
                }
                session            = new MD.DebuggerSession(config, options, "main", null);
                mdbAdaptor.Session = session;
                mdbAdaptor.InitializeSession();

                ST.ThreadPool.QueueUserWorkItem(delegate {
                    // Run in a thread to avoid a deadlock, since NotifyStarted calls back to the client.
                    NotifyStarted();
                    debugger.Run(session);
                });
            } catch (Exception e) {
                Console.WriteLine("error: " + e.ToString());
                throw;
            }
        }
Esempio n. 20
0
        protected DebuggerSession 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.GetTargetRuntime("Mono");
                break;

            default:
                runtime = Runtime.SystemAssemblyService.DefaultRuntime;
                break;
            }

            if (runtime == null)
            {
                return(null);
            }

            var cmd = new DotNetExecutionCommand();

            cmd.Command       = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), "MonoDevelop.Debugger.Tests.TestApp.exe");
            cmd.Arguments     = test;
            cmd.TargetRuntime = runtime;

            DebuggerStartInfo si      = engine.CreateDebuggerStartInfo(cmd);
            DebuggerSession   session = engine.CreateSession();
            var ops = new DebuggerSessionOptions();

            ops.EvaluationOptions = EvaluationOptions.DefaultOptions;
            ops.EvaluationOptions.EvaluationTimeout = 100000;

            FilePath path = Util.TestsRootDir;

            path = path.ParentDirectory.Combine("src", "addins", "MonoDevelop.Debugger", "MonoDevelop.Debugger.Tests.TestApp", "Main.cs").FullPath;
            TextFile file = TextFile.ReadFile(path);
            int      i    = file.Text.IndexOf("void " + test, StringComparison.Ordinal);

            if (i == -1)
            {
                throw new Exception("Test not found: " + test);
            }
            i = file.Text.IndexOf("/*break*/", i, StringComparison.Ordinal);
            if (i == -1)
            {
                throw new Exception("Break marker not found: " + test);
            }
            int line, col;

            file.GetLineColumnFromPosition(i, out line, out col);
            Breakpoint bp = session.Breakpoints.Add(path, line);

            bp.Enabled = true;

            var done = new ManualResetEvent(false);

            session.OutputWriter = (isStderr, text) => Console.WriteLine("PROC:" + text);

            session.TargetHitBreakpoint += delegate {
                done.Set();
            };

            session.Run(si, ops);
            if (!done.WaitOne(3000))
            {
                throw new Exception("Timeout while waiting for initial breakpoint");
            }

            return(session);
        }
Esempio n. 21
0
        public void ApplicationRunsWithDebuggerAndBreaks(bool embedAssemblies, string fastDevType, bool allowDeltaInstall, string username)
        {
            AssertCommercialBuild();
            AssertHasDevices();

            var           path       = Path.Combine("temp", TestName);
            int           userId     = GetUserId(username);
            List <string> parameters = new List <string> ();

            if (userId >= 0)
            {
                parameters.Add($"AndroidDeviceUserId={userId}");
            }
            if (SwitchUser(username))
            {
                WaitFor(5);
                ClickButton("", "android:id/button1", "Yes continue");
            }

            var lib = new XamarinAndroidLibraryProject {
                ProjectName = "Library1",
                Sources     =
                {
                    new BuildItem.Source("Foo.cs")
                    {
                        TextContent = () =>
                                      @"public class Foo
{
	public Foo ()
	{
	}
}"
                    },
                },
            };

            var app = new XamarinFormsAndroidApplicationProject {
                ProjectName               = "App",
                IsRelease                 = false,
                EmbedAssembliesIntoApk    = embedAssemblies,
                AndroidFastDeploymentType = fastDevType
            };

            app.MainPage = app.MainPage.Replace("InitializeComponent ();", "InitializeComponent (); new Foo ();");
            app.AddReference(lib);
            app.SetAndroidSupportedAbis("armeabi-v7a", "x86");
            app.SetProperty(KnownProperties._AndroidAllowDeltaInstall, allowDeltaInstall.ToString());
            app.SetDefaultTargetDevice();
            using (var libBuilder = CreateDllBuilder(Path.Combine(path, lib.ProjectName)))
                using (var appBuilder = CreateApkBuilder(Path.Combine(path, app.ProjectName))) {
                    Assert.True(libBuilder.Build(lib), "Library should have built.");

                    SetTargetFrameworkAndManifest(app, appBuilder);
                    Assert.True(appBuilder.Install(app, parameters: parameters.ToArray()), "App should have installed.");

                    if (!embedAssemblies)
                    {
                        // Check that we deployed .pdb files
                        StringAssertEx.ContainsRegex($@"NotifySync CopyFile.+{app.ProjectName}\.pdb", appBuilder.LastBuildOutput,
                                                     $"{app.ProjectName}.pdb should be deployed!");
                        StringAssertEx.ContainsRegex($@"NotifySync CopyFile.+{lib.ProjectName}\.pdb", appBuilder.LastBuildOutput,
                                                     $"{lib.ProjectName}.pdb should be deployed!");
                    }

                    int breakcountHitCount      = 0;
                    ManualResetEvent resetEvent = new ManualResetEvent(false);
                    var sw = new Stopwatch();
                    // setup the debugger
                    var session = new SoftDebuggerSession();
                    session.Breakpoints = new BreakpointStore {
                        { Path.Combine(Root, appBuilder.ProjectDirectory, "MainActivity.cs"), 20 },
                        { Path.Combine(Root, appBuilder.ProjectDirectory, "MainPage.xaml.cs"), 14 },
                        { Path.Combine(Root, appBuilder.ProjectDirectory, "MainPage.xaml.cs"), 19 },
                        { Path.Combine(Root, appBuilder.ProjectDirectory, "App.xaml.cs"), 12 },
                        { Path.Combine(Root, libBuilder.ProjectDirectory, "Foo.cs"), 4 },
                    };
                    session.TargetHitBreakpoint += (sender, e) => {
                        TestContext.WriteLine($"BREAK {e.Type}, {e.Backtrace.GetFrame (0)}");
                        breakcountHitCount++;
                        session.Continue();
                    };
                    var rnd  = new Random();
                    int port = rnd.Next(10000, 20000);
                    TestContext.Out.WriteLine($"{port}");
                    var args = new SoftDebuggerConnectArgs("", IPAddress.Loopback, port)
                    {
                        MaxConnectionAttempts = 10,
                    };
                    var startInfo = new SoftDebuggerStartInfo(args)
                    {
                        WorkingDirectory = Path.Combine(appBuilder.ProjectDirectory, app.IntermediateOutputPath, "android", "assets"),
                    };
                    var options = new DebuggerSessionOptions()
                    {
                        EvaluationOptions = EvaluationOptions.DefaultOptions,
                    };
                    options.EvaluationOptions.UseExternalTypeResolver = true;
                    ClearAdbLogcat();
                    appBuilder.BuildLogFile = "run.log";

                    parameters.Add($"AndroidSdbTargetPort={port}");
                    parameters.Add($"AndroidSdbHostPort={port}");
                    parameters.Add("AndroidAttachDebugger=True");

                    Assert.True(appBuilder.RunTarget(app, "_Run", doNotCleanupOnUpdate: true,
                                                     parameters: parameters.ToArray()), "Project should have run.");

                    Assert.IsTrue(WaitForDebuggerToStart(Path.Combine(Root, appBuilder.ProjectDirectory, "logcat.log")), "Activity should have started");
                    // we need to give a bit of time for the debug server to start up.
                    WaitFor(2000);
                    session.LogWriter    += (isStderr, text) => { Console.WriteLine(text); };
                    session.OutputWriter += (isStderr, text) => { Console.WriteLine(text); };
                    session.DebugWriter  += (level, category, message) => { Console.WriteLine(message); };
                    session.Run(startInfo, options);
                    WaitFor(TimeSpan.FromSeconds(30), () => session.IsConnected);
                    Assert.True(session.IsConnected, "Debugger should have connected but it did not.");
                    // we need to wait here for a while to allow the breakpoints to hit
                    // but we need to timeout
                    TimeSpan timeout  = TimeSpan.FromSeconds(60);
                    int      expected = 4;
                    while (session.IsConnected && breakcountHitCount < 3 && timeout >= TimeSpan.Zero)
                    {
                        Thread.Sleep(10);
                        timeout = timeout.Subtract(TimeSpan.FromMilliseconds(10));
                    }
                    WaitFor(2000);
                    Assert.AreEqual(expected, breakcountHitCount, $"Should have hit {expected} breakpoints. Only hit {breakcountHitCount}");
                    breakcountHitCount = 0;
                    ClearAdbLogcat();
                    ClickButton(app.PackageName, "myXFButton", "CLICK ME");
                    while (session.IsConnected && breakcountHitCount < 1 && timeout >= TimeSpan.Zero)
                    {
                        Thread.Sleep(10);
                        timeout = timeout.Subtract(TimeSpan.FromMilliseconds(10));
                    }
                    expected = 1;
                    Assert.AreEqual(expected, breakcountHitCount, $"Should have hit {expected} breakpoints. Only hit {breakcountHitCount}");
                    appBuilder.BuildLogFile = "uninstall.log";
                    Assert.True(appBuilder.Uninstall(app), "Project should have uninstalled.");
                    session.Exit();
                }
        }
        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);
            };
        }
Esempio n. 23
0
		Widget CreateContent (DebuggerSessionOptions options, StackFrame frame, bool disassemblySupported)
		{
			var fileName = GetFilename (frame.SourceLocation?.FileName);
			this.options = options;
			this.frame = frame;

			var vbox = new VBox {
				Spacing = 10,
				Margin = 30
			};

			if (!string.IsNullOrEmpty (fileName)) {
				DocumentTitle = GettextCatalog.GetString ("Source Not Found");
				var headerLabel = new Label {
					Markup = GettextCatalog.GetString ("{0} file not found", $"<b>{fileName}</b>")
				};
				headerLabel.Font = headerLabel.Font.WithScaledSize (2);
				vbox.PackStart (headerLabel);

				if (frame.SourceLocation?.SourceLink != null && options.AutomaticSourceLinkDownload == AutomaticSourceDownload.Ask) {
					var sourceLinkVbox = new VBox {
						MarginBottom = 20,
						MarginTop = 10,
						Spacing = 10,
					};

					sourceLinkLabel = new Label {
						Markup = GettextCatalog.GetString ("External source code is available. Would you like to download {0} and view it?", $"<a href=\"clicked\">{fileName}</a>"),
						Name = "SourceLinkLabel"
					};
					sourceLinkLabel.LinkClicked += OnDownloadSourceClicked;

					sourceLinkVbox.PackStart (sourceLinkLabel);

					var sourceLinkHbox = new HBox {
						Spacing = 10
					};

					sourceLinkButton = new Button (GettextCatalog.GetString ("Download {0}", fileName));
					sourceLinkButton.Clicked += OnDownloadSourceClicked;
					sourceLinkHbox.PackStart (sourceLinkButton);

					sourceLinkCheckbox = new CheckBox (GettextCatalog.GetString ("Always download source code automatically"));
					sourceLinkHbox.PackStart (sourceLinkCheckbox);

					sourceLinkVbox.PackStart (sourceLinkHbox);

					vbox.PackStart (sourceLinkVbox);

					var separator = new HSeparator ();
					vbox.PackStart (separator);
				}

				var buttonBox = new HBox ();

				browseButton = new Button (GettextCatalog.GetString ("Browse…"));
				browseButton.Clicked += OnBrowseClicked;
				buttonBox.PackStart (browseButton);

				if (disassemblySupported) {
					disassemblyButton = new Button (GettextCatalog.GetString ("Go to Disassembly"));
					disassemblyButton.Clicked += OnGoToDisassemblyClicked;
					buttonBox.PackStart (disassemblyButton);
				}

				var hbox = new HBox {
					MarginTop = 20,
					Spacing = 10
				};

				hbox.PackStart (buttonBox);

				if (IdeApp.ProjectOperations.CurrentSelectedSolution != null) {
					manageOptionsLabel = new Label {
						Markup = GettextCatalog.GetString ("Manage the locations used to find source files in the {0}.", "<a href=\"clicked\">" + GettextCatalog.GetString ("Solution Options") + "</a>"),
						MarginLeft = 10
					};
					manageOptionsLabel.LinkClicked += OnManageSolutionOptionsClicked;
					hbox.PackStart (manageOptionsLabel);
				}

				vbox.PackStart (hbox);
			} else {
				DocumentTitle = GettextCatalog.GetString ("Source Not Available");
				var headerLabel = new Label (GettextCatalog.GetString ("Source Not Available"));
				vbox.PackStart (headerLabel);
				var label = new Label (GettextCatalog.GetString ("Source information is missing from the debug information for this module"));
				headerLabel.Font = label.Font.WithScaledSize (2);
				vbox.PackStart (label);

				if (disassemblySupported) {
					disassemblyLabel = new Label {
						Markup = GettextCatalog.GetString ("View disassembly in the {0}", "<a href=\"clicked\">" + GettextCatalog.GetString ("Disassembly Tab") + "</a>")
					};
					disassemblyLabel.LinkClicked += OnGoToDisassemblyClicked;
					vbox.PackStart (disassemblyLabel);
				}
			}

			return vbox;
		}
Esempio n. 24
0
        public void DotNetDebug()
        {
            AssertCommercialBuild();
            AssertHasDevices();

            XASdkProject proj;

            proj = new XASdkProject {
                //TODO: targetSdkVersion="30" causes a crash on startup in .NET 5
                MinSdkVersion    = null,
                TargetSdkVersion = null,
            };
            proj.SetRuntimeIdentifier(DeviceAbi);

            var relativeProjDir = Path.Combine("temp", TestName);
            var fullProjDir     = Path.Combine(Root, relativeProjDir);

            TestOutputDirectories [TestContext.CurrentContext.Test.ID] = fullProjDir;
            var files = proj.Save();

            proj.Populate(relativeProjDir, files);
            proj.CopyNuGetConfig(relativeProjDir);
            var dotnet = new DotNetCLI(proj, Path.Combine(fullProjDir, proj.ProjectFilePath));

            Assert.IsTrue(dotnet.Build("Install"), "`dotnet build` should succeed");

            bool             breakpointHit = false;
            ManualResetEvent resetEvent    = new ManualResetEvent(false);
            var sw = new Stopwatch();
            // setup the debugger
            var session = new SoftDebuggerSession();

            session.Breakpoints = new BreakpointStore {
                { Path.Combine(Root, dotnet.ProjectDirectory, "MainActivity.cs"), 19 },
            };
            session.TargetHitBreakpoint += (sender, e) => {
                Console.WriteLine($"BREAK {e.Type}");
                breakpointHit = true;
                session.Continue();
            };
            var rnd  = new Random();
            int port = rnd.Next(10000, 20000);

            TestContext.Out.WriteLine($"{port}");
            var args = new SoftDebuggerConnectArgs("", IPAddress.Loopback, port)
            {
                MaxConnectionAttempts = 10,
            };
            var startInfo = new SoftDebuggerStartInfo(args)
            {
                WorkingDirectory = Path.Combine(dotnet.ProjectDirectory, proj.IntermediateOutputPath, "android", "assets"),
            };
            var options = new DebuggerSessionOptions()
            {
                EvaluationOptions = EvaluationOptions.DefaultOptions,
            };

            options.EvaluationOptions.UseExternalTypeResolver = true;
            ClearAdbLogcat();
            Assert.True(dotnet.Build("Run", new string [] {
                $"AndroidSdbTargetPort={port}",
                $"AndroidSdbHostPort={port}",
                "AndroidAttachDebugger=True",
            }), "Project should have run.");

            Assert.IsTrue(WaitForDebuggerToStart(Path.Combine(Root, dotnet.ProjectDirectory, "logcat.log")), "Activity should have started");
            // we need to give a bit of time for the debug server to start up.
            WaitFor(2000);
            session.LogWriter    += (isStderr, text) => { Console.WriteLine(text); };
            session.OutputWriter += (isStderr, text) => { Console.WriteLine(text); };
            session.DebugWriter  += (level, category, message) => { Console.WriteLine(message); };
            session.Run(startInfo, options);
            WaitFor(TimeSpan.FromSeconds(30), () => session.IsConnected);
            Assert.True(session.IsConnected, "Debugger should have connected but it did not.");
            // we need to wait here for a while to allow the breakpoints to hit
            // but we need to timeout
            TimeSpan timeout = TimeSpan.FromSeconds(60);

            while (session.IsConnected && !breakpointHit && timeout >= TimeSpan.Zero)
            {
                Thread.Sleep(10);
                timeout = timeout.Subtract(TimeSpan.FromMilliseconds(10));
            }
            WaitFor(2000);
            Assert.IsTrue(breakpointHit, "Should have a breakpoint");
        }
Esempio n. 25
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 + " " + (IntPtr.Size == 8 ? "64bit" : "32bit"));

            // 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);
            }
        }