Exemplo n.º 1
0
        private void GetFullUrl(LaunchConfiguration config, out Uri uri, out int port)
        {
            int p;

            if (!int.TryParse(config.GetLaunchOption(PythonConstants.WebBrowserPortSetting) ?? "", out p))
            {
                p = TestServerPort;
            }
            port = p;

            var host = config.GetLaunchOption(PythonConstants.WebBrowserUrlSetting);

            if (string.IsNullOrEmpty(host))
            {
                uri = null;
                return;
            }
            try {
                uri = GetFullUrl(host, p);
            } catch (UriFormatException) {
                var output = OutputWindowRedirector.GetGeneral(_serviceProvider);
                output.WriteErrorLine(Strings.ErrorInvalidLaunchUrl.FormatUI(host));
                output.ShowAndActivate();
                uri = null;
            }
        }
Exemplo n.º 2
0
        public override void AddToLaunchConfiguration(LaunchConfiguration configuration)
        {
            base.AddToLaunchConfiguration(configuration);
            var          command            = this.Config.Commands.AddCommand <Command>("CreateWindowsShare");
            const string CreateWindowsShare = "c:/cfn/scripts/CreateWindowsShare.ps1";
            var          script             = this.Config.Files.GetFile(CreateWindowsShare);

            script.Source   = "https://s3.amazonaws.com/gtbb/CreateWindowsShare.ps1";
            command.Command = new FnJoinPowershellCommand(FnJoinDelimiter.Space,
                                                          CreateWindowsShare,
                                                          this.Path,
                                                          this.ShareName,
                                                          "@(",
                                                          new FnJoin(FnJoinDelimiter.Comma,
                                                                     this.Accounts),
                                                          ")");

            SecurityGroup securityGroupSmbAccess = new SecurityGroup("Security Group For SMB Access", configuration.Subnet.Vpc);

            securityGroupSmbAccess.AddIngress(PredefinedCidr.AllVpcs, Protocol.Tcp, Ports.Smb);
            securityGroupSmbAccess.AddIngress(PredefinedCidr.AllVpcs, Protocol.Tcp, Ports.NetBt, Ports.NetBiosNameServices);
            configuration.Template.Resources.Add(securityGroupSmbAccess.LogicalId, securityGroupSmbAccess);
            Instance launchConfigurationAsInstance = configuration as Instance;

            launchConfigurationAsInstance.SecurityGroupIds.Add(new ReferenceProperty(securityGroupSmbAccess));
        }
        /// <inheritdoc/>
        public Task SetLaunchConfigurationAsync(ScalingGroupId groupId, LaunchConfiguration configuration, CancellationToken cancellationToken)
        {
            if (groupId == null)
            {
                throw new ArgumentNullException("groupId");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            UriTemplate template   = new UriTemplate("/groups/{groupId}/launch");
            var         parameters = new Dictionary <string, string> {
                { "groupId", groupId.Value }
            };

            Func <Task <Tuple <IdentityToken, Uri> >, Task <HttpWebRequest> > prepareRequest =
                PrepareRequestAsyncFunc(HttpMethod.PUT, template, parameters, configuration);

            Func <Task <HttpWebRequest>, Task <string> > requestResource =
                GetResponseAsyncFunc(cancellationToken);

            return(AuthenticateServiceAsync(cancellationToken)
                   .Then(prepareRequest)
                   .Then(requestResource));
        }
Exemplo n.º 4
0
        public void LaunchWebBrowserUriTests()
        {
            var testCases = new[] {
                new { Url = "/fob", Port = 1, Expected = "http://localhost:1/fob" },
                new { Url = "http://localhost:9999/fob", Port = 9999, Expected = "http://localhost:9999/fob" },
                new { Url = "http://localhost/fob", Port = 9999, Expected = "http://localhost:9999/fob" },
                new { Url = "fob", Port = 9999, Expected = "http://localhost:9999/fob" },
                new { Url = "/hello/world", Port = 367, Expected = "http://localhost:367/hello/world" },
                new { Url = "/fob", Port = -1, Expected = "http://localhost:{port}/fob" },
            };

            foreach (var testCase in testCases)
            {
                Console.WriteLine("{0} {1} == {2}", testCase.Url, testCase.Port, testCase.Expected);

                Uri url;
                int port;

                var config = new LaunchConfiguration(null, new Dictionary <string, string> {
                    { PythonConstants.WebBrowserUrlSetting, testCase.Url }
                });
                if (testCase.Port >= 0)
                {
                    config.LaunchOptions[PythonConstants.WebBrowserPortSetting] = testCase.Port.ToString();
                }
                PythonWebLauncher.GetFullUrl(null, config, out url, out port);
                Assert.AreEqual(
                    testCase.Expected.Replace("{port}", port.ToString()),
                    url.AbsoluteUri
                    );
            }
        }
Exemplo n.º 5
0
        private static void ProfileStandaloneTarget(SessionNode session, StandaloneTarget runTarget, bool openReport)
        {
            LaunchConfiguration config;

            if (runTarget.PythonInterpreter != null)
            {
                var registry    = session._serviceProvider.GetComponentModel().GetService <IInterpreterRegistryService>();
                var interpreter = registry.FindConfiguration(runTarget.PythonInterpreter.Id);
                if (interpreter == null)
                {
                    return;
                }
                config = new LaunchConfiguration(interpreter);
            }
            else
            {
                config = new LaunchConfiguration(null);
            }

            config.InterpreterPath  = runTarget.InterpreterPath;
            config.ScriptName       = runTarget.Script;
            config.ScriptArguments  = runTarget.Arguments;
            config.WorkingDirectory = runTarget.WorkingDirectory;

            RunProfiler(session, config, openReport);
        }
Exemplo n.º 6
0
        internal static string DoSubstitutions(LaunchConfiguration original, IPythonProject project, string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(str);
            }

            return(SubstitutionPattern.Replace(
                       str,
                       m => {
                switch (m.Groups[1].Value.ToLowerInvariant())
                {
                case "startupfile":
                    return original.ScriptName;

                case "startupmodule":
                    try {
                        return ModulePath.FromFullPath(original.ScriptName, project.ProjectHome).ModuleName;
                    } catch (ArgumentException) {
                    }
                    break;
                }
                return m.Value;
            }
                       ));
        }
Exemplo n.º 7
0
        private void StartInterpreter_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try {
                var view = (EnvironmentView)e.Parameter;

                var config = new LaunchConfiguration(view.Factory.Configuration)
                {
                    PreferWindowedInterpreter = (e.Command == EnvironmentPathsExtension.StartWindowsInterpreter),
                    WorkingDirectory          = view.Factory.Configuration.GetPrefixPath(),
                    SearchPaths = new List <string>()
                };

                var sln = (IVsSolution)_site.GetService(typeof(SVsSolution));
                foreach (var pyProj in sln.EnumerateLoadedPythonProjects())
                {
                    if (pyProj.InterpreterConfigurations.Contains(config.Interpreter))
                    {
                        config.SearchPaths.AddRange(pyProj.GetSearchPaths());
                    }
                }

                config.LaunchOptions[PythonConstants.NeverPauseOnExit] = "true";

                Process.Start(Debugger.DebugLaunchHelper.CreateProcessStartInfo(_site, config))?.Dispose();
            } catch (Exception ex) when(!ex.IsCriticalException())
            {
                TaskDialog.ForException(_site, ex, Strings.ErrorStartingInterpreter, Strings.IssueTrackerUrl).ShowModal();
                return;
            }
        }
