示例#1
0
        protected virtual IProcessAsyncOperation StartProcess(XmlDocument options)
        {
            string mono       = Utilities.GetMonoExecutable();
            string executable = options.DocumentElement["executable"].InnerText;
            string arguments  = options.DocumentElement["arguments"].InnerText;

            string mono_arguments = string.Empty;

            if (options.DocumentElement["monoarguments"] != null)
            {
                mono_arguments = options.DocumentElement["monoarguments"].InnerText;
            }

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

            AddMonoArguments(args);
            args.Add(mono_arguments);
            args.Add(executable);
            AddExecutableArguments(args);
            args.Add(arguments);

            string args_string = string.Join(" ", args.ToArray());

            var env_vars = ParseEnvironmentVariables(options);

            Logger.LogDebug("  Process->File: {0}", mono);
            Logger.LogDebug("  Process->Arguments: {0}", args_string);
            Logger.LogDebug("  Process->WorkingDir: {0}", RemotePath);
            Logger.LogDebug("  Pause Terminal: {0}", PauseTerminal);

            IProcessAsyncOperation console = TerminalManager.StartConsoleProcess(mono, args_string, RemotePath, env_vars, "MonoTools Process", PauseTerminal);

            return(console);
        }
            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, info.EnvironmentVariables,
                        console, null);
                }
                else
                {
                    var psi = new ProcessStartInfo(info.Command, info.Arguments)
                    {
                        WorkingDirectory = info.WorkingDirectory,
                    };
                    foreach (KeyValuePair <string, string> kvp in info.EnvironmentVariables)
                    {
                        psi.EnvironmentVariables [kvp.Key] = kvp.Value;
                    }

                    process = Runtime.ProcessService.StartProcess(psi, ProcessOutput, ProcessError, null);
                }
            }
示例#3
0
        void ProcessExited(IAsyncOperation oper)
        {
            lock (this) {
                Counters.ExternalHostProcesses--;

                // Remove all callbacks from existing objects
                foreach (object ob in remoteObjects)
                {
                    RemotingService.UnregisterMethodCallback(ob, "Dispose");
                }

                remoteObjects.Clear();

                exitedEvent.Set();

                // If the remote process crashes, a thread may be left hung in WaitForExit. This will awaken it.
                exitRequestEvent.Set();

                if (oper != process)
                {
                    return;
                }

                // The process suddently died
                runningEvent.Reset();
                processHost = null;
                process     = null;
                references  = 0;
            }
        }
        internal protected override void OnExecute(IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            ProjectConfiguration conf = (ProjectConfiguration)GetConfiguration(configuration);

            monitor.Log.WriteLine(GettextCatalog.GetString("Running {0} ...", FileName));

            IConsole console = conf.ExternalConsole
                                ? context.ExternalConsoleFactory.CreateConsole(!conf.PauseConsoleOutput)
                                : context.ConsoleFactory.CreateConsole(!conf.PauseConsoleOutput);

            AggregatedOperationMonitor aggregatedOperationMonitor = new AggregatedOperationMonitor(monitor);

            try {
                try {
                    ExecutionCommand executionCommand = CreateExecutionCommand(configuration, conf);

                    if (!context.ExecutionHandler.CanExecute(executionCommand))
                    {
                        monitor.ReportError(GettextCatalog.GetString("Can not execute \"{0}\". The selected execution mode is not supported for .NET projects.", FileName), null);
                        return;
                    }

                    IProcessAsyncOperation asyncOp = context.ExecutionHandler.Execute(executionCommand, console);
                    aggregatedOperationMonitor.AddOperation(asyncOp);
                    asyncOp.WaitForCompleted();

                    monitor.Log.WriteLine(GettextCatalog.GetString("The application exited with code: {0}", asyncOp.ExitCode));
                } finally {
                    console.Dispose();
                    aggregatedOperationMonitor.Dispose();
                }
            } catch (Exception ex) {
                monitor.ReportError(GettextCatalog.GetString("Cannot execute \"{0}\"", FileName), ex);
            }
        }
示例#5
0
        bool VerifyKeyInfo()
        {
            bool success = false;
            var  output  = new StringWriter();
            IProcessAsyncOperation proc = null;

            try {
                proc = MonoDroidFramework.Toolbox.VerifyKeypair(signingOptions, output, output);
                proc.WaitForCompleted();
                success = proc.Success;
            } catch {
            } finally {
                if (proc != null)
                {
                    proc.Dispose();
                }
            }

            if (success)
            {
                return(true);
            }

            Ide.MessageService.ShowError("Verification failed", "Keystore verification failed:\n" + output);
            return(false);
        }
示例#6
0
        protected override bool OnBuild(IProgressMonitor monitor, DeployContext ctx)
        {
            string   consMsg;
            IConsole cons;

            if (ExternalConsole)
            {
                cons    = ExternalConsoleFactory.Instance.CreateConsole(CloseConsoleWhenDone);
                consMsg = GettextCatalog.GetString("(in external terminal)");
            }
            else
            {
                cons    = new MonitorConsole(monitor);
                consMsg = "";
            }

            monitor.Log.WriteLine(GettextCatalog.GetString("Executing: {0} {1} {2}", Command, Arguments, consMsg));
            IProcessAsyncOperation process = Runtime.ProcessService.StartConsoleProcess(Command, Arguments, workingDirectory, cons, null);

            process.WaitForCompleted();

            if (cons is MonitorConsole)
            {
                ((MonitorConsole)cons).Dispose();
            }
            return(true);
        }
