Пример #1
0
        private void StartAttaching(IPAddress address, int port)
        {
            SoftDebuggerConnectArgs connectArgs = new SoftDebuggerConnectArgs(string.Empty, address, port);
            SoftDebuggerStartInfo   startInfo   = new SoftDebuggerStartInfo(connectArgs);

            StartConnecting(startInfo);
        }
Пример #2
0
        public DebuggerStartInfo CreateDebuggerStartInfo(ExecutionCommand command)
        {
            var cmd = (AspNetExecutionCommand)command;

            var runtime   = (MonoTargetRuntime)cmd.TargetRuntime;
            var startInfo = new SoftDebuggerStartInfo(runtime.Prefix, runtime.EnvironmentVariables)
            {
                WorkingDirectory = cmd.BaseDirectory,
                Arguments        = cmd.XspParameters.GetXspParameters().Trim(),
            };

            FilePath prefix = runtime.Prefix;

            if (MonoDevelop.Core.PropertyService.IsWindows)
            {
                startInfo.Command = (cmd.ClrVersion == ClrVersion.Net_1_1)
                                        ? prefix.Combine("lib", "mono", "1.0", "winhack", "xsp.exe")
                                        : prefix.Combine("lib", "mono", "2.0", "winhack", "xsp2.exe");
            }
            else
            {
                startInfo.Command = (cmd.ClrVersion == ClrVersion.Net_1_1)
                                        ? prefix.Combine("lib", "mono", "1.0", "xsp.exe")
                                        : prefix.Combine("lib", "mono", "2.0", "xsp2.exe");
            }

            string error;

            startInfo.UserAssemblyNames = SoftDebuggerEngine.GetAssemblyNames(cmd.UserAssemblyPaths, out error);
            startInfo.LogMessage        = error;

            return(startInfo);
        }
Пример #3
0
        public static void SetUserAssemblyNames(SoftDebuggerStartInfo dsi, IList <string> files)
        {
            if (files == null || files.Count == 0)
            {
                return;
            }

            var names = new List <AssemblyName> ();

            foreach (var file in files)
            {
                if (!File.Exists(file))
                {
                    dsi.LogMessage = GettextCatalog.GetString("User assembly '{0}' is missing. " +
                                                              "Debugger will now debug all code, not just user code.", file);
                    return;
                }
                try {
                    var asm = Mono.Cecil.AssemblyDefinition.ReadAssembly(file);
                    if (string.IsNullOrEmpty(asm.Name.Name))
                    {
                        throw new InvalidOperationException("Assembly has no assembly name");
                    }
                    names.Add(new AssemblyName(asm.Name.FullName));
                } catch (Exception ex) {
                    dsi.LogMessage = GettextCatalog.GetString("Could not get assembly name for user assembly '{0}'. " +
                                                              "Debugger will now debug all code, not just user code.", file);
                    MDLS.LogError("Error getting assembly name for user assembly '" + file + "'", ex);
                    return;
                }
            }
            dsi.UserAssemblyNames = names;
        }
        public override DebuggerStartInfo CreateDebuggerStartInfo(ExecutionCommand c)
        {
            var cmd     = (DotNetExecutionCommand)c;
            var runtime = (MonoTargetRuntime)cmd.TargetRuntime;
            var dsi     = new SoftDebuggerStartInfo(runtime.Prefix, runtime.EnvironmentVariables)
            {
                Command          = cmd.Command,
                Arguments        = cmd.Arguments,
                WorkingDirectory = cmd.WorkingDirectory,
            };

            SetUserAssemblyNames(dsi, cmd.UserAssemblyPaths);

            foreach (KeyValuePair <string, string> var in cmd.EnvironmentVariables)
            {
                dsi.EnvironmentVariables [var.Key] = var.Value;
            }

            var varsCopy  = new Dictionary <string, string> (cmd.EnvironmentVariables);
            var startArgs = (SoftDebuggerLaunchArgs)dsi.StartArgs;

            startArgs.ExternalConsoleLauncher = delegate(System.Diagnostics.ProcessStartInfo info) {
                IProcessAsyncOperation oper;
                oper = Runtime.ProcessService.StartConsoleProcess(info.FileName, info.Arguments, info.WorkingDirectory,
                                                                  varsCopy, ExternalConsoleFactory.Instance.CreateConsole(dsi.CloseExternalConsoleOnExit), null);
                return(new ProcessAdapter(oper, Path.GetFileName(info.FileName)));
            };

            return(dsi);
        }