Exemplo n.º 8
0
        private void StartInterpreter_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var view = (EnvironmentView)e.Parameter;

            var config = new LaunchConfiguration(view.Factory.Configuration)
            {
                PreferWindowedInterpreter = (e.Command == EnvironmentPathsExtension.StartWindowsInterpreter),
                WorkingDirectory          = view.Factory.Configuration.PrefixPath,
                SearchPaths = new List <string>()
            };

            var sln = (IVsSolution)_site.GetService(typeof(SVsSolution));

            foreach (var pyProj in sln.EnumerateLoadedPythonProjects())
            {
                if (pyProj.InterpreterConfigurations.Contains(config.Interpreter))
                {
                    config.SearchPaths.AddRange(pyProj.GetSearchPaths());
                }
            }

            config.LaunchOptions[PythonConstants.NeverPauseOnExit] = "true";

            Process.Start(Debugger.DebugLaunchHelper.CreateProcessStartInfo(_site, config)).Dispose();
        }
Exemplo n.º 9
0
        private void configComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Sélection d'une autre configuration dans la liste : mise à jour des paramètres
            int selectedConfig = configComboBox.SelectedIndex;

            if (selectedConfig != -1)
            {
                if (selectedConfig == 0)
                {
                    // Ajout de config
                    _InitializeLaunchFormContents(null);
                }
                else
                {
                    // Récupération de la configuration
                    selectedConfig -= 1;

                    LaunchConfiguration currentConfig = _TemporaryConfigList[selectedConfig];

                    if (currentConfig != null)
                    {
                        _InitializeLaunchFormContents(currentConfig);
                    }
                }
            }
        }
Exemplo n.º 10
0
        public override void AddToLaunchConfiguration(LaunchConfiguration configuration)
        {
            base.AddToLaunchConfiguration(configuration);
            FileInfo iso = new FileInfo("c:/cfn/files/en_sql_server_2014_standard_edition_with_service_pack_1_x64_dvd_6669998.iso");

            this.Config.Files.GetFile(iso.FullName).Source = $"https://s3.amazonaws.com/{this.BucketName}/software/{iso.Name}";
        }
Exemplo n.º 11
0
        public override void AddToLaunchConfiguration(LaunchConfiguration configuration)
        {
            base.AddToLaunchConfiguration(configuration);
            var command = this.Config.Commands.AddCommand <Command>("dir2");

            command.Command = "dir>dir2.txt";
        }
Exemplo n.º 12
0
        public Dictionary <string, string> GetFullEnvironment(LaunchConfiguration config)
        {
            // Start with global environment, add configured environment,
            // then add search paths.
            var baseEnv = Environment.GetEnvironmentVariables();

            // Clear search paths from the global environment. The launch
            // configuration should include the existing value
            baseEnv[config.Interpreter.PathEnvironmentVariable] = string.Empty;
            var env = PathUtils.MergeEnvironments(
                baseEnv.AsEnumerable <string, string>(),
                config.GetEnvironmentVariables(),
                "Path", config.Interpreter.PathEnvironmentVariable
                );

            if (config.SearchPaths != null && config.SearchPaths.Any())
            {
                env = PathUtils.MergeEnvironments(
                    env,
                    new[] {
                    new KeyValuePair <string, string>(
                        config.Interpreter.PathEnvironmentVariable,
                        PathUtils.JoinPathList(config.SearchPaths)
                        )
                },
                    config.Interpreter.PathEnvironmentVariable
                    );
            }
            return(env);
        }
Exemplo n.º 13
0
        internal static void GetFullUrl(IServiceProvider provider, LaunchConfiguration config, out Uri uri, out int port)
        {
            int p;

            if (int.TryParse(config.GetLaunchOption(PythonConstants.WebBrowserPortSetting) ?? "", out p))
            {
                port = p;
            }
            else
            {
                SocketUtils.GetRandomPortListener(IPAddress.Loopback, out port).Stop();
                p = -1;
            }

            var host = config.GetLaunchOption(PythonConstants.WebBrowserUrlSetting);

            if (string.IsNullOrEmpty(host))
            {
                uri = null;
                return;
            }

            try {
                UriBuilder builder;
                if (Uri.TryCreate(host, UriKind.Absolute, out uri))
                {
                    builder = new UriBuilder(uri);
                }
                else
                {
                    builder        = new UriBuilder();
                    builder.Scheme = Uri.UriSchemeHttp;
                    builder.Host   = "localhost";
                    builder.Path   = host;
                }

                if (p >= 0)
                {
                    builder.Port = p;
                }
                else if (builder.Port < 0 || (builder.Uri.IsDefaultPort && !host.Contains(":{0}".FormatInvariant(builder.Port))))
                {
                    SocketUtils.GetRandomPortListener(IPAddress.Loopback, out port).Stop();
                    builder.Port = port;
                }

                uri  = builder.Uri;
                port = uri.Port;
            } catch (UriFormatException) {
                if (provider == null)
                {
                    throw;
                }
                var output = OutputWindowRedirector.GetGeneral(provider);
                output.WriteErrorLine(Strings.ErrorInvalidLaunchUrl.FormatUI(host));
                output.ShowAndActivate();
                uri = null;
            }
        }
        internal LaunchConfigurationViewModel(EngineLauncherViewModel launcher, LaunchConfiguration config)
        {
            this.config = config;

            this.DeleteCommand = new UiCommand(
                () => launcher.DeleteConfig(this),
                () => this.IsUserPath);
        }
Exemplo n.º 15
0
 public TeamFoundationServerBuildServerBase(TeamFoundationServerEdition edition,
                                            LaunchConfiguration applicationServer,
                                            string bucketName,
                                            string recipeName,
                                            DbInstance sqlServer4Build) : base(edition, bucketName, recipeName)
 {
     this.ApplicationServer = applicationServer;
     this.SqlServer4Build   = sqlServer4Build;
 }