示例#7
0
        void ProcessExited(IAsyncOperation oper)
        {
            lock (this) {
                Counters.ExternalHostProcesses--;

                // Remove all callbacks from existing objects
                foreach (object ob in remoteObjects)
                {
                    RemotingService.UnregisterMethodCallback(ob, "Dispose");
                }

                remoteObjects.Clear();

                exitedEvent.Set();
                if (oper != process)
                {
                    return;
                }

                // The process suddently died
                runningEvent.Reset();
                processHost = null;
                process     = null;
                references  = 0;
            }
        }
示例#8
0
 public ProcessMonitor(IConsole console, IProcessAsyncOperation operation, EventHandler exited)
 {
     this.exited              = exited;
     this.operation           = operation;
     this.console             = console;
     operation.Completed     += new OperationHandler(OnOperationCompleted);
     console.CancelRequested += new EventHandler(OnCancelRequest);
 }
示例#9
0
 public override void Dispose()
 {
     if (console != null && !console.IsCompleted)
     {
         console.Cancel();
         console = null;
     }
 }
示例#10
0
		public ProfilingContext (IProcessAsyncOperation asyncOperation, string filename)
		{
			if (asyncOperation == null)
				throw new ArgumentNullException ("asyncOperation");
			if (filename == null)
				throw new ArgumentNullException ("filename");
			
			this.asyncOperation = asyncOperation;
			this.filename = filename;
		}
 public ProcessAdapter(IProcessAsyncOperation oper, string name)
 {
     this.oper       = oper;
     this.name       = name;
     oper.Completed += delegate {
         if (Exited != null)
         {
             Exited(this, EventArgs.Empty);
         }
     };
 }
示例#12
0
        protected override void DoExecute(IProgressMonitor monitor,
                                          ExecutionContext context,
                                          ConfigurationSelector configuration)
        {
            PythonConfiguration config;
            IConsole            console;

            config = (PythonConfiguration)GetConfiguration(configuration);

            // Make sure we have a module to execute
            if (config.Runtime == null || String.IsNullOrEmpty(config.Module))
            {
                MessageService.ShowMessage("No target module specified!");
                return;
            }

            monitor.Log.WriteLine("Running project...");

            // Create a console, external if needed
            if (config.ExternalConsole)
            {
                console = context.ExternalConsoleFactory.CreateConsole(!config.PauseConsoleOutput);
            }
            else
            {
                console = context.ConsoleFactory.CreateConsole(!config.PauseConsoleOutput);
            }

            AggregatedOperationMonitor operationMonitor = new AggregatedOperationMonitor(monitor);

            try {
                PythonExecutionCommand cmd = new PythonExecutionCommand(config);

                if (!context.ExecutionHandler.CanExecute(cmd))
                {
                    monitor.ReportError("The selected execution mode is not supported for Python projects.", null);
                    return;
                }

                IProcessAsyncOperation op = context.ExecutionHandler.Execute(cmd, console);
                operationMonitor.AddOperation(op);
                op.WaitForCompleted();

                monitor.Log.WriteLine("The operation exited with code: {0}", op.ExitCode);
            }
            catch (Exception ex) {
                monitor.ReportError("Cannot execute \"" + config.Runtime.Path + "\"", ex);
            }
            finally {
                operationMonitor.Dispose();
                console.Dispose();
            }
        }
示例#13
0
        protected override void DoExecute(IProgressMonitor monitor,
                                          ExecutionContext context)
        {
            CProjectConfiguration conf = (CProjectConfiguration)ActiveConfiguration;
            string   command           = conf.Output;
            string   args     = conf.CommandLineParameters;
            string   dir      = Path.GetFullPath(conf.OutputDirectory);
            string   platform = "Native";
            bool     pause    = conf.PauseConsoleOutput;
            IConsole console;

            if (conf.CompileTarget != CBinding.CompileTarget.Bin)
            {
                IdeApp.Services.MessageService.ShowMessage("Compile target is not an executable!");
                return;
            }

            monitor.Log.WriteLine("Running project...");

            if (conf.ExternalConsole)
            {
                console = context.ExternalConsoleFactory.CreateConsole(!pause);
            }
            else
            {
                console = context.ConsoleFactory.CreateConsole(!pause);
            }

            AggregatedOperationMonitor operationMonitor = new AggregatedOperationMonitor(monitor);

            try {
                IExecutionHandler handler = context.ExecutionHandlerFactory.CreateExecutionHandler(platform);

                if (handler == null)
                {
                    monitor.ReportError("Cannot execute \"" + command + "\". The selected execution mode is not supported in the " + platform + " platform.", null);
                    return;
                }

                IProcessAsyncOperation op = handler.Execute(Path.Combine(dir, command), args, dir, console);

                operationMonitor.AddOperation(op);
                op.WaitForCompleted();

                monitor.Log.WriteLine("The operation exited with code: {0}", op.ExitCode);
            } catch (Exception ex) {
                monitor.ReportError("Cannot execute \"" + command + "\"", ex);
            } finally {
                operationMonitor.Dispose();
                console.Dispose();
            }
        }