Пример #5
0
            void StartProcess(SoftDebuggerStartInfo info)
            {
                if (string.IsNullOrEmpty(info.Command))
                {
                    return;
                }

                if (info.UseExternalConsole)
                {
                    usingExternalConsole = true;
                    var console = ExternalConsoleFactory.Instance.CreateConsole(info.CloseExternalConsoleOnExit);
                    process = Runtime.ProcessService.StartConsoleProcess(
                        info.Command, info.Arguments, info.WorkingDirectory, console, info.EnvironmentVariables);
                }
                else
                {
                    var psi = new ProcessStartInfo(info.Command, info.Arguments)
                    {
                        WorkingDirectory = info.WorkingDirectory,
                        UseShellExecute  = false
                    };
                    foreach (KeyValuePair <string, string> kvp in info.EnvironmentVariables)
                    {
                        psi.EnvironmentVariables [kvp.Key] = kvp.Value;
                    }

                    process = Runtime.ProcessService.StartProcess(psi, ProcessOutput, ProcessError, null).ProcessAsyncOperation;
                }
            }
Пример #6
0
        private void StartListening(IPAddress address, int port)
        {
            SoftDebuggerListenArgs listenArgs = new SoftDebuggerListenArgs(string.Empty, address, port);
            SoftDebuggerStartInfo  startInfo  = new SoftDebuggerStartInfo(listenArgs);

            StartListening(startInfo);
        }
Пример #7
0
        public static void Run(FileInfo file)
        {
            lock (_lock)
            {
                EnsureCreated();

                CurrentExecutable = file;
                CurrentAddress    = null;
                CurrentPort       = -1;

                _debuggeeKilled = false;
                _kind           = SessionKind.Launched;

                var info = new SoftDebuggerStartInfo(Configuration.Current.RuntimePrefix,
                                                     new Dictionary <string, string>(EnvironmentVariables))
                {
                    Command          = file.FullName,
                    Arguments        = Arguments,
                    WorkingDirectory = WorkingDirectory,
                    StartArgs        =
                    {
                        MaxConnectionAttempts         = Configuration.Current.MaxConnectionAttempts,
                        TimeBetweenConnectionAttempts = Configuration.Current.ConnectionAttemptInterval
                    }
                };

                // We need to ignore `SIGINT` while we start the inferior
                // process so that it inherits that signal disposition.
                CommandLine.UnsetControlCHandler();

                _session.Run(info, Options);

                CommandLine.InferiorExecuting = true;
            }
        }
Пример #8
0
            public new SoftDebuggerStartInfo Run()
            {
                var response = (Gtk.ResponseType)MonoDevelop.Ide.MessageService.RunCustomDialog(this);

                if (response != listenResponse && response != connectResponse)
                {
                    return(null);
                }

                properties.Set("Command", command);
                properties.Set("Arguments", args);
                properties.Set("IpAddress", ip.ToString());
                properties.Set("Port", PortToString(port));
                properties.Set("ConsolePort", PortToString(consolePort));

                var  name      = string.IsNullOrEmpty(command)? "" : command;
                bool listen    = response == listenResponse;
                var  agentArgs = string.Format("transport=dt_socket,address={0}:{1}{2}", ip, port, listen?"":",server=y");

                var customArgsTags = new string[, ] {
                    { "AgentArgs", agentArgs },
                    { "IP", ip.ToString() },
                    { "Port", PortToString(port) },
                    { "Console", PortToString(consolePort) },
                };

                SoftDebuggerRemoteArgs startArgs;

                if (listen)
                {
                    startArgs = (SoftDebuggerRemoteArgs) new SoftDebuggerListenArgs(name, ip, port.Value, consolePort ?? -1);
                }
                else
                {
                    startArgs = new SoftDebuggerConnectArgs(name, ip, port.Value, consolePort ?? -1)
                    {
                        //infinite connection retries (user can cancel), 800ms between them
                        TimeBetweenConnectionAttempts = 800,
                        MaxConnectionAttempts         = -1,
                    };
                }

                var dsi = new SoftDebuggerStartInfo(startArgs)
                {
                    Command   = StringParserService.Parse(command),
                    Arguments = StringParserService.Parse(args, customArgsTags),
                };

                //FIXME: GUI for env vars
                //dsi.EnvironmentVariables [kvp.Key] = kvp.Value;

                return(dsi);
            }
        public override DebuggerStartInfo CreateDebuggerStartInfo(ExecutionCommand command)
        {
            var cmd     = (AspNetExecutionCommand)command;
            var evars   = new Dictionary <string, string>(cmd.EnvironmentVariables);
            var runtime = (MonoTargetRuntime)cmd.TargetRuntime;

            foreach (var v in runtime.EnvironmentVariables)
            {
                if (!evars.ContainsKey(v.Key))
                {
                    evars.Add(v.Key, v.Value);
                }
            }

            //HACK: work around Mono trying to create registry in non-writable location
            if (cmd.TargetRuntime is MonoTargetRuntime && !Platform.IsWindows)
            {
                evars ["MONO_REGISTRY_PATH"] = UserProfile.Current.TempDir.Combine("aspnet-registry");
            }

            var startInfo = new SoftDebuggerStartInfo(runtime.Prefix, evars)
            {
                WorkingDirectory = cmd.BaseDirectory,
                Arguments        = cmd.XspParameters.GetXspParameters().Trim(),
            };

            var xspName = AspNetExecutionHandler.GetXspName(cmd);

            FilePath fxDir   = GetFxDir(runtime, cmd.ClrVersion);
            FilePath xspPath = fxDir.Combine(xspName).ChangeExtension(".exe");

            //no idea why xsp is sometimes relocated to a "winhack" dir on Windows
            if (MonoDevelop.Core.Platform.IsWindows && !File.Exists(xspPath))
            {
                var winhack = fxDir.Combine("winhack");
                if (Directory.Exists(winhack))
                {
                    xspPath = winhack.Combine(xspName).ChangeExtension(".exe");
                }
            }

            if (!File.Exists(xspPath))
            {
                throw new UserException(GettextCatalog.GetString(
                                            "The \"{0}\" web server cannot be started. Please ensure that it is installed.", xspName), null);
            }

            startInfo.Command = xspPath;
            SoftDebuggerEngine.SetUserAssemblyNames(startInfo, cmd.UserAssemblyPaths);

            return(startInfo);
        }