Exemplo n.º 16
0
        private int Launch(LaunchConfiguration config, bool debug)
        {
            DebugLaunchHelper.RequireStartupFile(config);

            //if (factory.Id == _cpyInterpreterGuid || factory.Id == _cpy64InterpreterGuid) {
            //    MessageBox.Show(
            //        "The project is currently set to use the .NET debugger for IronPython debugging but the project is configured to start with a CPython interpreter.\r\n\r\nTo fix this change the debugger type in project properties->Debug->Launch mode.\r\nIf IronPython is not an available interpreter you may need to download it from http://ironpython.codeplex.com.",
            //        "Visual Studio");
            //    return VSConstants.S_OK;
            //}

            try {
                if (debug)
                {
                    if (string.IsNullOrEmpty(config.InterpreterArguments))
                    {
                        config.InterpreterArguments = "-X:Debug";
                    }
                    else if (config.InterpreterArguments.IndexOf("-X:Debug", StringComparison.OrdinalIgnoreCase) < 0)
                    {
                        config.InterpreterArguments = "-X:Debug " + config.InterpreterArguments;
                    }

                    var  debugStdLib = _project.GetProperty(IronPythonLauncherOptions.DebugStandardLibrarySetting);
                    bool debugStdLibResult;
                    if (!bool.TryParse(debugStdLib, out debugStdLibResult) || !debugStdLibResult)
                    {
                        string interpDir = config.Interpreter.PrefixPath;
                        config.InterpreterArguments += " -X:NoDebug \"" + System.Text.RegularExpressions.Regex.Escape(Path.Combine(interpDir, "Lib\\")) + ".*\"";
                    }

                    using (var dti = DebugLaunchHelper.CreateDebugTargetInfo(_serviceProvider, config)) {
                        // Set the CLR debugger
                        dti.Info.clsidCustom = VSConstants.CLSID_ComPlusOnlyDebugEngine;
                        dti.Info.grfLaunch   = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd;

                        // Clear the CLSID list while launching, then restore it
                        // so Dispose() can free it.
                        var clsidList = dti.Info.pClsidList;
                        dti.Info.pClsidList   = IntPtr.Zero;
                        dti.Info.dwClsidCount = 0;
                        try {
                            dti.Launch();
                        } finally {
                            dti.Info.pClsidList = clsidList;
                        }
                    }
                }
                else
                {
                    var psi = DebugLaunchHelper.CreateProcessStartInfo(_serviceProvider, config);
                    Process.Start(psi).Dispose();
                }
            } catch (FileNotFoundException) {
            }
            return(VSConstants.S_OK);
        }
 public Config(LaunchConfiguration resource) : base(resource)
 {
     Commands = this.Add("commands", new Commands(resource)) as Commands;
     Files    = this.Add("files", new Files(resource)) as Files;
     Services = this.Add("services", new CloudFormationDictionary(resource));
     Sources  = this.Add("sources", new Sources(resource)) as Sources;
     Packages = this.Add("packages", new Packages(resource)) as Packages;
     this.Add("ignoreErrors", false.ToString());
 }
Exemplo n.º 18
0
        private static void RunVTune(SessionNode session, LaunchConfiguration config, bool openReport)
        {
            var interpreter = config.GetInterpreterPath();

            if (!File.Exists(interpreter))
            {
                MessageBox.Show(Strings.CannotFindPythonInterpreter, Strings.ProductTitle);
                return;
            }

            string outPathDir = Path.GetTempPath();
            var    subpath    = Path.Combine(outPathDir, Path.GetRandomFileName());

            while (Directory.Exists(subpath) || File.Exists(subpath))
            {
                subpath = Path.Combine(outPathDir, Path.GetRandomFileName());
            }
            outPathDir = subpath;

            string outPath = Path.Combine(outPathDir, "pythontrace.diagsession");

            var driver = PythonToolsInstallPath.GetFile(ExternalProfilerDriverExe, typeof(PythonProfilingPackage).Assembly);

            var procInfo = new ProcessStartInfo(driver)
            {
                CreateNoWindow = false,
                Arguments      = string.Join(" ", new[] {
                    "-d",
                    ProcessOutput.QuoteSingleArgument(outPathDir),
                    "--",
                    ProcessOutput.QuoteSingleArgument(interpreter),
                    config.InterpreterArguments,
                    string.IsNullOrEmpty(config.ScriptName) ? "" : ProcessOutput.QuoteSingleArgument(config.ScriptName),
                    config.ScriptArguments
                }),
                WorkingDirectory = config.WorkingDirectory,
            };

            var proc = new Process {
                StartInfo = procInfo
            };
            var dte = (EnvDTE.DTE)session._serviceProvider.GetService(typeof(EnvDTE.DTE));

            proc.EnableRaisingEvents = true;
            proc.Exited += (_, args) => {
                if (!File.Exists(Path.Combine(outPathDir, "Sample.dwjson")))
                {
                    MessageBox.Show(Strings.CannotFindGeneratedFile, Strings.ProductTitle);
                }
                else
                {
                    PackageTrace(outPathDir);
                    dte.ItemOperations.OpenFile(Path.Combine(outPathDir, "trace.diagsession"));
                }
            };
            proc.Start();
        }
Exemplo n.º 19
0
        internal Dictionary <string, string> GetFullEnvironment(LaunchConfiguration config)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            // Start with global environment, add configured environment,
            // then add search paths.
            var baseEnv = Environment.GetEnvironmentVariables();
            // Clear search paths from the global environment. The launch
            // configuration should include the existing value

            var pathVar = config.Interpreter?.PathEnvironmentVariable;

            if (string.IsNullOrEmpty(pathVar))
            {
                pathVar = "PYTHONPATH";
            }
            baseEnv[pathVar] = string.Empty;

            // TODO: We could introduce a cache so that we don't activate the
            // environment + capture the env variables every time. Not doing this
            // right now to minimize risk/complexity so close to release.
            if (CondaUtils.IsCondaEnvironment(config.Interpreter.GetPrefixPath()))
            {
                var condaExe   = CondaUtils.GetRootCondaExecutablePath(Site);
                var prefixPath = config.Interpreter.GetPrefixPath();
                if (File.Exists(condaExe) && Directory.Exists(prefixPath))
                {
                    var condaEnv = CondaUtils.CaptureActivationEnvironmentVariablesForPrefix(condaExe, prefixPath);
                    baseEnv = PathUtils.MergeEnvironments(baseEnv.AsEnumerable <string, string>(), condaEnv, "Path", pathVar);
                }
            }

            var env = PathUtils.MergeEnvironments(
                baseEnv.AsEnumerable <string, string>(),
                config.GetEnvironmentVariables(),
                "Path", pathVar
                );

            if (config.SearchPaths != null && config.SearchPaths.Any())
            {
                env = PathUtils.MergeEnvironments(
                    env,
                    new[] {
                    new KeyValuePair <string, string>(
                        pathVar,
                        PathUtils.JoinPathList(config.SearchPaths)
                        )
                },
                    pathVar
                    );
            }
            return(env);
        }
Exemplo n.º 20
0
        private static string GetOptions(IServiceProvider provider, LaunchConfiguration config)
        {
            var pyService = provider.GetPythonToolsService();

            return(string.Join(";", GetGlobalDebuggerOptions(pyService)
                               .Concat(GetLaunchConfigurationOptions(config))
                               .Where(s => !string.IsNullOrEmpty(s))
                               .Select(s => s.Replace(";", ";;"))
                               ));
        }
Exemplo n.º 21
0
        public override void AddToLaunchConfiguration(LaunchConfiguration configuration)
        {
            base.AddToLaunchConfiguration(configuration);
            this.Config.Files.Add("c:/cfn/scripts/ReSharperUltimate.10.0.2.exe")
            .Add("source", "https://s3.amazonaws.com/gtbb/software/JetBrains.ReSharperUltimate.10.0.2.exe");
            var command = this.Config.Commands.AddCommand <Command>("InstallResharper");

            command.Command             = "c:/cfn/scripts/ReSharperUltimate.10.0.2.exe /VsVersion=14 /SpecificProductNames=ReSharper /Silent=True /PerMachine=True";
            command.Test                = "IF EXIST \"C:\\Program Files (x86)\\JetBrains\\Installations\\ReSharperPlatformVs14\\CsLex.exe\" EXIT /B 1";
            command.WaitAfterCompletion = 0.ToString();
        }