示例#14
0
        public void Start()
        {
            lock (this)
            {
                if (starting)
                {
                    return;
                }
                starting = true;
                exitRequestEvent.Reset();

                RemotingService.RegisterRemotingChannel();

                BinaryFormatter bf   = new BinaryFormatter();
                ObjRef          oref = RemotingServices.Marshal(this);
                MemoryStream    ms   = new MemoryStream();
                bf.Serialize(ms, oref);
                string sref    = Convert.ToBase64String(ms.ToArray());
                string tmpFile = null;

                if (executionHandlerFactory == null)
                {
                    executionHandlerFactory = Runtime.SystemAssemblyService.CurrentRuntime.GetExecutionHandler();
                }

                try {
                    string location = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                    location = Path.Combine(location, "mdhost.exe");

                    ProcessHostConsole cons = new ProcessHostConsole();
                    tmpFile = Path.GetTempFileName();
                    File.WriteAllText(tmpFile, sref + "\n" + Process.GetCurrentProcess().Id + "\n");
                    string arguments           = string.Format("{0} \"{1}\"", id, tmpFile);
                    DotNetExecutionCommand cmd = new DotNetExecutionCommand(location, arguments, AppDomain.CurrentDomain.BaseDirectory);
                    cmd.DebugMode = isDebugMode;
                    process       = executionHandlerFactory.Execute(cmd, cons);
                    Counters.ExternalHostProcesses++;

                    process.Completed += ProcessExited;
                } catch (Exception ex) {
                    if (tmpFile != null)
                    {
                        try {
                            File.Delete(tmpFile);
                        } catch {
                        }
                    }
                    LoggingService.LogError(ex.ToString());
                    throw;
                }
            }
        }
示例#15
0
        public override void Dispose()
        {
            if (console != null && !console.IsCompleted)
            {
                console.Cancel();
                console = null;
            }

            if (thread != null)
            {
                thread.Abort();
            }
        }
示例#16
0
        protected override void DoExecute(IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            CProjectConfiguration conf = (CProjectConfiguration)GetConfiguration(configuration);
            bool     pause             = conf.PauseConsoleOutput;
            IConsole console;

            if (conf.CompileTarget != CBinding.CompileTarget.Bin)
            {
                MessageService.ShowMessage("Compile target is not an executable!");
                return;
            }

            monitor.Log.WriteLine("Running project...");

            if (conf.ExternalConsole)
            {
                console = context.ExternalConsoleFactory.CreateConsole(!pause);
            }
            else
            {
                console = context.ConsoleFactory.CreateConsole(!pause);
            }

            AggregatedOperationMonitor operationMonitor = new AggregatedOperationMonitor(monitor);

            try
            {
                ExecutionCommand cmd = CreateExecutionCommand(conf);
                if (!context.ExecutionHandler.CanExecute(cmd))
                {
                    monitor.ReportError("Cannot execute \"" + conf.Output + "\". The selected execution mode is not supported for C projects.", null);
                    return;
                }

                IProcessAsyncOperation op = context.ExecutionHandler.Execute(cmd, console);

                operationMonitor.AddOperation(op);
                op.WaitForCompleted();

                monitor.Log.WriteLine("The operation exited with code: {0}", op.ExitCode);
            }
            catch (Exception ex)
            {
                monitor.ReportError("Cannot execute \"" + conf.Output + "\"", ex);
            }
            finally
            {
                operationMonitor.Dispose();
                console.Dispose();
            }
        }
        public ProfilingContext(IProcessAsyncOperation asyncOperation, string filename)
        {
            if (asyncOperation == null)
            {
                throw new ArgumentNullException("asyncOperation");
            }
            if (filename == null)
            {
                throw new ArgumentNullException("filename");
            }

            this.asyncOperation = asyncOperation;
            this.filename       = filename;
        }
        public static void Run(HaxeProject project, HaxeProjectConfiguration configuration, IProgressMonitor monitor, ExecutionContext context)
        {
            ExecutionCommand cmd = CreateExecutionCommand(project, configuration);

            if (cmd is HaxeExecutionCommand)
            {
                IConsole console;
                if (configuration.ExternalConsole)
                {
                    console = context.ExternalConsoleFactory.CreateConsole(false);
                }
                else
                {
                    console = context.ConsoleFactory.CreateConsole(false);
                }

                AggregatedOperationMonitor operationMonitor = new AggregatedOperationMonitor(monitor);

                try
                {
                    if (!context.ExecutionHandler.CanExecute(cmd))
                    {
                        monitor.ReportError(String.Format("Cannot execute '{0}'.", cmd.Target), null);
                        return;
                    }

                    IProcessAsyncOperation operation = context.ExecutionHandler.Execute(cmd, console);

                    operationMonitor.AddOperation(operation);
                    operation.WaitForCompleted();

                    monitor.Log.WriteLine("Player exited with code {0}.", operation.ExitCode);
                }
                catch (Exception)
                {
                    monitor.ReportError(String.Format("Error while executing '{0}'.", cmd.Target), null);
                }
                finally
                {
                    operationMonitor.Dispose();
                    console.Dispose();
                }
            }
            //else
            //{
            //	Process.Start (cmd);
            //}
        }
		public override IProcessAsyncOperation Execute (ExecutionCommand command, IConsole console)
		{
			DotNetExecutionCommand dotcmd = (DotNetExecutionCommand) command;
			
			string tempFile = Path.GetTempFileName ();
			string snapshotFile = profiler.GetSnapshotFileName (dotcmd.Command, tempFile);
			
			string args = string.Format ("--profile={2}:{3} --debug \"{0}\" {1}", dotcmd.Command, dotcmd.Arguments, profiler.Identifier, tempFile);
			NativeExecutionCommand cmd = new NativeExecutionCommand ("mono", args, dotcmd.WorkingDirectory, dotcmd.EnvironmentVariables);
			
			IProcessAsyncOperation pao = base.Execute (cmd, console);
			
			ProfilingService.ActiveProfiler = profiler;
			ProfilingContext profContext = new ProfilingContext (pao, snapshotFile);
			profiler.Start (profContext);
			return pao;
		}
		protected override void OnRun (DebuggerStartInfo startInfo)
		{
			var dsi = (MonoDroidDebuggerStartInfo) startInfo;
			var cmd = dsi.ExecutionCommand;
			
			string monoOptions = string.Format ("debug={0}:{1}:{2}", dsi.Address, dsi.DebugPort, dsi.OutputPort);
			process = MonoDroidFramework.Toolbox.StartActivity (cmd.Device, cmd.Activity, monoOptions,
				ProcessOutput, ProcessError);
			
			process.Completed += delegate {
				process = null;
			};
			
			TargetExited += delegate {
				EndProcess ();
			};
			
			StartListening (dsi);
		}
            void EndProcess()
            {
                if (process == null)
                {
                    return;
                }

                var p = process;

                process = null;

                if (usingExternalConsole || p.IsCompleted)
                {
                    return;
                }

                try {
                    p.Cancel();
                } catch {}
            }