Пример #10
0
        public SoftDebuggerStartInfo DebuggerInfo(int consolePort = -1)
        {
            try
            {
                IPAddress[] addresslist = Dns.GetHostAddresses(LocalHost);

                var startArgs = new SoftDebuggerConnectArgs("", addresslist[0], (int)LocalTunnelPort, consolePort)
                {
                    //infinite connection retries (user can cancel), 800ms between them
                    TimeBetweenConnectionAttempts = 800,
                    MaxConnectionAttempts         = -1,
                };

                var dsi = new SoftDebuggerStartInfo(startArgs)
                {
                    Command   = "",
                    Arguments = ""
                };

                if (Terminal != null)
                {
                    Terminal.SSH.WriteLine("Configuring debugger {0}:{1}", addresslist[0], (int)LocalTunnelPort);
                }

                return(dsi);
            }
            catch (Exception ex)
            {
                if (Terminal != null)
                {
                    Terminal.SSH.WriteLine("SoftDebuggerStartInfo Error {0}", ex.Message);
                }
                else
                {
                    Gtk.Application.Invoke(delegate {
                        using (var md = new MessageDialog(null, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, String.Format("SoftDebuggerStartInfo Error {0}", ex.Message))) {
                            md.Title = "ProcessScript";
                            md.Run();
                            md.Destroy();
                        }
                    });
                }
                return(null);
            }
        }
Пример #11
0
        protected override string GetConnectingMessage(DebuggerStartInfo dsi)
        {
            SoftDebuggerStartInfo startInfo = dsi as SoftDebuggerStartInfo;

            SoftDebuggerListenArgs listenArgs = startInfo?.StartArgs as SoftDebuggerListenArgs;

            if (listenArgs != null)
            {
                return($"{DubrovnikDebuggerUtils.LISTEN_MESSAGE_PREFIX}{listenArgs.Address}:{listenArgs.DebugPort}...");
            }

            SoftDebuggerConnectArgs connectArgs = startInfo?.StartArgs as SoftDebuggerConnectArgs;

            if (connectArgs != null)
            {
                return($"{DubrovnikDebuggerUtils.ATTACH_MESSAGE_PREFIX}{connectArgs.Address}:{connectArgs.DebugPort}...");
            }

            return(base.GetConnectingMessage(dsi));
        }