Exemplo n.º 22
0
        /// <summary>
        /// Constructeur par défaut
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
            _Instance = this;

            // Titre
            Text = _TITLE_MAIN_FORM;

            // EVO_73: Debug mode notify
            if (bool.Parse(Program.ApplicationSettings.DebugModeEnabled))
            {
                Text += _TITLE_BRIBE_DEBUG;
            }

            // EVO_40 : lancement automatique d'un module
            try
            {
                string moduleName = Program.ApplicationSettings.StartupModule;

                if (StartupModuleList.Contains(moduleName))
                {
                    ModuleType moduleType = (ModuleType)Enum.Parse(typeof(ModuleType), moduleName);

                    LoadTool(moduleType, null);
                }
            }
            catch (Exception ex)
            {
                // Exception silencieuse
                Exception2.PrintStackTrace(new Exception("Unable to launch startup module.", ex));
            }

            // EVO_36 : initialisation des configurations de lancement
            string launchConfigurationsValue = Program.ApplicationSettings.TduLaunchConfigurations;

            if (string.IsNullOrEmpty(launchConfigurationsValue))
            {
                Collection <LaunchConfiguration> launchConfigs = new Collection <LaunchConfiguration>();
                LaunchConfiguration launchConfig = new LaunchConfiguration
                {
                    Default = true,
                    Name    = _LAUNCH_CONFIG_DEFAULT_NAME
                };

                launchConfigs.Add(launchConfig);

                Program.ApplicationSettings.TduLaunchConfigurations = LaunchConfigurationConverter.ConvertToString(launchConfigs);
                Program.ApplicationSettings.Save();
            }

            // View mode
            _isBasicView = !bool.Parse(Program.ApplicationSettings.AdvancedMode);
            _SetView();
        }
Exemplo n.º 23
0
        public override void AddToLaunchConfiguration(LaunchConfiguration configuration)
        {
            base.AddToLaunchConfiguration(configuration);
            var node      = GetChefNodeJsonContent(configuration);
            var tfsNode   = node.Add("tfs");
            var sqlServer = new FnJoin(FnJoinDelimiter.Period, SqlServer.LogicalId, new ReferenceProperty(ActiveDirectoryBase.DomainFqdnParameterName));

            tfsNode.Add("application_server_sqlname", sqlServer);
            tfsNode.Add(TeamFoundationServerBuildServerBase.TfsServiceAccountNameParameterName, new ReferenceProperty(TeamFoundationServerBuildServerBase.TfsServiceAccountNameParameterName));
            tfsNode.Add(TeamFoundationServerBuildServerBase.TfsServicePasswordParameterName, new ReferenceProperty(TeamFoundationServerBuildServerBase.TfsServicePasswordParameterName));
        }
Exemplo n.º 24
0
        internal void AddPropertiesAfter(LaunchConfiguration config)
        {
            AddArgumentAtEnd(config.ScriptArguments);
            WorkingDirectory = ChooseFirst(WorkingDirectory, config.WorkingDirectory);

            EnvironmentVariables = PathUtils.MergeEnvironments(
                EnvironmentVariables.MaybeEnumerate(),
                config.Environment.MaybeEnumerate(),
                "PATH", config.Interpreter.PathEnvironmentVariable
                );
        }
Exemplo n.º 25
0
 public override void AddUser(LaunchConfiguration instance, string ou, ReferenceProperty user, ReferenceProperty password)
 {
     if (this.Type == ResourceType.AwsDirectoryServiceMicrosoftAd)
     {
         AddUserMicrosoftAd(instance, ou, (object)user, (object)password);
     }
     else
     {
         AddUserSimpleAd(instance, ou, (object)user, (object)password);
     }
 }
Exemplo n.º 26
0
 /// <summary>
 /// Default implementation of the "Start without Debugging" command.
 /// </summary>
 private Process StartWithoutDebugger(LaunchConfiguration config)
 {
     try {
         _serviceProvider.GetPythonToolsService().Logger.LogEvent(Logging.PythonLogEvent.Launch, new Logging.LaunchInfo {
             IsDebug = false,
             Version = config.Interpreter?.Version.ToString() ?? ""
         });
     } catch (Exception ex) {
         Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
     }
     return(Process.Start(DebugLaunchHelper.CreateProcessStartInfo(_serviceProvider, config)));
 }
        public override void AddToLaunchConfiguration(LaunchConfiguration configuration)
        {
            base.AddToLaunchConfiguration(configuration);
            const string powerShellToolsVsixLocalPath = "c:/cfn/scripts/PowerShellTools.14.0.vsix";
            var          powerShellToolsVsix          = this.Config.Files.GetFile(powerShellToolsVsixLocalPath);

            powerShellToolsVsix.Source = "https://visualstudiogallery.msdn.microsoft.com/c9eb3ba8-0c59-4944-9a62-6eee37294597/file/199313/2/PowerShellTools.14.0.vsix";
            var installPowerSehllToolsVsix = this.Config.Commands.AddCommand <Command>("PowerShellTools140vsix");

            installPowerSehllToolsVsix.Command             = $"\"C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\VSIXInstaller.exe\" /q {powerShellToolsVsixLocalPath}";
            installPowerSehllToolsVsix.WaitAfterCompletion = 0.ToString();
        }