示例#22
0
        void WaitTimeout(object sender, System.Timers.ElapsedEventArgs args)
        {
            try {
                IProcessAsyncOperation oldProcess;

                lock (this) {
                    if (references > 0)
                    {
                        stopping = false;
                        return;
                    }

                    uint waited = (uint)(DateTime.Now - lastReleaseTime).TotalMilliseconds;
                    if (waited < stopDelay)
                    {
                        timer.Interval = stopDelay - waited;
                        timer.Enabled  = true;
                        return;
                    }

                    runningEvent.Reset();
                    exitedEvent.Reset();
                    exitRequestEvent.Set();
                    oldProcess  = process;
                    processHost = null;
                    process     = null;
                    stopping    = false;
                }

                if (!exitedEvent.WaitOne(shutdownTimeout, false))
                {
                    try {
                        oldProcess.Cancel();
                    } catch {
                    }
                }
            } catch (Exception ex) {
                LoggingService.LogError(ex.ToString());
            }
        }
示例#23
0
        protected override void DoExecute(IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            if (!CurrentExecutionTargetIsCoreClr(context.ExecutionTarget))
            {
                base.DoExecute(monitor, context, configuration);
                return;
            }

            var config = GetConfiguration(configuration) as DotNetProjectConfiguration;

            monitor.Log.WriteLine(GettextCatalog.GetString("Running {0} ...", Name));

            IConsole console = CreateConsole(config, context);
            var      aggregatedOperationMonitor = new AggregatedOperationMonitor(monitor);

            try {
                try {
                    ExecutionCommand executionCommand = CreateExecutionCommand(configuration, config);
                    if (context.ExecutionTarget != null)
                    {
                        executionCommand.Target = context.ExecutionTarget;
                    }

                    IProcessAsyncOperation asyncOp = Execute(executionCommand, console);
                    aggregatedOperationMonitor.AddOperation(asyncOp);
                    asyncOp.WaitForCompleted();

                    monitor.Log.WriteLine(GettextCatalog.GetString("The application exited with code: {0}", asyncOp.ExitCode));
                } finally {
                    console.Dispose();
                    aggregatedOperationMonitor.Dispose();
                }
            } catch (Exception ex) {
                LoggingService.LogError(string.Format("Cannot execute \"{0}\"", Name), ex);
                monitor.ReportError(GettextCatalog.GetString("Cannot execute \"{0}\"", Name), ex);
            }
        }
示例#24
0
 public AdbOutputOperation(IProcessAsyncOperation process, StringWriter output)
 {
     this.process = process;
     this.output  = output;
 }
示例#25
0
 public StartAvdOperation(IProcessAsyncOperation process, StringWriter error)
 {
     this.process = process;
     this.error   = error;
 }
示例#26
0
 public InstallPackageOperation(IProcessAsyncOperation process, StringWriter error)
 {
     this.process = process;
     this.error   = error;
 }
示例#27
0
			public StartAvdOperation (IProcessAsyncOperation process, StringWriter error)
			{
				this.process = process;
				this.error = error;
			}
示例#28
0
        protected override void Run()
        {
            var proj = DefaultUploadToDeviceHandler.GetActiveExecutableIPhoneProject();
            var conf = (IPhoneProjectConfiguration)proj.GetConfiguration(IdeApp.Workspace.ActiveConfiguration);

            IdeApp.ProjectOperations.Build(proj).Completed += delegate(IAsyncOperation op) {
                if (!op.Success)
                {
                    MessageService.ShowError(
                        GettextCatalog.GetString("Cannot zip app bundle"),
                        GettextCatalog.GetString("Project did not build successfully"));
                    return;
                }

                var dlg = new MonoDevelop.Components.SelectFileDialog(
                    GettextCatalog.GetString("Save zipped app bundle"), Gtk.FileChooserAction.Save);
                dlg.InitialFileName = string.Format("{0}-{1}.zip", conf.CompiledOutputName.FileNameWithoutExtension, proj.BundleVersion);
                dlg.DefaultFilter   = dlg.AddFilter("Zip file", "*.zip");

                if (!dlg.Run())
                {
                    return;
                }

                var zipFile = dlg.SelectedFile;
                var builder = new ProcessArgumentBuilder();
                builder.Add("-r", "-y");
                builder.AddQuoted(zipFile);
                builder.AddQuoted(conf.AppDirectory.FileName);
                var cmd = builder.ToString();
                var workingDirectory = conf.AppDirectory.ParentDirectory;

                new System.Threading.Thread(delegate() {
                    IProgressMonitor monitor         = null;
                    AggregatedOperationMonitor opMon = null;
                    IProcessAsyncOperation procOp    = null;

                    try {
                        monitor = IdeApp.Workbench.ProgressMonitors.GetOutputProgressMonitor(
                            GettextCatalog.GetString("Zip App Bundle"), MonoDevelop.Ide.Gui.Stock.RunProgramIcon, true, true);
                        monitor.BeginTask(GettextCatalog.GetString("Zipping app bundle"), 0);

                        var console = (IConsole)monitor;
                        console.Log.WriteLine("zip " + cmd);

                        //don't use StartConsoleProcess, it disposes the pad
                        procOp = Runtime.ProcessService.StartProcess(
                            "zip", cmd, workingDirectory, console.Out, console.Error, null);
                        opMon = new AggregatedOperationMonitor(monitor, procOp);

                        procOp.WaitForCompleted();

                        monitor.EndTask();

                        if (procOp.ExitCode != 0)
                        {
                            monitor.ReportError(GettextCatalog.GetString("Failed to zip app"), null);
                        }
                        else
                        {
                            monitor.ReportSuccess(GettextCatalog.GetString("Saved zipped app to '{0}'", zipFile));
                        }
                    } catch (Exception ex) {
                        LoggingService.LogError("Error in app zipper", ex);
                        //be super-safe, crashing thread crashes whole app
                        try {
                            monitor.ReportError("App zipping failed", ex);
                        } catch {}
                    }
                    if (opMon != null)
                    {
                        opMon.Dispose();
                    }
                    if (procOp != null)
                    {
                        procOp.Dispose();
                    }
                    if (monitor != null)
                    {
                        monitor.Dispose();
                    }
                }).Start();
            };
        }