Пример #12
0
        public static bool IsPhysicalDevice(this SoftDebuggerStartInfo startInfo)
        {
            var startInfoType = startInfo.GetType();

            // Android
            var device = startInfoType.GetProperty("Device")?.GetValue(startInfo);

            if (device is null)
            {
                // iOS
                var rsi = startInfoType.GetProperty("RunSessionInfo")?.GetValue(startInfo);
                if (rsi is null)
                {
                    throw new NotSupportedException("Cannot get RunSessionInfo");
                }
                device = rsi.GetType().GetProperty("Device")?.GetValue(rsi);
            }
            if (device is null)
            {
                throw new NotSupportedException("Cannot get Device");
            }

            var deviceType     = device.GetType();
            var isEmulatorProp = deviceType.GetProperty("IsEmulator");

            if (isEmulatorProp != null)
            {
                return(!(bool)isEmulatorProp.GetValue(device));
            }

            var isPhysicalDeviceProp = deviceType.GetProperty("IsPhysicalDevice");

            if (isPhysicalDeviceProp != null)
            {
                return((bool)isPhysicalDeviceProp.GetValue(device));
            }

            throw new NotSupportedException("Cannot find either IsEmulator or IsPhysicalDevice");
        }
        public DebuggerStartInfo CreateDebuggerStartInfo(ExecutionCommand command)
        {
            var cmd = (AspNetExecutionCommand)command;

            var runtime   = (MonoTargetRuntime)cmd.TargetRuntime;
            var startInfo = new SoftDebuggerStartInfo(runtime.Prefix, runtime.EnvironmentVariables)
            {
                WorkingDirectory = cmd.BaseDirectory,
                Arguments        = cmd.XspParameters.GetXspParameters().Trim(),
            };

            var xspName = AspNetExecutionHandler.GetXspName(cmd);

            FilePath fxDir   = GetFxDir(runtime, cmd.ClrVersion);
            FilePath xspPath = fxDir.Combine(xspName).ChangeExtension(".exe");

            //no idea why xsp is sometimes relocated to a "winhack" dir on Windows
            if (MonoDevelop.Core.Platform.IsWindows && !File.Exists(xspPath))
            {
                var winhack = fxDir.Combine("winhack");
                if (Directory.Exists(winhack))
                {
                    xspPath = winhack.Combine(xspName).ChangeExtension(".exe");
                }
            }

            if (!File.Exists(xspPath))
            {
                throw new UserException(GettextCatalog.GetString(
                                            "The \"{0}\" web server cannot be started. Please ensure that it is installed.", xspName), null);
            }

            startInfo.Command = xspPath;
            SoftDebuggerEngine.SetUserAssemblyNames(startInfo, cmd.UserAssemblyPaths);

            return(startInfo);
        }
        protected virtual void Start(string test)
        {
            TestName = test;
            Session  = CreateSession(test, EngineId);

            //var dsi = CreateStartInfo (test, EngineId);

            var assemblyName = AssemblyName.GetAssemblyName(TargetExePath);
            var soft         = new SoftDebuggerStartInfo(null, new Dictionary <string, string>())
            {
                Command           = TargetExePath,
                Arguments         = test,
                UserAssemblyNames = new List <AssemblyName> {
                    assemblyName
                },
            };

            ((SoftDebuggerLaunchArgs)soft.StartArgs).MonoExecutableFileName = @"C:\projects\mono\mono\build\builds\monodistribution\bin-x64\mono.exe";

            if (soft != null)
            {
            }
            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(soft, ops);
            Session.ExceptionHandler = (ex) => {
                Console.WriteLine("Session.ExceptionHandler:" + Environment.NewLine + ex.ToString());
                HandleAnyException(ex);
                return(true);
            };
            switch (WaitHandle.WaitAny(new WaitHandle[] { done, targetExited }, 3000))
            {
            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);
            }
        }
Пример #15
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();
            }
        }
Пример #16
0
        public override DebuggerStartInfo CreateDebuggerStartInfo(ExecutionCommand c)
        {
            SoftDebuggerStartInfo dsi = null;

            try{
                //If new host, no host is selected, or ther terminal window is closed
                if (BuildList() || selectedHost == null || selectedHost.Terminal == null)
                {
                    //Load any new templates
                    selectedHost = InvokeSynch <clsHost> (GetDebuggerInfo);                     //Query user for selected host
                }

                if (selectedHost != null)
                {
                    if (selectedHost.Terminal == null)
                    {
                                                #if VTE
                        selectedHost.Terminal = new windowTerminalVTE(selectedHost);
                                                #else
                        selectedHost.Terminal = new windowTerminalGTK(selectedHost);
                                                #endif
                    }
                    else
                    {
                        selectedHost.Terminal.Front();
                    }

                    var done = new ManualResetEvent(false);
                    Task.Run(() => {
                        dsi = selectedHost.ProcessScript(true);
                    }).ContinueWith((t) => {
                        done.Set();
                    });

                    while (true)
                    {
                        Gtk.Application.RunIteration();
                        if (done.WaitOne(0))
                        {
                            break;
                        }
                    }
                }

                if (dsi != null)
                {
                    selectedHost.Terminal.SSH.WriteLine("Starting debugger");
                }

                return(dsi);
            }
            catch (ThreadAbortException)              //User closed terminal (probably)
            {
                return(null);
            }
            catch (Exception ex)
            {
                Gtk.Application.Invoke(delegate
                {
                    using (var md = new MessageDialog(null, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "Terminal error " + ex.Message))
                    {
                        md.Run();
                        md.Destroy();
                    }
                });
                return(null);
            }
        }
Пример #17
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();
                }
        }
Пример #18
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");
        }
Пример #19
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();
            }
        }
Пример #20
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();
            }
        }