Exemplo n.º 28
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public override IDebugLaunchSettings [] QueryDebugTargets(DebugLaunchOptions launchOptions)
        {
            LoggingUtils.PrintFunction();

            IDebugLauncher debugLauncher = null;

            try
            {
                debugLauncher = GetDebugLauncher(ServiceProvider);

                debugLauncher.PrepareLaunch();

                DebugLaunchSettings debugLaunchSettings;

                Dictionary <string, string> projectProperties = DebuggerProperties.ProjectPropertiesToDictionary();

                projectProperties.Add("ConfigurationGeneral.ProjectDir", Path.GetDirectoryName(DebuggerProperties.GetConfiguredProject().UnconfiguredProject.FullPath));

                LaunchConfiguration launchConfig = debugLauncher.GetLaunchConfigurationFromProjectProperties(projectProperties);

                LaunchProps [] launchProps = debugLauncher.GetLaunchPropsFromProjectProperties(projectProperties);

                if (launchOptions.HasFlag(DebugLaunchOptions.NoDebug))
                {
                    debugLaunchSettings = (DebugLaunchSettings)debugLauncher.StartWithoutDebugging((int)launchOptions, launchConfig, launchProps, projectProperties);
                }
                else
                {
                    debugLaunchSettings = (DebugLaunchSettings)debugLauncher.StartWithDebugging((int)launchOptions, launchConfig, launchProps, projectProperties);
                }

                return(new IDebugLaunchSettings [] { debugLaunchSettings });
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                string description = string.Format("'QueryDebugTargets' failed:\n[Exception]{0}", e.Message);

#if DEBUG
                description += "\n[Exception] Stack trace:\n" + e.StackTrace;
#endif

                if (debugLauncher != null)
                {
                    LoggingUtils.RequireOk(debugLauncher.GetConnectionService().LaunchDialogUpdate(description, true));
                }

                VsShellUtilities.ShowMessageBox(ServiceProvider, description, "Android++ Debugger", OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }

            return(null);
        }
Exemplo n.º 29
0
        public override void AddToLaunchConfiguration(LaunchConfiguration configuration)
        {
            base.AddToLaunchConfiguration(configuration);
            const string fileName = "Git-2.7.1.2-64-bit.exe";
            const string filePath = "c:/cfn/scripts/" + fileName;

            this.Config.Files.Add(filePath)
            .Add("source", $"https://s3.amazonaws.com/{this.BucketName}/software/{fileName}");


            this.Config.Commands.AddCommand <Command>(fileName.Replace('.', '-')).Command = $"{filePath} /silent";
        }
Exemplo n.º 30
0
        public static void RequireStartupFile(LaunchConfiguration config)
        {
            if (string.IsNullOrEmpty(config.ScriptName))
            {
                throw new NoStartupFileException(Strings.DebugLaunchScriptNameMissing);
            }

            if (!File.Exists(config.ScriptName))
            {
                throw new NoStartupFileException(Strings.DebugLaunchScriptNameDoesntExist.FormatUI(config.ScriptName));
            }
        }
Exemplo n.º 31
0
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public DebugEngine ()
    {
      m_broadcastHandleLock = new AutoResetEvent (false);

      m_breakpointManager = new DebugBreakpointManager (this);

      m_launchConfiguration = new LaunchConfiguration ();

      Program = null;

      NativeDebugger = null;

      JavaDebugger = null;
    }
Exemplo n.º 32
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void InstallApplicationAsync(AndroidDevice debuggingDevice, LaunchConfiguration launchConfig)
        {
            //
              // Asynchronous installation process, so the UI can be updated appropriately.
              //

              LoggingUtils.PrintFunction ();

              ManualResetEvent installCompleteEvent = new ManualResetEvent (false);

              Exception installFailedException = null;

              System.Threading.Thread asyncInstallApplicationThread = new System.Threading.Thread (delegate ()
              {
            try
            {
              string targetLocalApk = launchConfig ["TargetApk"];

              string targetRemoteTemporaryPath = "/data/local/tmp";

              string targetRemoteTemporaryFile = targetRemoteTemporaryPath + '/' + Path.GetFileName (targetLocalApk);

              bool keepData = launchConfig ["KeepAppData"].Equals ("true");

              string installerPackage = launchConfig ["InstallerPackage"];

              //
              // Construct 'am install' arguments for installing the application in a manner compatible with GDB.
              //
              // Note: Installations to /mnt/asec/ cause 'run-as' to fail regarding permissions.
              //

              StringBuilder installArgsBuilder = new StringBuilder ();

              installArgsBuilder.Append ("-f "); // install package on internal flash. (required for debugging)

              if (keepData)
              {
            installArgsBuilder.Append ("-r "); // reinstall an existing app, keeping its data.
              }

              if (!string.IsNullOrWhiteSpace (installerPackage))
              {
            installArgsBuilder.Append (string.Format (CultureInfo.InvariantCulture, "-i {0} ", installerPackage));
              }

              installArgsBuilder.Append (targetRemoteTemporaryFile);

              //
              // Explicitly install the target APK using 'pm' tool, as this allows more customisation.
              //
              //  1) APKs must already be on the device for this tool to work. We push these manually.
              //
              //  2) Installations can fail for various reasons; errors are reported thusly:
              //         pkg: /data/local/tmp/hello-gdbserver-Debug.apk
              //       Failure [INSTALL_FAILED_INVALID_URI]
              //

              m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "[adb:push] {0} {1}", targetLocalApk, targetRemoteTemporaryPath), false);

              debuggingDevice.Push (targetLocalApk, targetRemoteTemporaryPath);

              m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "[adb:shell:pm] {0} {1}", "install", installArgsBuilder.ToString ()), false);

              string installReport = debuggingDevice.Shell ("pm", "install " + installArgsBuilder.ToString (), int.MaxValue);

              if (!installReport.Contains ("Success"))
              {
            string sanitisedFailure = installReport;

            throw new InvalidOperationException (string.Format (CultureInfo.InvariantCulture, "[adb:shell:pm] install failed: {0}", sanitisedFailure));
              }

              m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "[adb:shell:rm] {0}", targetRemoteTemporaryFile), false);

              debuggingDevice.Shell ("rm", targetRemoteTemporaryFile);
            }
            catch (Exception e)
            {
              LoggingUtils.HandleException (e);

              installFailedException = e;

              throw;
            }
            finally
            {
              installCompleteEvent.Set ();
            }
              });

              asyncInstallApplicationThread.Start ();

              while (!installCompleteEvent.WaitOne (0))
              {
            Application.DoEvents ();

            System.Threading.Thread.Sleep (100);
              }

              if (installFailedException != null)
              {
            throw installFailedException;
              }
        }
Exemplo n.º 33
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public object StartWithoutDebugging(int launchOptions, LaunchConfiguration launchConfig, LaunchProps [] launchProps, IDictionary<string, string> projectProperties)
        {
            LoggingUtils.PrintFunction ();

              if (launchConfig == null)
              {
            throw new ArgumentNullException ("launchConfig");
              }

              if (launchProps == null)
              {
            throw new ArgumentNullException ("launchProps");
              }

              if (projectProperties == null)
              {
            throw new ArgumentNullException ("projectProperties");
              }

              try
              {
            //
            // Refresh ADB service and evaluate a list of connected devices or emulators.
            //

            AndroidAdb.Refresh ();

            AndroidDevice debuggingDevice = GetPrioritisedConnectedDevice ();

            if (debuggingDevice == null)
            {
              throw new InvalidOperationException ("No device/emulator found or connected. Check status using \"adb devices\".");
            }

            //
            // Construct VS launch settings to debug or attach to the specified target application.
            //

            launchOptions |= (int) DebugLaunchOptions.Silent;

            DebugLaunchSettings nonDebuglaunchSettings = new DebugLaunchSettings ((DebugLaunchOptions) launchOptions);

            nonDebuglaunchSettings.LaunchDebugEngineGuid = new Guid ("8310DAF9-1043-4C8E-85A0-FF68896E1922");

            nonDebuglaunchSettings.PortSupplierGuid = new Guid ("3AEE417F-E5F9-4B89-BC31-20534C99B7F5");

            nonDebuglaunchSettings.PortName = debuggingDevice.ID;

            nonDebuglaunchSettings.Options = launchConfig.ToString ();

            nonDebuglaunchSettings.Executable = launchConfig ["TargetApk"];

            nonDebuglaunchSettings.LaunchOperation = DebugLaunchOperation.Custom;

            return nonDebuglaunchSettings;
              }
              catch (Exception e)
              {
            LoggingUtils.HandleException (e);

            throw;
              }
        }