示例#29
0
        public void Execute(IProgressMonitor monitor, IWorkspaceObject entry, ExecutionContext context,
                            ConfigurationSelector configuration)
        {
            ProcessExecutionCommand cmd = CreateExecutionCommand(entry, configuration);

            monitor.Log.WriteLine(GettextCatalog.GetString("Executing: {0} {1}", cmd.Command, cmd.Arguments));

            if (!Directory.Exists(cmd.WorkingDirectory))
            {
                monitor.ReportError(GettextCatalog.GetString("Custom command working directory does not exist"), null);
                return;
            }

            AggregatedOperationMonitor aggMon = null;
            IProcessAsyncOperation     oper   = null;
            IConsole console = null;

            try {
                if (context != null)
                {
                    if (externalConsole)
                    {
                        console = context.ExternalConsoleFactory.CreateConsole(!pauseExternalConsole);
                    }
                    else
                    {
                        console = context.ConsoleFactory.CreateConsole(!pauseExternalConsole);
                    }
                    oper = context.ExecutionHandler.Execute(cmd, console);
                }
                else
                {
                    if (externalConsole)
                    {
                        console = ExternalConsoleFactory.Instance.CreateConsole(!pauseExternalConsole);
                        oper    = Runtime.ProcessService.StartConsoleProcess(cmd.Command, cmd.Arguments,
                                                                             cmd.WorkingDirectory, console, null);
                    }
                    else
                    {
                        oper = Runtime.ProcessService.StartProcess(cmd.Command, cmd.Arguments,
                                                                   cmd.WorkingDirectory, monitor.Log, monitor.Log, null, false);
                    }
                }
                aggMon = new AggregatedOperationMonitor(monitor, oper);
                oper.WaitForCompleted();
                if (!oper.Success)
                {
                    monitor.ReportError("Custom command failed (exit code: " + oper.ExitCode + ")", null);
                }
            } catch (Win32Exception w32ex) {
                monitor.ReportError(GettextCatalog.GetString("Failed to execute custom command '{0}': {1}",
                                                             cmd.Command, w32ex.Message), null);
                return;
            } catch (Exception ex) {
                LoggingService.LogError("Command execution failed", ex);
                throw new UserException(GettextCatalog.GetString("Command execution failed: {0}", ex.Message));
            } finally {
                if (oper == null || !oper.Success)
                {
                    monitor.AsyncOperation.Cancel();
                }
                if (oper != null)
                {
                    oper.Dispose();
                }
                if (console != null)
                {
                    console.Dispose();
                }
                if (aggMon != null)
                {
                    aggMon.Dispose();
                }
            }
        }
示例#30
0
		public void Start (IList<string> userAssemblyPaths = null)
		{
			lock (this) {
				if (starting)
					return;
				starting = true;
				exitRequestEvent.Reset ();

				RemotingService.RegisterRemotingChannel ();

				BinaryFormatter bf = new BinaryFormatter ();
				ObjRef oref = RemotingServices.Marshal (this);
				MemoryStream ms = new MemoryStream ();
				bf.Serialize (ms, oref);
				string sref = Convert.ToBase64String (ms.ToArray ());
				string tmpFile = null;

				if (executionHandlerFactory == null)
					executionHandlerFactory = Runtime.SystemAssemblyService.CurrentRuntime.GetExecutionHandler ();

				try {
					string location = Path.GetDirectoryName (System.Reflection.Assembly.GetExecutingAssembly ().Location);
					location = Path.Combine (location, "mdhost.exe");

					tmpFile = Path.GetTempFileName ();
					StreamWriter sw = new StreamWriter (tmpFile);
					sw.WriteLine (sref);
					sw.WriteLine (Process.GetCurrentProcess ().Id);
					sw.WriteLine (Runtime.SystemAssemblyService.CurrentRuntime.RuntimeId);

					// Explicitly load Mono.Addins since the target runtime may not have it installed
					sw.WriteLine (2);
					sw.WriteLine (typeof(AddinManager).Assembly.Location);
					sw.WriteLine (typeof(Mono.Addins.Setup.SetupService).Assembly.Location);
					sw.Close ();

					string arguments = string.Format ("{0} \"{1}\"", id, tmpFile);
					DotNetExecutionCommand cmd = new DotNetExecutionCommand (location, arguments, AppDomain.CurrentDomain.BaseDirectory);
					if (userAssemblyPaths != null)
						cmd.UserAssemblyPaths = userAssemblyPaths;
					cmd.DebugMode = isDebugMode;
					ProcessHostConsole cons = new ProcessHostConsole ();
					process = executionHandlerFactory.Execute (cmd, cons);
					Counters.ExternalHostProcesses++;

					process.Completed += ProcessExited;

				} catch (Exception ex) {
					if (tmpFile != null) {
						try {
							File.Delete (tmpFile);
						} catch {
						}
					}
					LoggingService.LogError (ex.ToString ());
					throw;
				}
			}
		}