Exemplo n.º 34
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public object StartWithDebugging(int launchOptions, LaunchConfiguration launchConfig, LaunchProps [] launchProps, IDictionary<string, string> projectProperties)
        {
            LoggingUtils.PrintFunction ();

              if (launchConfig == null)
              {
            throw new ArgumentNullException ("launchConfig");
              }

              if (launchProps == null)
              {
            throw new ArgumentNullException ("launchProps");
              }

              if (projectProperties == null)
              {
            throw new ArgumentNullException ("projectProperties");
              }

              try
              {
            //
            // Refresh ADB service and evaluate a list of connected devices or emulators.
            //

            AndroidAdb.Refresh ();

            AndroidDevice debuggingDevice = GetPrioritisedConnectedDevice ();

            if (debuggingDevice == null)
            {
              throw new InvalidOperationException ("No device/emulator found or connected. Check status using \"adb devices\".");
            }

            //
            // Enforce required device/emulator properties.
            //

            foreach (LaunchProps prop in launchProps)
            {
              debuggingDevice.Shell ("setprop", string.Format (CultureInfo.InvariantCulture, "{0} {1}", prop.Item1, prop.Item2));
            }

            //
            // Construct VS launch settings to debug or attach to the specified target application.
            //

            bool shouldAttach = false;

            #if false
            AndroidProcess [] debuggingDeviceProcesses = debuggingDevice.GetProcesses ();

            foreach (AndroidProcess process in debuggingDeviceProcesses)
            {
              if (process.Name.Equals (applicationPackageName))
              {
            shouldAttach = true;

            break;
              }
            }
            #endif

            launchOptions |= (int) DebugLaunchOptions.Silent;

            DebugLaunchSettings debugLaunchSettings = new DebugLaunchSettings ((DebugLaunchOptions) launchOptions);

            debugLaunchSettings.LaunchDebugEngineGuid = new Guid ("8310DAF9-1043-4C8E-85A0-FF68896E1922");

            debugLaunchSettings.PortSupplierGuid = new Guid ("3AEE417F-E5F9-4B89-BC31-20534C99B7F5");

            debugLaunchSettings.PortName = debuggingDevice.ID;

            debugLaunchSettings.Options = launchConfig.ToString ();

            if (shouldAttach)
            {
              debugLaunchSettings.Executable = launchConfig ["PackageName"];

              debugLaunchSettings.LaunchOperation = DebugLaunchOperation.AlreadyRunning;
            }
            else
            {
              //
              // Determine whether the application is currently installed, and if it is;
              // check last modified date to ensure we don't re-installed unchanged binaries.
              //

              bool upToDateCheck = launchConfig ["UpToDateCheck"].Equals ("true");

              bool appIsInstalled = false;

              bool appIsOutOfDate = true;

              if (upToDateCheck)
              {
            FileInfo targetApkFileInfo = new FileInfo (launchConfig ["TargetApk"]);

            try
            {
              string [] adbPmPathOutput = debuggingDevice.Shell ("pm", "path " + launchConfig ["PackageName"]).Replace ("\r", "").Split (new char [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

              foreach (string line in adbPmPathOutput)
              {
                if (line.StartsWith ("package:", StringComparison.OrdinalIgnoreCase))
                {
                  appIsInstalled = true;

                  LoggingUtils.RequireOk (m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "'{0}' already installed on target '{1}'.", launchConfig ["PackageName"], debuggingDevice.ID), false));

                  string path = line.Substring ("package:".Length);

                  //
                  // Get the target device/emulator's UTC current time.
                  //
                  //   This is done by specifying the '-u' argument to 'date'. Despite this though,
                  //   the returned string will always claim to be in GMT:
                  //
                  //   i.e: "Fri Jan  9 14:35:23 GMT 2015"
                  //

                  DateTime debuggingDeviceUtcTime;

                  try
                  {
                    string [] deviceDateOutput = debuggingDevice.Shell ("date", "-u").Replace ("\r", "").Split (new char [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                    string debuggingDeviceUtcTimestamp = deviceDateOutput [0];

                    string [] debuggingDeviceUtcTimestampComponents = debuggingDeviceUtcTimestamp.Split (new char [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    debuggingDeviceUtcTimestampComponents [4] = "-00:00";

                    if (!DateTime.TryParseExact (string.Join (" ", debuggingDeviceUtcTimestampComponents), "ddd MMM  d HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out debuggingDeviceUtcTime))
                    {
                      break;
                    }

                    debuggingDeviceUtcTime = debuggingDeviceUtcTime.ToUniversalTime ();
                  }
                  catch (Exception e)
                  {
                    throw new InvalidOperationException ("Failed to evaluate device local time.", e);
                  }

                  //
                  // Convert current device/emulator time to UTC, and probe the working machine's time too.
                  //

                  DateTime thisMachineUtcTime = DateTime.UtcNow;

                  TimeSpan thisMachineUtcVersusDeviceUtc = debuggingDeviceUtcTime - thisMachineUtcTime;

                  LoggingUtils.RequireOk (m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "Current UTC time on '{0}': {1}", debuggingDevice.ID, debuggingDeviceUtcTime.ToString ()), false));

                  LoggingUtils.RequireOk (m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "Current UTC time on '{0}': {1}", System.Environment.MachineName, thisMachineUtcTime.ToString ()), false));

                  LoggingUtils.RequireOk (m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "Difference in UTC time between '{0}' and '{1}': {2}", System.Environment.MachineName, debuggingDevice.ID, thisMachineUtcVersusDeviceUtc.ToString ()), false));

                  //
                  // Check the last modified date; ls output currently uses this format:
                  //
                  // -rw-r--r-- system   system   11533274 2015-01-09 13:47 com.example.native_activity-2.apk
                  //

                  DateTime lastModifiedTimestampDeviceLocalTime;

                  try
                  {
                    string [] extendedLsOutput = debuggingDevice.Shell ("ls -l", path).Replace ("\r", "").Split (new char [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                    string [] extendedLsOutputComponents = extendedLsOutput [0].Split (new char [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    string date = extendedLsOutputComponents [4];

                    string time = extendedLsOutputComponents [5];

                    if (!DateTime.TryParseExact (date + " " + time, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out lastModifiedTimestampDeviceLocalTime))
                    {
                      break;
                    }
                  }
                  catch (Exception e)
                  {
                    throw new InvalidOperationException (string.Format (CultureInfo.InvariantCulture, "Failed to evaluate device local modified time of: {0}", path), e);
                  }

                  //
                  // Calculate how long ago the APK was changed, according to the device's local time.
                  //

                  TimeSpan timeSinceLastModification = debuggingDeviceUtcTime - lastModifiedTimestampDeviceLocalTime;

                  DateTime debuggingDeviceUtcTimeAtLastModification = debuggingDeviceUtcTime - timeSinceLastModification;

                  DateTime thisMachineUtcTimeAtLastModification = thisMachineUtcTime - timeSinceLastModification;

                  LoggingUtils.RequireOk (m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "'{0}' was last modified on '{1}' at: {2}.", launchConfig ["PackageName"], debuggingDevice.ID, debuggingDeviceUtcTimeAtLastModification.ToString ()), false));

                  LoggingUtils.RequireOk (m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "{0} (on {1}) was around {2} (on {3}).", debuggingDeviceUtcTimeAtLastModification.ToString (), debuggingDevice.ID, thisMachineUtcTimeAtLastModification.ToString (), System.Environment.MachineName), false));

                  LoggingUtils.RequireOk (m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "'{0}' was last modified on '{1}' at: {2}.", Path.GetFileName (targetApkFileInfo.FullName), System.Environment.MachineName, targetApkFileInfo.LastWriteTime.ToString ()), false));

                  if ((targetApkFileInfo.LastWriteTime + thisMachineUtcVersusDeviceUtc) > thisMachineUtcTimeAtLastModification)
                  {
                    LoggingUtils.RequireOk (m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "'{0}' was determined to be out-of-date. Reinstalling...", launchConfig ["PackageName"]), false));
                  }
                  else
                  {
                    appIsOutOfDate = false;
                  }

                  break;
                }
              }
            }
            catch (Exception)
            {
              appIsInstalled = false;
            }
              }
              else
              {
            LoggingUtils.RequireOk (m_debugConnectionService.LaunchDialogUpdate ("Skipping up-to-date check.", false));
              }

              if (!appIsInstalled || appIsOutOfDate)
              {
            LoggingUtils.RequireOk (m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "Installing '{0}' to '{1}'...", launchConfig ["PackageName"], debuggingDevice.ID), false));

            InstallApplicationAsync (debuggingDevice, launchConfig);

            LoggingUtils.RequireOk (m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "'{0}' installed successfully.", launchConfig ["PackageName"]), false));
              }
              else
              {
            LoggingUtils.RequireOk (m_debugConnectionService.LaunchDialogUpdate (string.Format (CultureInfo.InvariantCulture, "'{0}' on '{1}' is up-to-date. Skipping installation...", launchConfig ["PackageName"], debuggingDevice.ID), false));
              }

              debugLaunchSettings.Executable = launchConfig ["TargetApk"];

              debugLaunchSettings.LaunchOperation = DebugLaunchOperation.Custom;
            }

            return debugLaunchSettings;
              }
              catch (Exception e)
              {
            LoggingUtils.HandleException (e);

            throw;
              }
        }
Exemplo n.º 35
0
        public LaunchConfiguration GetLaunchConfigurationFromProjectProperties(IDictionary<string, string> projectProperties)
        {
            LoggingUtils.PrintFunction ();

              //
              // Retrieve standard project macro values, and determine the preferred debugger configuration.
              //

              string projectTargetName = EvaluateProjectProperty (projectProperties, "ConfigurationGeneral", "TargetName");

              string projectProjectDir = EvaluateProjectProperty (projectProperties, "ConfigurationGeneral", "ProjectDir");

              string debuggerMode = EvaluateProjectProperty (projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigMode");

              string debuggerTargetApk = EvaluateProjectProperty (projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigTargetApk");

              string debuggerUpToDateCheck = EvaluateProjectProperty (projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigUpToDateCheck");

              string debuggerLaunchActivity = EvaluateProjectProperty (projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigLaunchActivity");

              string debuggerDebugMode = EvaluateProjectProperty (projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigDebugMode");

              string debuggerOpenGlTrace = EvaluateProjectProperty (projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigOpenGlTrace");

              string debuggerKeepAppData = EvaluateProjectProperty (projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigKeepAppData");

              string debuggerInstallerPackage = EvaluateProjectProperty (projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigInstallerPackage");

              if (string.IsNullOrEmpty (debuggerMode))
              {
            debuggerMode = "Custom";
              }
              else if (debuggerMode.Equals ("vs-android"))
              {
            //
            // Support for vs-android.
            //

            string antBuildPath = EvaluateProjectProperty (projectProperties, "AntBuild", "AntBuildPath");

            string antBuildType = EvaluateProjectProperty (projectProperties, "AntBuild", "AntBuildType");

            string antBuildXml = Path.Combine (antBuildPath, "build.xml");

            XmlDocument buildXmlDocument = new XmlDocument ();

            buildXmlDocument.Load (antBuildXml);

            string antBuildXmlProjectName = buildXmlDocument.DocumentElement.GetAttribute ("name");

            debuggerTargetApk = Path.Combine (antBuildPath, "bin", string.Format (CultureInfo.InvariantCulture, "{0}-{1}.apk", antBuildXmlProjectName, antBuildType));
              }

              //
              // Ensure the provided target APK is found and absolute.
              //

              if (string.IsNullOrEmpty (debuggerTargetApk))
              {
            throw new FileNotFoundException ("Could not locate target application. Empty path provided.");
              }
              else if (!Path.IsPathRooted (debuggerTargetApk) && !string.IsNullOrWhiteSpace (projectProjectDir))
              {
            debuggerTargetApk = Path.Combine (projectProjectDir, debuggerTargetApk);
              }

              if (!Path.IsPathRooted (debuggerTargetApk))
              {
            throw new InvalidOperationException ("Could not evaluate an absolute path to the target application. Tried: " + debuggerTargetApk);
              }

              debuggerTargetApk = Path.GetFullPath (debuggerTargetApk); // normalises relative paths.

              if (!File.Exists (debuggerTargetApk))
              {
            throw new FileNotFoundException ("Could not find required target application. Expected: " + debuggerTargetApk);
              }

              //
              // Find the selected Android SDK (and associated build-tools) deployment.
              //

              string androidSdkRoot = EvaluateProjectProperty (projectProperties, "ConfigurationGeneral", "AndroidSdkRoot");

              if (string.IsNullOrWhiteSpace (androidSdkRoot))
              {
            throw new DirectoryNotFoundException ("Could not locate Android SDK. \"AndroidSdkRoot\" property is empty.");
              }
              else if (!Directory.Exists (androidSdkRoot))
              {
            throw new DirectoryNotFoundException ("Could not locate Android SDK. \"AndroidSdkRoot\" property references a directory which does not exist. Expected: " + androidSdkRoot);
              }

              string androidSdkBuildToolsVersion = EvaluateProjectProperty (projectProperties, "ConfigurationGeneral", "AndroidSdkBuildToolsVersion");

              string androidSdkBuildToolsPath = Path.Combine (androidSdkRoot, "build-tools", androidSdkBuildToolsVersion);

              if (!Directory.Exists (androidSdkBuildToolsPath))
              {
            throw new DirectoryNotFoundException (string.Format (CultureInfo.CurrentCulture, "Could not locate Android SDK build-tools (v{0}). Expected: {1}", androidSdkBuildToolsVersion, androidSdkBuildToolsPath));
              }

              //
              // Spawn a AAPT.exe instance to gain some extra information about the APK we are trying to load.
              //

              string applicationPackageName = string.Empty;

              string applicationLaunchActivity = string.Empty;

              string aaptToolPath = Path.Combine (androidSdkBuildToolsPath, "aapt.exe");

              if (!File.Exists (aaptToolPath))
              {
            throw new FileNotFoundException ("Could not locate AAPT tool (under Android SDK build-tools).", aaptToolPath);
              }

              using (SyncRedirectProcess getApkDetails = new SyncRedirectProcess (aaptToolPath, "dump --values badging " + PathUtils.SantiseWindowsPath (debuggerTargetApk)))
              {
            int exitCode = getApkDetails.StartAndWaitForExit ();

            if (exitCode != 0)
            {
              throw new InvalidOperationException ("AAPT failed to dump required application badging information. Exit-code: " + exitCode);
            }

            string [] apkDetails = getApkDetails.StandardOutput.Replace ("\r", "").Split (new char [] { '\n' });

            foreach (string singleLine in apkDetails)
            {
              if (singleLine.StartsWith ("package: ", StringComparison.OrdinalIgnoreCase))
              {
            //
            // Retrieve package name from format: "package: name='com.example.hellogdbserver' versionCode='1' versionName='1.0'"
            //

            string [] packageData = singleLine.Substring ("package: ".Length).Split (' ');

            foreach (string data in packageData)
            {
              if (data.StartsWith ("name=", StringComparison.OrdinalIgnoreCase))
              {
                applicationPackageName = data.Substring ("name=".Length).Trim ('\'');
              }
            }
              }
              else if (singleLine.StartsWith ("launchable-activity: ", StringComparison.OrdinalIgnoreCase))
              {
            string [] launchActivityData = singleLine.Substring ("launchable-activity: ".Length).Split (' ');

            foreach (string data in launchActivityData)
            {
              if (data.StartsWith ("name=", StringComparison.OrdinalIgnoreCase))
              {
                applicationLaunchActivity = data.Substring ("name=".Length).Trim ('\'');
              }
            }
              }
            }
              }

              //
              // If a specific launch activity was not requested, ensure that the default one is referenced.
              //

              if (string.IsNullOrEmpty (debuggerLaunchActivity))
              {
            debuggerLaunchActivity = applicationLaunchActivity;
              }

              LaunchConfiguration launchConfig = new LaunchConfiguration ();

              launchConfig ["TargetApk"] = debuggerTargetApk;

              launchConfig ["UpToDateCheck"] = debuggerUpToDateCheck;

              launchConfig ["PackageName"] = applicationPackageName;

              launchConfig ["LaunchActivity"] = debuggerLaunchActivity;

              launchConfig ["DebugMode"] = debuggerDebugMode;

              launchConfig ["OpenGlTrace"] = debuggerOpenGlTrace;

              launchConfig ["KeepAppData"] = debuggerKeepAppData;

              launchConfig ["InstallerPackage"] = debuggerInstallerPackage;

              return launchConfig;
        }
Exemplo n.º 36
0
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public CLangDebugger (DebugEngine debugEngine, LaunchConfiguration launchConfiguration, DebuggeeProgram debugProgram)
    {
      Engine = debugEngine;

      m_launchConfiguration = launchConfiguration;

      NativeProgram = new CLangDebuggeeProgram (this, debugProgram);

      NativeMemoryBytes = new CLangDebuggeeMemoryBytes (this);

      VariableManager = new CLangDebuggerVariableManager (this);

      // 
      // Evaluate target device's architecture triple.
      // 

      string preferedGdbAbiToolPrefix = string.Empty;

      bool allow64BitAbis = true;

      switch (debugProgram.DebugProcess.NativeProcess.PrimaryCpuAbi)
      {
        case "armeabi":
        case "armeabi-v7a":
        {
          preferedGdbAbiToolPrefix = "arm-linux-androideabi";

          break;
        }

        case "arm64-v8a":
        {
          if (allow64BitAbis)
          {
            preferedGdbAbiToolPrefix = "aarch64-linux-android";
          }
          else
          {
            preferedGdbAbiToolPrefix = "arm-linux-androideabi";
          }

          break;
        }

        case "x86":
        {
          preferedGdbAbiToolPrefix = "i686-linux-android";

          break;
        }

        case "x86_64":
        {
          if (allow64BitAbis)
          {
            preferedGdbAbiToolPrefix = "x86_64-linux-android";
          }
          else
          {
            preferedGdbAbiToolPrefix = "i686-linux-android";
          }

          break;
        }

        case "mips":
        {
          preferedGdbAbiToolPrefix = "mipsel-linux-android";

          break;
        }

        case "mips64":
        {
          if (allow64BitAbis)
          {
            preferedGdbAbiToolPrefix = "mips64el-linux-android";
          }
          else
          {
            preferedGdbAbiToolPrefix = "mipsel-linux-android";
          }

          break;
        }
      }

      if (string.IsNullOrEmpty (preferedGdbAbiToolPrefix))
      {
        throw new InvalidOperationException (string.Format ("Unrecognised target primary CPU ABI: {0}", debugProgram.DebugProcess.NativeProcess.PrimaryCpuAbi));
      }

      bool preferedGdbAbiIs64Bit = preferedGdbAbiToolPrefix.Contains ("64");

      Engine.Broadcast (new DebugEngineEvent.DebuggerConnectionEvent (DebugEngineEvent.DebuggerConnectionEvent.EventType.LogStatus, string.Format ("Configuring GDB for '{0}' target...", preferedGdbAbiToolPrefix)), null, null);

      // 
      // Android++ bundles its own copies of GDB to get round various NDK issues. Search for these.
      // 

      string androidPlusPlusRoot = Environment.GetEnvironmentVariable ("ANDROID_PLUS_PLUS");

      // 
      // Build GDB version permutations.
      // 

      List<string> gdbToolPermutations = new List<string> ();

      string [] availableHostArchitectures = new string [] { "x86", "x86_64" };

      foreach (string arch in availableHostArchitectures)
      {
        if (arch.Contains ("64") && !Environment.Is64BitOperatingSystem)
        {
          continue;
        }

        string gdbToolFilePattern = string.Format ("{0}-gdb.cmd", preferedGdbAbiToolPrefix);

        string [] availableVersionPaths = Directory.GetDirectories (Path.Combine (androidPlusPlusRoot, "contrib", "gdb", "bin", arch), "*.*.*", SearchOption.TopDirectoryOnly);

        foreach (string versionPath in availableVersionPaths)
        {
          string [] gdbToolMatches = Directory.GetFiles (versionPath, gdbToolFilePattern, SearchOption.TopDirectoryOnly);

          foreach (string tool in gdbToolMatches)
          {
            gdbToolPermutations.Add (tool);
          }
        }
      }

      if (gdbToolPermutations.Count == 0)
      {
        throw new InvalidOperationException ("Could not locate required 32/64-bit GDB deployments.");
      }
      else
      {
        // 
        // Pick the oldest GDB version available if running 'Jelly Bean' or below.
        // 

        bool forceNdkR9dClient = (debugProgram.DebugProcess.NativeProcess.HostDevice.SdkVersion <= AndroidSettings.VersionCode.JELLY_BEAN);

        if (forceNdkR9dClient)
        {
          m_gdbSetup = new GdbSetup (debugProgram.DebugProcess.NativeProcess, gdbToolPermutations [0]);
        }
        else
        {
          m_gdbSetup = new GdbSetup (debugProgram.DebugProcess.NativeProcess, gdbToolPermutations [gdbToolPermutations.Count - 1]);
        }

        // 
        // A symbolic link to 'share' is placed in the architecture directory, provide GDB with that location.
        // 

        string architecturePath = Path.GetDirectoryName (Path.GetDirectoryName (m_gdbSetup.GdbToolPath));

        string pythonGdbScriptsPath = Path.Combine (architecturePath, "share", "gdb");

        m_gdbSetup.GdbToolArguments += " --data-directory " + PathUtils.SantiseWindowsPath (pythonGdbScriptsPath);
      }

      if (m_gdbSetup == null)
      {
        throw new InvalidOperationException ("Could not evaluate a suitable GDB instance. Ensure you have the correct NDK deployment for your system's architecture.");
      }

      if (m_launchConfiguration != null)
      {
        string launchDirectory;

        if (m_launchConfiguration.TryGetValue ("LaunchSuspendedDir", out launchDirectory))
        {
          m_gdbSetup.SymbolDirectories.Add (launchDirectory);
        }
      }

      GdbServer = new GdbServer (m_gdbSetup);

      GdbClient = new GdbClient (m_gdbSetup);

      GdbClient.OnResultRecord = OnClientResultRecord;

      GdbClient.OnAsyncRecord = OnClientAsyncRecord;

      GdbClient.OnStreamRecord = OnClientStreamRecord;

      GdbClient.Start ();
    }