示例#31
0
		void WaitTimeout (object sender, System.Timers.ElapsedEventArgs args)
		{
			try {
				IProcessAsyncOperation oldProcess;
				
				lock (this) {
					if (references > 0) {
						stopping = false;
						return;
					}
	
					uint waited = (uint) (DateTime.Now - lastReleaseTime).TotalMilliseconds;
					if (waited < stopDelay) {
						timer.Interval = stopDelay - waited;
						timer.Enabled = true;
						return;
					}
				
					runningEvent.Reset ();
					exitedEvent.Reset ();
					exitRequestEvent.Set ();
					oldProcess = process;
					processHost = null;
					process = null;
					stopping = false;
				}
	
				if (!exitedEvent.WaitOne (shutdownTimeout, false)) {
					try {
						oldProcess.Cancel ();
					} catch {
					}
				}
			} catch (Exception ex) {
				LoggingService.LogError (ex.ToString ());
			}
		}
示例#32
0
		void ProcessExited (IAsyncOperation oper)
		{
			lock (this) {

				Counters.ExternalHostProcesses--;
				
				// Remove all callbacks from existing objects
				foreach (object ob in remoteObjects)
					RemotingService.UnregisterMethodCallback (ob, "Dispose");
				
				remoteObjects.Clear ();
				
				exitedEvent.Set ();
				
				// If the remote process crashes, a thread may be left hung in WaitForExit. This will awaken it.
				exitRequestEvent.Set ();
				
				if (oper != process) return;

				// The process suddently died
				runningEvent.Reset ();
				processHost = null;
				process = null;
				references = 0;
			}
		}
示例#33
0
		protected override void OnRun (DebuggerStartInfo startInfo)
		{
			lock (gdbLock) {
				// Create a script to be run in a terminal
				string script = Path.GetTempFileName ();
				string ttyfile = Path.GetTempFileName ();
				string ttyfileDone = ttyfile + "_done";
				string tty;
				
				try {
					File.WriteAllText (script, "tty > " + ttyfile + "\ntouch " + ttyfileDone + "\nsleep 10000d");
					Mono.Unix.Native.Syscall.chmod (script, FilePermissions.ALLPERMS);
					
					console = Runtime.ProcessService.StartConsoleProcess (script, "", ".", ExternalConsoleFactory.Instance.CreateConsole (true), null);
					DateTime tim = DateTime.Now;
					while (!File.Exists (ttyfileDone)) {
						System.Threading.Thread.Sleep (100);
						if ((DateTime.Now - tim).TotalSeconds > 10)
							throw new InvalidOperationException ("Console could not be created.");
					}
					tty = File.ReadAllText (ttyfile).Trim (' ','\n');
				} finally {
					try {
						if (File.Exists (script))
							File.Delete (script);
						if (File.Exists (ttyfile))
							File.Delete (ttyfile);
						if (File.Exists (ttyfileDone))
							File.Delete (ttyfileDone);
					} catch {
						// Ignore
					}
				}
				
				StartGdb ();
				
				// Initialize the terminal
				RunCommand ("-inferior-tty-set", Escape (tty));
				
				try {
					RunCommand ("-file-exec-and-symbols", Escape (startInfo.Command));
				} catch {
					FireTargetEvent (TargetEventType.TargetExited, null);
					throw;
				}

				RunCommand ("-environment-cd", Escape (startInfo.WorkingDirectory));
				
				// Set inferior arguments
				if (!string.IsNullOrEmpty (startInfo.Arguments))
					RunCommand ("-exec-arguments", startInfo.Arguments);
				
				currentProcessName = startInfo.Command + " " + startInfo.Arguments;
				
				CheckIsMonoProcess ();
				OnStarted ();
				
				RunCommand ("-exec-run");
			}
		}
		public void Start ()
		{
			lock (this)
			{
				if (starting) return;
				starting = true;
				exitRequestEvent.Reset ();
				
				RemotingService.RegisterRemotingChannel ();
				
				BinaryFormatter bf = new BinaryFormatter ();
				ObjRef oref = RemotingServices.Marshal (this);
				MemoryStream ms = new MemoryStream ();
				bf.Serialize (ms, oref);
				string sref = Convert.ToBase64String (ms.ToArray ());
				string tmpFile = null;

				if (executionHandlerFactory == null)
					executionHandlerFactory = Runtime.SystemAssemblyService.CurrentRuntime.GetExecutionHandler ();

				try {
					string location = Path.GetDirectoryName (System.Reflection.Assembly.GetExecutingAssembly ().Location);
					location = Path.Combine (location, "mdhost.exe");
					
					ProcessHostConsole cons = new ProcessHostConsole ();
					tmpFile = Path.GetTempFileName ();
					File.WriteAllText (tmpFile, sref + "\n" + Process.GetCurrentProcess ().Id + "\n");
					string arguments = string.Format("{0} \"{1}\"", id, tmpFile);
					DotNetExecutionCommand cmd = new DotNetExecutionCommand(location, arguments, AppDomain.CurrentDomain.BaseDirectory);
					cmd.DebugMode = isDebugMode;
					process = executionHandlerFactory.Execute (cmd, cons);
					Counters.ExternalHostProcesses++;
					
					process.Completed += ProcessExited;
					
				} catch (Exception ex) {
					if (tmpFile != null) {
						try {
							File.Delete (tmpFile);
						} catch {
						}
					}
					LoggingService.LogError (ex.ToString ());
					throw;
				}
			}
		}
示例#35
0
        protected override void OnRun(DebuggerStartInfo startInfo)
        {
            lock (gdbLock) {
                // Create a script to be run in a terminal
                string script      = Path.GetTempFileName();
                string ttyfile     = Path.GetTempFileName();
                string ttyfileDone = ttyfile + "_done";
                string tty;

                try {
                    File.WriteAllText(script, "tty > " + ttyfile + "\ntouch " + ttyfileDone + "\nsleep 10000d");
                    Mono.Unix.Native.Syscall.chmod(script, FilePermissions.ALLPERMS);

                    console = Runtime.ProcessService.StartConsoleProcess(script, "", ".", ExternalConsoleFactory.Instance.CreateConsole(true), null);
                    DateTime tim = DateTime.Now;
                    while (!File.Exists(ttyfileDone))
                    {
                        System.Threading.Thread.Sleep(100);
                        if ((DateTime.Now - tim).TotalSeconds > 10)
                        {
                            throw new InvalidOperationException("Console could not be created.");
                        }
                    }
                    tty = File.ReadAllText(ttyfile).Trim(' ', '\n');
                } finally {
                    try {
                        if (File.Exists(script))
                        {
                            File.Delete(script);
                        }
                        if (File.Exists(ttyfile))
                        {
                            File.Delete(ttyfile);
                        }
                        if (File.Exists(ttyfileDone))
                        {
                            File.Delete(ttyfileDone);
                        }
                    } catch {
                        // Ignore
                    }
                }

                StartGdb();

                // Initialize the terminal
                RunCommand("-inferior-tty-set", Escape(tty));

                try {
                    RunCommand("-file-exec-and-symbols", Escape(startInfo.Command));
                } catch {
                    FireTargetEvent(TargetEventType.TargetExited, null);
                    throw;
                }

                RunCommand("-environment-cd", Escape(startInfo.WorkingDirectory));

                // Set inferior arguments
                if (!string.IsNullOrEmpty(startInfo.Arguments))
                {
                    RunCommand("-exec-arguments", startInfo.Arguments);
                }

                currentProcessName = startInfo.Command + " " + startInfo.Arguments;

                CheckIsMonoProcess();
                OnStarted();

                RunCommand("-exec-run");
            }
        }
示例#36
0
        public void Start(IList <string> userAssemblyPaths = null)
        {
            lock (this) {
                if (starting)
                {
                    return;
                }
                starting = true;
                exitRequestEvent.Reset();

                RemotingService.RegisterRemotingChannel();

                BinaryFormatter bf   = new BinaryFormatter();
                ObjRef          oref = RemotingServices.Marshal(this);
                MemoryStream    ms   = new MemoryStream();
                bf.Serialize(ms, oref);
                string sref    = Convert.ToBase64String(ms.ToArray());
                string tmpFile = null;

                if (executionHandlerFactory == null)
                {
                    executionHandlerFactory = Runtime.SystemAssemblyService.CurrentRuntime.GetExecutionHandler();
                }

                try {
                    string location = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                    location = Path.Combine(location, "mdhost.exe");

                    tmpFile = Path.GetTempFileName();
                    StreamWriter sw = new StreamWriter(tmpFile);
                    sw.WriteLine(sref);
                    sw.WriteLine(Process.GetCurrentProcess().Id);
                    sw.WriteLine(Runtime.SystemAssemblyService.CurrentRuntime.RuntimeId);

                    // Explicitly load Mono.Addins since the target runtime may not have it installed
                    sw.WriteLine(2);
                    sw.WriteLine(typeof(AddinManager).Assembly.Location);
                    sw.WriteLine(typeof(Mono.Addins.Setup.SetupService).Assembly.Location);
                    sw.Close();

                    string arguments           = string.Format("{0} \"{1}\"", id, tmpFile);
                    DotNetExecutionCommand cmd = new DotNetExecutionCommand(location, arguments, AppDomain.CurrentDomain.BaseDirectory);
                    if (userAssemblyPaths != null)
                    {
                        cmd.UserAssemblyPaths = userAssemblyPaths;
                    }
                    cmd.DebugMode = isDebugMode;
                    ProcessHostConsole cons = new ProcessHostConsole();
                    process = executionHandlerFactory.Execute(cmd, cons);
                    Counters.ExternalHostProcesses++;

                    process.Completed += ProcessExited;
                } catch (Exception ex) {
                    if (tmpFile != null)
                    {
                        try {
                            File.Delete(tmpFile);
                        } catch {
                        }
                    }
                    LoggingService.LogError(ex.ToString());
                    throw;
                }
            }
        }
示例#37
0
			public GetDateOperation (IProcessAsyncOperation process, StringWriter output) : base (process, output)
			{
			}
示例#38
0
 public override void Dispose()
 {
     if (console != null && !console.IsCompleted) {
         console.Cancel ();
         console = null;
     }
 }
示例#39
0
        protected override void DoExecute(IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            if (!CheckCanExecute(configuration))
            {
                return;
            }

            var      config  = (LuaConfiguration)GetConfiguration(configuration);
            IConsole console = config.ExternalConsole ?
                               context.ExternalConsoleFactory.CreateConsole(!config.PauseConsoleOutput) :
                               context.ConsoleFactory.CreateConsole(!config.PauseConsoleOutput);

            var aggregatedMonitor = new AggregatedOperationMonitor(monitor);

            try {
                string param;

                if (config.LangVersion != LangVersion.Love)
                {
                    param = string.Format("\"{0}\" {1}", config.MainFile, config.CommandLineParameters);
                }
                else
                {
                    param = string.Format("\"{0}\" {1}", ItemDirectory, config.CommandLineParameters);
                }

                IProcessAsyncOperation op =
                    Runtime.ProcessService.StartConsoleProcess(GetLuaPath(config),
                                                               param, (config.LangVersion != LangVersion.Love) ? BaseDirectory : ItemDirectory,
                                                               config.EnvironmentVariables, console, null);

                monitor.CancelRequested += delegate {
                    op.Cancel();
                };

                aggregatedMonitor.AddOperation(op);
                op.WaitForCompleted();
                monitor.Log.WriteLine("The application exited with code: " + op.ExitCode);

                /*
                 * var executionCommand = //CreateExecutionCommand( configuration, config );
                 *      new NativeExecutionCommand( GetLuaPath( config.LangVersion ),
                 *                                 config.CommandLineParameters,
                 *                                 BaseDirectory );
                 *
                 *
                 * if( !context.ExecutionHandler.CanExecute( executionCommand ) )
                 * {
                 *      monitor.ReportError( GettextCatalog.GetString( "Cannot execute application. The selected execution mode " +
                 *      "is not supported for Lua projects" ), null );
                 *      return;
                 * }
                 *
                 * IProcessAsyncOperation asyncOp = context.ExecutionHandler.Execute( executionCommand, console );
                 * aggregatedMonitor.AddOperation( asyncOp );
                 * asyncOp.WaitForCompleted();
                 *
                 * monitor.Log.WriteLine( "The application exited with code: " + asyncOp.ExitCode );
                 */
            } catch (Exception exc) {
                monitor.ReportError(GettextCatalog.GetString("Cannot execute \"{0}\"", config.MainFile), exc);
            } finally {
                console.Dispose();
                aggregatedMonitor.Dispose();
            }
        }
		void ProcessExited (IAsyncOperation oper)
		{
			lock (this) {

				Counters.ExternalHostProcesses--;
				
				// Remove all callbacks from existing objects
				foreach (object ob in remoteObjects)
					RemotingService.UnregisterMethodCallback (ob, "Dispose");
				
				remoteObjects.Clear ();
				
				exitedEvent.Set ();
				if (oper != process) return;

				// The process suddently died
				runningEvent.Reset ();
				processHost = null;
				process = null;
				references = 0;
			}
		}
示例#41
0
		public ProcessMonitor (IConsole console, IProcessAsyncOperation operation, EventHandler exited)
		{
			this.exited = exited;
			this.operation = operation;
			this.console = console;
			operation.Completed += new OperationHandler (OnOperationCompleted);
			console.CancelRequested += new EventHandler (OnCancelRequest);
		}
示例#42
0
			public AdbOutputOperation (IProcessAsyncOperation process, StringWriter output)
			{
				this.process = process;
				this.output = output;
			}
示例#43
0
			public InstallPackageOperation (IProcessAsyncOperation process, StringWriter error)
			{
				this.process = process;
				this.error = error;
			}
示例#44
0
        /// <summary>Executes a build command, writing output to the monitor.</summary>
        /// <returns>Whether the command executed successfully.</returns>
        /// <param name='monitor'>Progress monitor for writing output and handling cancellation.</param>
        /// <param name='startInfo'>Process start info. Redirection will be enabled if necessary.</param>
        /// <param name='stdout'>Text writer for stdout. May be null.</param>
        /// <param name='stderr'>Text writer for stderr. May be null.</param>
        public static int ExecuteBuildCommand(IProgressMonitor monitor, ProcessStartInfo startInfo,
                                              TextWriter stdout, TextWriter stderr)
        {
            monitor.Log.WriteLine(startInfo.FileName + " " + startInfo.Arguments);

            startInfo.UseShellExecute        = false;
            startInfo.RedirectStandardError  = true;
            startInfo.RedirectStandardOutput = true;

            int exitCode = -1;

            TextWriter    outWriter = monitor.Log, errWriter = monitor.Log;
            LogTextWriter chainedOut = null, chainedErr = null;

            if (stdout != null)
            {
                chainedOut = new LogTextWriter();
                chainedOut.ChainWriter(outWriter);
                chainedOut.ChainWriter(stdout);
                outWriter = chainedOut;
            }

            if (stderr != null)
            {
                chainedErr = new LogTextWriter();
                chainedErr.ChainWriter(errWriter);
                chainedErr.ChainWriter(stderr);
                errWriter = chainedErr;
            }

            var operationMonitor = new AggregatedOperationMonitor(monitor);

            IProcessAsyncOperation p = null;

            try {
                p = Runtime.ProcessService.StartProcess(startInfo, outWriter, errWriter, null);
                operationMonitor.AddOperation(p);                  //handles cancellation
                p.WaitForCompleted();
                exitCode = p.ExitCode;
            } finally {
                if (chainedErr != null)
                {
                    chainedErr.Dispose();
                }
                if (chainedOut != null)
                {
                    chainedOut.Dispose();
                }
                if (p != null)
                {
                    p.Dispose();
                }
                operationMonitor.Dispose();
            }

            if (exitCode != 0)
            {
                monitor.Log.WriteLine("{0} exited with code {1}", Path.GetFileName(startInfo.FileName), exitCode);
            }

            return(exitCode);
        }
		public ProcessAdapter (IProcessAsyncOperation oper, string name)
		{
			this.oper = oper;
			this.name = name;
			oper.Completed += delegate {
				if (Exited != null)
					Exited (this, EventArgs.Empty);
			};
		}
示例#46
0
		public override void Dispose ()
		{
			if (console != null && !console.IsCompleted) {
				console.Cancel ();
				console = null;
			}
				
			if (thread != null)
				thread.Abort ();
		}