Exemple #1
0
        public void build(string arguments)
        {
            System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
            pProcess.StartInfo.FileName = variables.pathforit + @"\xeBuild\xeBuild.exe";

            if (variables.debugme)
            {
                Console.WriteLine(variables.pathforit);
            }
            if (variables.debugme)
            {
                Console.WriteLine("---" + variables.pathforit + @"\xeBuild\xeBuild.exe");
            }
            if (variables.debugme)
            {
                Console.WriteLine(arguments);
            }
            pProcess.StartInfo.Arguments              = arguments;
            pProcess.StartInfo.UseShellExecute        = false;
            pProcess.StartInfo.WorkingDirectory       = variables.pathforit;
            pProcess.StartInfo.RedirectStandardInput  = true;
            pProcess.StartInfo.RedirectStandardOutput = true;
            pProcess.StartInfo.CreateNoWindow         = true;
            pProcess.Exited += new EventHandler(xeExit);
            //pProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(DataReceived);
            //pProcess.Exited += new EventHandler(xe_Exited);
            //pProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);
            try
            {
                AutoResetEvent outputWaitHandle = new AutoResetEvent(false);
                pProcess.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        Console.WriteLine(e.Data);
                        if (e.Data != null && e.Data.Contains("image built"))
                        {
                            variables.xefinished = true;
                        }
                    }
                };
                pProcess.Start();
                pProcess.BeginOutputReadLine();
                pProcess.StandardInput.WriteLine("enter");
                pProcess.WaitForExit();

                if (pProcess.HasExited)
                {
                    pProcess.CancelOutputRead();
                }
            }
            catch (Exception objException)
            {
                Console.WriteLine(objException.Message);
            }
        }
Exemple #2
0
        private void stopThread(BackgroundWorker t)
        {
            if (t != null)
            {
                t.CancelAsync();

                if (pro != null)
                {
                    pro.CancelOutputRead();
                    pro.Close();
                    pro = null;
                }
            }
        }
Exemple #3
0
 /// <summary>
 /// Manually call this method to abort all workings.
 /// </summary>
 private void ProcAbort()
 {
     // return value is useless when force aborted
     proc.CancelOutputRead();
     // exit process should be omitted too
     proc.Exited -= new EventHandler(ProcExit);
     // terminate threads
     killProcTree(proc.Id);
     // reset taskbar progress
     if (win7supported)
     {
         TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress);
     }
     // Print abort message to log
     Print(Environment.NewLine + "Work is aborted by user.");
 }
Exemple #4
0
 public void Dispose()
 {
     if (null != process)
     {
         if (!hasExited && !_wasKilled)
         {
             Util.KillProcessAndChildren(this.process.Id);
             _wasKilled = true;
         }
         try { process.CancelOutputRead(); } catch { }
         try { process.CancelErrorRead(); } catch { }
         try { process.OutputDataReceived -= Process_OutputDataReceived; } catch { }
         try { process.ErrorDataReceived -= Process_ErrorDataReceived; } catch { }
         try { process.Exited -= Process_Exited; } catch { }
     }
     process = null;
 }
        private void Cleanup(bool requested)
        {
            // TODO: Read and log messages written to STDERR, for cases where, for example, the VM exits with errors before the stitch script is executed
            //var contents = _process.StandardError.ReadToEnd();
            if (_process != null && !_process.HasExited)
            {
                _process.CancelErrorRead();
                _process.CancelOutputRead();
                _process.Kill();
                _process = null;
            }

            _channel.Dispose();
            _channel = null;

            _observer.StitchStateChanged(_stitchInstance.Id, false, requested);
        }
        public static string Exec(String command)
        {
            Console.WriteLine("command : " + command);
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/c " + command;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;

            p.Start();

            var stdout = new StringBuilder();
            var stderr = new StringBuilder();
            p.OutputDataReceived += (sender, e) => {
                if (e.Data != null) {
                    stdout.AppendLine(e.Data);
                }
            };
            p.ErrorDataReceived += (sendar, e) => {
                if (e.Data != null) {
                    stderr.AppendLine(e.Data);
                }
            };
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            var output = new StringBuilder();
            var isTimeOut = false;
            if (!p.WaitForExit(3000)) {
                isTimeOut = true;
                p.Kill();
            }
            p.CancelOutputRead();
            p.CancelErrorRead();
            output.Append(stdout.ToString());
            output.Append(stderr.ToString());
            if (isTimeOut) {
                output.Append("TIMEOUT.");
            }
            return output.ToString();
        }
Exemple #7
0
        /// <summary>
        /// Get the user name
        /// </summary>
        /// <remarks>
        /// This is a hack until the time
        /// .NET core flushes out the Enviroment
        /// namespace with proper username information.
        /// "whoami" command should work on linux/mac/windows
        /// although it would be proper to use "id -un"
        /// at this point in time.
        /// </remarks>
        /// <returns></returns>
        public static string GetUserName()
        {
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.FileName = "whoami";
            // redirect standard in, not using currently
            startInfo.RedirectStandardOutput = true;
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo = startInfo;

            // setup and allow an event
            process.EnableRaisingEvents = true;
            // for building output from standard out
            StringBuilder outputBuilder = new StringBuilder();

            // add event handling for process
            process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler
                                          (
                delegate(object sender, System.Diagnostics.DataReceivedEventArgs e)
            {
                // append the output data to a string
                outputBuilder.Append(e.Data);
            }
                                          );
            try
            {
                // start
                process.Start();
                // read is async
                process.BeginOutputReadLine();
                // wait for user process to end
                process.WaitForExit();
                process.CancelOutputRead();
            }
            catch (Exception e)
            {
                var error = e.ToString();
                Console.WriteLine(error);
                outputBuilder.Clear();
                outputBuilder.Append("Unknown");
            }

            return(outputBuilder.ToString());
        }
Exemple #8
0
 /// <summary>
 /// Manually call this method to abort all workings.
 /// </summary>
 private void ProcAbort()
 {
     // return value is useless when force aborted
     proc.CancelOutputRead();
     // exit process should be omitted too
     proc.Exited -= new EventHandler(ProcExit);
     // terminate threads
     killProcTree(proc.Id);
     if (win7supported)
     {
         // turn progressbar red
         NativeMethods.PostMessage(progressBarX264.Handle, NativeMethods.Win32CommCtrlMsgs.PBM_SETSTATE,
                                   new UIntPtr((uint)NativeMethods.ProgressBarState.PBST_ERROR), new IntPtr(0));
         // reset taskbar progress
         taskbarProgress.SetProgressState(this.Handle, TBPFLAG.TBPF_NOPROGRESS);
     }
     // Print abort message to log
     Print(Environment.NewLine + "Work is aborted by user.");
     // Disable abort button
     buttonAbort.Enabled = false;
 }
        static public void CompilerDll(string _filename, string _args)
        {
            try
            {
                System.Diagnostics.Process tprocess = new System.Diagnostics.Process();
                tprocess.StartInfo.FileName  = _filename;
                tprocess.StartInfo.Arguments = _args;

                tprocess.StartInfo.RedirectStandardOutput = true;
                tprocess.BeginOutputReadLine();
                tprocess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(SortOutputHandler);
                tprocess.Start();

                tprocess.WaitForExit();
                tprocess.CancelOutputRead();
                tprocess.Close();
            }
            catch (System.Exception ex)
            {
                DLog.LogError(ex.Message);
            }
        }
Exemple #10
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                return;
            }

            var cmd = string.Join(" ", args);

            var procStartInfo = new System.Diagnostics.ProcessStartInfo();

            procStartInfo.FileName               = "cmd.exe";
            procStartInfo.Arguments              = "/C " + cmd;
            procStartInfo.UseShellExecute        = false;
            procStartInfo.RedirectStandardError  = true;
            procStartInfo.RedirectStandardInput  = true;
            procStartInfo.RedirectStandardOutput = true;

            var process = new System.Diagnostics.Process();

            process.StartInfo           = procStartInfo;
            process.OutputDataReceived += (sender, dataReceivedArgs) => Console.WriteLine(dataReceivedArgs.Data);
            process.ErrorDataReceived  += (sender, dataReceivedArgs) => Console.WriteLine(dataReceivedArgs.Data);

            QueryPerfCounter timer = new QueryPerfCounter();

            timer.Start();
            {
                process.Start();
                process.BeginOutputReadLine();
                process.WaitForExit();
                process.CancelOutputRead();
            }
            timer.Stop();

            Console.WriteLine("Time elapsed: {0} ms", timer.Duration().ToString("F"));
        }
Exemple #11
0
        public static RunResult RunWaiting(string fileName, string arguments = null, string workingDirectory = "")
        {
            var res = new RunResult();
            var p   = new System.Diagnostics.Process
            {
                StartInfo = new System.Diagnostics.ProcessStartInfo
                {
                    WorkingDirectory       = workingDirectory,
                    FileName               = System.IO.Path.Combine(workingDirectory, fileName),
                    Arguments              = arguments,
                    UseShellExecute        = false,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                    CreateNoWindow         = true,
                }
            };

            p.OutputDataReceived += (s, a) => { if (a.Data == null)
                                                {
                                                    return;
                                                }
                                                res.Output.Add(a.Data); };
            p.ErrorDataReceived += (s, a) => { if (a.Data == null)
                                               {
                                                   return;
                                               }
                                               res.Error.Add(a.Data); };
            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            p.WaitForExit();
            p.CancelOutputRead();
            p.CancelErrorRead();
            res.Success = p.ExitCode == 0;
            return(res);
        }
        /// <summary>
        /// Asynchronously starts the child process.
        /// </summary>
        /// <returns>The return code returned from the process.</returns>
        public void Start()
        {
            // Initialize the process and its StartInfo properties.
            using (System.Diagnostics.Process process = new System.Diagnostics.Process())
            {
                _process = process;
                process.StartInfo.FileName  = _filename;
                process.StartInfo.Arguments = _arguments;
                // Set UseShellExecute to false for redirection.
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow  = true;
                process.StartInfo.LoadUserProfile = false;

                // redirect the standard input of the command
                process.StartInfo.RedirectStandardInput = true;

                // Redirect the standard output of the command.
                // This stream is read asynchronously using an event handler.
                process.StartInfo.RedirectStandardOutput = true;
                process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(NetOutputDataHandler);

                // Redirect the error output of the command.
                process.StartInfo.RedirectStandardError = true;
                process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(NetErrorDataHandler);

                // mark the last message receive time
                _lastMessageReceiveTime = System.DateTime.UtcNow.Ticks;

                WorkerPool.Default.RunAsync(() =>
                {
                    bool stop = false;
                    while (!stop && !_abort)
                    {
                        try
                        {
                            // Start the process.
                            process.Start();

                            bool outputConnectionFailed = false;
                            bool errorConnectionFailed  = false;
                            try
                            {
                                // Start the asynchronous read of the standard output stream.
                                process.BeginOutputReadLine();
                            }
                            catch (Exception e)
                            {
                                // ignore all exceptions here--it may be that the process just exited too fast to perform these operations
                                System.Diagnostics.Debug.WriteLine("Error starting process output read: " + e.ToString());
                                outputConnectionFailed = true;
                            }
                            try
                            {
                                // Start the asynchronous read of the standard error stream.
                                process.BeginErrorReadLine();
                            }
                            catch (Exception e)
                            {
                                // ignore all exceptions here--it may be that the process just exited too fast to perform these operations
                                System.Diagnostics.Debug.WriteLine("Error starting process error read: " + e.ToString());
                                errorConnectionFailed = true;
                            }

                            try
                            {
                                // set the process priority so it doesn't consume all the foreground CPU!
                                process.PriorityClass = _priority;
                            }
                            catch (Exception e)
                            {
                                // ignore all exceptions here--it may be that the process just exited too fast to perform these operations
                                System.Diagnostics.Debug.WriteLine("Error changing process priority: " + e.ToString());
                            }
                            // output connection failed?
                            if (outputConnectionFailed)
                            {
                                // try to read synchronously
                                try
                                {
                                    string output = process.StandardOutput.ReadToEnd();
                                    OutputDataHandler(output);
                                }
                                catch
                                {
                                    // ignore errors because this shouldn't work anyway, but might in rare cases where the process was so fast that it finished before we could begin doing async reads
                                }
                            }
                            // error connection failed?
                            if (errorConnectionFailed)
                            {
                                // try to read synchronously
                                try
                                {
                                    string output = process.StandardError.ReadToEnd();
                                    ErrorDataHandler(output);
                                }
                                catch
                                {
                                    // ignore errors because this shouldn't work anyway, but might in rare cases where the process was so fast that it finished before we could begin doing async reads
                                }
                            }
                            // wait until the timeout elapses, make sure we fully process async output if we exited properly
                            if (process.WaitForExit(_timeoutMilliseconds))
                            {
                                process.WaitForExit();
                            }
                            else     // timed out
                            {
                                // kill the process
                                process.Kill();
                                // return the timeout code
                                _returnCode = System.Int32.MinValue;
                                return;
                            }
                            // wait until it's been at least 100 ms since the last message was received
                            while ((System.DateTime.UtcNow - new DateTime(_lastMessageReceiveTime)).TotalMilliseconds < 100)
                            {
                                System.Threading.Thread.Sleep(100);
                            }
                            // get the process exit code
                            _returnCode = process.ExitCode;
                        }
                        finally
                        {
                            // close the process
                            process.Close();
                        }
                    }
                    // cancel the reads now
                    try { process.CancelErrorRead(); } catch { }
                    try { process.CancelOutputRead(); } catch { }
                });
            }
        }
Exemple #13
0
        public void update()
        {
            System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
            pProcess.StartInfo.FileName = variables.pathforit + @"\xeBuild\xeBuild.exe";
            string arguments = "update ";

            foreach (String patch in _patches)
            {
                arguments += " " + patch;
            }
            if (variables.debugme)
            {
                arguments += " -v";
            }
            if (_noava)
            {
                arguments += " -noava";
            }
            if (_nowrite)
            {
                arguments += " -nowrite";
            }
            if (_clean)
            {
                arguments += " -clean";
            }
            if (_noreeb)
            {
                arguments += " -noreeb";
            }
            arguments += " -noenter";
            arguments += " -f " + _dash;
            arguments += " -d ";
            arguments += "\"" + variables.outfolder + "\"";

            RegexOptions options = RegexOptions.None;
            Regex        regex   = new Regex(@"[ ]{2,}", options);

            arguments = regex.Replace(arguments, @" ");

            if (variables.debugme)
            {
                Console.WriteLine(variables.pathforit);
            }
            if (variables.debugme)
            {
                Console.WriteLine("---" + variables.pathforit + @"\xeBuild\xeBuild.exe");
            }
            if (variables.debugme)
            {
                Console.WriteLine(arguments);
            }
            pProcess.StartInfo.Arguments              = arguments;
            pProcess.StartInfo.UseShellExecute        = false;
            pProcess.StartInfo.WorkingDirectory       = variables.pathforit;
            pProcess.StartInfo.RedirectStandardInput  = true;
            pProcess.StartInfo.RedirectStandardOutput = true;
            pProcess.StartInfo.CreateNoWindow         = true;
            pProcess.Exited += new EventHandler(xeExit);
            try
            {
                AutoResetEvent outputWaitHandle = new AutoResetEvent(false);
                pProcess.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        Console.WriteLine(e.Data);
                        if (e.Data != null && e.Data.Contains("image built"))
                        {
                            variables.xefinished = true;
                        }
                    }
                };
                pProcess.Start();
                pProcess.BeginOutputReadLine();
                pProcess.WaitForExit();

                if (pProcess.HasExited)
                {
                    pProcess.CancelOutputRead();
                }
            }
            catch (Exception objException)
            {
                Console.WriteLine(objException.Message);
            }
        }
Exemple #14
0
        public void client(string args)
        {
            System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
            pProcess.StartInfo.FileName = variables.pathforit + @"\xeBuild\xeBuild.exe";
            string arguments = "client ";

            arguments += args;
            if (variables.debugme)
            {
                arguments += " -v";
            }
            arguments += " -noenter";

            RegexOptions options = RegexOptions.None;
            Regex        regex   = new Regex(@"[ ]{2,}", options);

            arguments = regex.Replace(arguments, @" ");

            if (variables.debugme)
            {
                Console.WriteLine(variables.pathforit);
            }
            if (variables.debugme)
            {
                Console.WriteLine("---" + variables.pathforit + @"\xeBuild\xeBuild.exe");
            }
            if (variables.debugme)
            {
                Console.WriteLine(arguments);
            }
            pProcess.StartInfo.Arguments              = arguments;
            pProcess.StartInfo.UseShellExecute        = false;
            pProcess.StartInfo.WorkingDirectory       = variables.pathforit;
            pProcess.StartInfo.RedirectStandardInput  = true;
            pProcess.StartInfo.RedirectStandardOutput = true;
            pProcess.StartInfo.CreateNoWindow         = true;
            //pProcess.Exited += new EventHandler(xeExit);
            try
            {
                AutoResetEvent outputWaitHandle = new AutoResetEvent(false);
                pProcess.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        Console.WriteLine(e.Data);
                    }
                };
                pProcess.Start();
                pProcess.BeginOutputReadLine();
                pProcess.WaitForExit();

                if (pProcess.HasExited)
                {
                    pProcess.CancelOutputRead();
                }
            }
            catch (Exception objException)
            {
                Console.WriteLine(objException.Message);
            }
        }
Exemple #15
0
        /// <summary>
        /// Runs iwyu. Blocks until finished.
        /// </summary>
        static public string RunIncludeWhatYouUse(string fullFileName, EnvDTE.Project project, IncludeWhatYouUseOptionsPage settings)
        {
            string reasonForFailure;
            string preprocessorDefintions = VSUtils.VCUtils.GetCompilerSetting_PreprocessorDefinitions(project, out reasonForFailure);

            if (preprocessorDefintions == null)
            {
                Output.Instance.ErrorMsg("Can't run IWYU: {0}", reasonForFailure);
                return(null);
            }

            string output = "";

            using (var process = new System.Diagnostics.Process())
            {
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.FileName = settings.ExecutablePath;

                // Clang options
                // Disable all diagnostics
                var iwyuOptions = "-w ";
                // ... despite of that "invalid token paste" comes through a lot. Disable it.
                iwyuOptions += "-Wno-invalid-token-paste ";
                // Assume C++14
                // arguments += "-std=c++14 ";
                // MSVC specific. See https://clang.llvm.org/docs/UsersManual.html#microsoft-extensions
                iwyuOptions += "-fms-extensions -fms-compatibility -fdelayed-template-parsing ";
                iwyuOptions += $"-fmsc-version={VSUtils.GetMSCVerString()} ";
                // Architecture
                var targetMachine = VSUtils.VCUtils.GetLinkerSetting_TargetMachine(project, out reasonForFailure);
                if (!targetMachine.HasValue)
                {
                    Output.Instance.ErrorMsg("Failed to query for target machine: {0}", reasonForFailure);
                }
                else
                {
                    switch (targetMachine.Value)
                    {
                    // Most targets give an error of this form:
                    // "error: unknown target CPU 'x86'"
                    // It seems iwyu is only really fine with x86-64

                    /*case VCProjectUtils.Base.TargetMachineType.X86:
                     *  clangOptions += "-march=x86 ";
                     *  break;*/
                    case VCProjectUtils.Base.TargetMachineType.AMD64:
                        iwyuOptions += "-march=x86-64 ";
                        break;

                        /*case VCProjectUtils.Base.TargetMachineType.ARM:
                         *  clangOptions += "-march=arm ";
                         *  break;
                         * case VCProjectUtils.Base.TargetMachineType.MIPS:
                         *  clangOptions += "-march=mips ";
                         *  break;
                         * case VCProjectUtils.Base.TargetMachineType.THUMB:
                         *  clangOptions += "-march=thumb ";
                         *  break;*/
                    }
                }


                iwyuOptions += "-Xiwyu --verbose=" + settings.LogVerbosity + " ";
                if (settings.MappingFiles.Length == 0)
                {
                    settings.MappingFiles = new string[] { "stl.c.headers.imp", "msvc.imp", "boost-all.imp", "boost-all-private.imp" };
                }
                for (int i = 0; i < settings.MappingFiles.Length; ++i)
                {
                    iwyuOptions += "-Xiwyu --mapping_file=\"" + settings.MappingFiles[i] + "\" ";
                }
                if (settings.NoDefaultMappings)
                {
                    iwyuOptions += "-Xiwyu --no_default_mappings ";
                }
                if (settings.PCHInCode)
                {
                    iwyuOptions += "-Xiwyu --pch_in_code ";
                }
                switch (settings.PrefixHeaderIncludes)
                {
                case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Add:
                    iwyuOptions += "-Xiwyu --prefix_header_includes=add ";
                    break;

                case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Remove:
                    iwyuOptions += "-Xiwyu --prefix_header_includes=remove ";
                    break;

                case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Keep:
                    iwyuOptions += "-Xiwyu --prefix_header_includes=keep ";
                    break;
                }
                if (settings.TransitiveIncludesOnly)
                {
                    iwyuOptions += "-Xiwyu --transitive_includes_only ";
                }

                // Set max line length so something large so we don't loose comment information.
                // Documentation:
                // --max_line_length: maximum line length for includes. Note that this only affects comments and alignment thereof,
                // the maximum line length can still be exceeded with long file names(default: 80).
                iwyuOptions += "-Xiwyu --max_line_length=1024 ";

                // Include-paths and Preprocessor.
                var includeEntries = VSUtils.GetProjectIncludeDirectories(project, false);
                var includes       = includeEntries.Aggregate("", (current, inc) => current + ("-I \"" + Regex.Escape(inc) + "\" "));

                var defines = " -D " + string.Join(" -D", preprocessorDefintions.Split(';'));

                // write support file. Long argument lists lead to an error. Support files are the solution here.
                // https://github.com/Wumpf/IncludeToolbox/issues/36
                var supportFile    = Path.GetTempFileName();
                var supportContent = includes + " " + defines + " " + Regex.Escape(fullFileName);
                File.WriteAllText(supportFile, supportContent);

                process.StartInfo.Arguments = $"{iwyuOptions} {settings.AdditionalParameters} @{supportFile}";
                Output.Instance.Write("Running command '{0}' with following arguments:\n{1}\n\n", process.StartInfo.FileName, process.StartInfo.Arguments);

                // Start the child process.
                process.EnableRaisingEvents = true;
                process.OutputDataReceived += (s, args) =>
                {
                    Output.Instance.WriteLine(args.Data);
                    output += args.Data + "\n";
                };
                process.ErrorDataReceived += (s, args) =>
                {
                    Output.Instance.WriteLine(args.Data);
                    output += args.Data + "\n";
                };

                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                process.CancelOutputRead();
                process.CancelErrorRead();
            }
            output = Regex.Replace(output, @"#include <moduleworks_dummy.*?>.*?\n", "");

            return(output);
        }
Exemple #16
0
        /// <summary>
        /// Runs iwyu. Blocks until finished.
        /// </summary>
        static public string RunIncludeWhatYouUse(string fullFileName, EnvDTE.Project project, IncludeWhatYouUseOptionsPage settings)
        {
            string reasonForFailure;
            string preprocessorDefintions = VSUtils.VCUtils.GetCompilerSetting_PreprocessorDefinitions(project, out reasonForFailure);

            if (preprocessorDefintions == null)
            {
                Output.Instance.ErrorMsg("Can't run IWYU: {0}", reasonForFailure);
                return(null);
            }

            string output = "";

            using (var process = new System.Diagnostics.Process())
            {
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.FileName  = settings.ExecutablePath;
                process.StartInfo.Arguments = "";

                // Include-paths and Preprocessor.
                var includeEntries = VSUtils.GetProjectIncludeDirectories(project, false);
                process.StartInfo.Arguments = includeEntries.Aggregate("", (current, inc) => current + ("-I \"" + inc + "\" "));
                process.StartInfo.Arguments = preprocessorDefintions.
                                              Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).
                                              Aggregate(process.StartInfo.Arguments, (current, def) => current + ("-D" + def + " "));

                // Clang options
                // Disable all diagnostics
                process.StartInfo.Arguments += "-w ";
                // ... despite of that "invalid token paste" comes through a lot. Disable it.
                process.StartInfo.Arguments += "-Wno-invalid-token-paste ";
                // Assume C++14
                process.StartInfo.Arguments += "-std=c++14 ";
                // MSVC specific. See https://clang.llvm.org/docs/UsersManual.html#microsoft-extensions
                process.StartInfo.Arguments += "-fms-compatibility -fms-extensions -fdelayed-template-parsing ";
                process.StartInfo.Arguments += $"-fmsc-version={VSUtils.GetMSCVerString()} ";
                // Architecture
                var targetMachine = VSUtils.VCUtils.GetLinkerSetting_TargetMachine(project, out reasonForFailure);
                if (!targetMachine.HasValue)
                {
                    Output.Instance.ErrorMsg("Failed to query for target machine: {0}", reasonForFailure);
                }
                else
                {
                    switch (targetMachine.Value)
                    {
                    // Most targets give an error of this form:
                    // "error: unknown target CPU 'x86'"
                    // It seems iwyu is only really fine with x86-64

                    /*case VCProjectUtils.Base.TargetMachineType.X86:
                     *  process.StartInfo.Arguments += "-march=x86 ";
                     *  break;*/
                    case VCProjectUtils.Base.TargetMachineType.AMD64:
                        process.StartInfo.Arguments += "-march=x86-64 ";
                        break;

                        /*case VCProjectUtils.Base.TargetMachineType.ARM:
                         *  process.StartInfo.Arguments += "-march=arm ";
                         *  break;
                         * case VCProjectUtils.Base.TargetMachineType.MIPS:
                         *  process.StartInfo.Arguments += "-march=mips ";
                         *  break;
                         * case VCProjectUtils.Base.TargetMachineType.THUMB:
                         *  process.StartInfo.Arguments += "-march=thumb ";
                         *  break;*/
                    }
                }

                // icwyu options
                {
                    process.StartInfo.Arguments += "-Xiwyu --verbose=" + settings.LogVerbosity + " ";
                    for (int i = 0; i < settings.MappingFiles.Length; ++i)
                    {
                        process.StartInfo.Arguments += "-Xiwyu --mapping_file=\"" + settings.MappingFiles[i] + "\" ";
                    }
                    if (settings.NoDefaultMappings)
                    {
                        process.StartInfo.Arguments += "-Xiwyu --no_default_mappings ";
                    }
                    if (settings.PCHInCode)
                    {
                        process.StartInfo.Arguments += "-Xiwyu --pch_in_code ";
                    }
                    switch (settings.PrefixHeaderIncludes)
                    {
                    case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Add:
                        process.StartInfo.Arguments += "-Xiwyu --prefix_header_includes=add ";
                        break;

                    case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Remove:
                        process.StartInfo.Arguments += "-Xiwyu --prefix_header_includes=remove ";
                        break;

                    case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Keep:
                        process.StartInfo.Arguments += "-Xiwyu --prefix_header_includes=keep ";
                        break;
                    }
                    if (settings.TransitiveIncludesOnly)
                    {
                        process.StartInfo.Arguments += "-Xiwyu --transitive_includes_only ";
                    }

                    // Set max line length so something large so we don't loose comment information.
                    // Documentation:
                    // --max_line_length: maximum line length for includes. Note that this only affects comments and alignment thereof,
                    // the maximum line length can still be exceeded with long file names(default: 80).
                    process.StartInfo.Arguments += "-Xiwyu --max_line_length=1024 ";

                    // Custom stuff.
                    process.StartInfo.Arguments += settings.AdditionalParameters;
                    process.StartInfo.Arguments += " ";
                }


                // Finally, the file itself.
                process.StartInfo.Arguments += "\"";
                process.StartInfo.Arguments += fullFileName;
                process.StartInfo.Arguments += "\"";

                Output.Instance.Write("Running command '{0}' with following arguments:\n{1}\n\n", process.StartInfo.FileName, process.StartInfo.Arguments);

                // Start the child process.
                process.EnableRaisingEvents = true;
                process.OutputDataReceived += (s, args) =>
                {
                    Output.Instance.WriteLine(args.Data);
                    output += args.Data + "\n";
                };
                process.ErrorDataReceived += (s, args) =>
                {
                    Output.Instance.WriteLine(args.Data);
                    output += args.Data + "\n";
                };
                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                process.CancelOutputRead();
                process.CancelErrorRead();
            }

            return(output);
        }
Exemple #17
0
        private void buttonCook_Click(object sender, EventArgs e)
        {
            if (m_Cooking)
            {                   // User pressed abort
                m_Abort = true;
                return;
            }

            m_Cooking = true;                   // Prevent re-entrance!

            System.Diagnostics.Process P = processCook;

            // Invalidate input panel and ready cancel button
            panelInput.Enabled = false;
            buttonCook.Text    = "Cancel";
            richTextBoxOutput.Clear();

            try
            {
                FileInfo ApplicationFileName = new FileInfo(m_ExecutablePath);
                if (!ApplicationFileName.Exists)
                {
                    throw new Exception("Application Blacksparrow64.exe could not be found while looking at \"" + ApplicationFileName.FullName + "\"! Did you build it?");
                }

                P.StartInfo.FileName         = ApplicationFileName.FullName;
                P.StartInfo.Arguments        = GenerateCommandLine();
                P.StartInfo.WorkingDirectory = m_BasePath;
                P.StartInfo.WindowStyle      = System.Diagnostics.ProcessWindowStyle.Minimized;                 // Start minimized

                // Let's go !!
                P.Start();

                // Hook to outputs
                if (P.StartInfo.RedirectStandardOutput && !P.StartInfo.UseShellExecute)
                {
                    P.BeginErrorReadLine();
                    P.BeginOutputReadLine();
                }

                DateTime LastKeepAliveTime = DateTime.Now;
                while (!P.HasExited)
                {
                    if (m_Abort)
                    {
                        throw new AbortException();
                    }

                    // We met success!
                    if (m_ForceSuccess)
                    {
                        P.Kill();
                    }

//                  if ( (DateTime.Now - LastKeepAliveTime).TotalSeconds > KEEP_ALIVE_DELAY )
//                  {	// Send keep alive status
//                      LastKeepAliveTime = DateTime.Now;
//                      m_EndPoint.WriteStream( END_POINT_STATUS.KEEP_ALIVE, "Still alive !" );
//                  }

//					Thread.Sleep( 10 );	// Poll every 0.01 seconds...
                    Application.DoEvents();

//                  if ( !Focused )
//                      Focus();
                }

//              StartTime = P.StartTime;
//              EndTime = P.ExitTime;
//              ExitCode = (APPLICATION_RESULT_CODE) P.ExitCode;

                MessageBox("Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (AbortException)
            {
                P.Kill();
                MessageBox("Aborted!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception _e)
            {
                MessageBox("The rendering process generated an exception!\r\n\r\n" + _e, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (!P.HasExited)
                {
                    P.Kill();
                }

                // Unhook from outputs
                if (P.StartInfo.RedirectStandardOutput && !P.StartInfo.UseShellExecute)
                {
                    P.CancelErrorRead();
                    P.CancelOutputRead();
                }

//              P.Dispose();
            }

            // Restore input panel and cook button
            panelInput.Enabled = true;
            buttonCook.Text    = "Cook";

            // Restore cooking states
            m_Cooking = m_Abort = m_ForceSuccess = false;
        }
        public static Task <List <string> > GetGitVersionTags()
        {
            var    tcs         = new TaskCompletionSource <List <string> >();
            var    lines       = new List <string>();
            string errorString = string.Empty;

            try
            {
                var process = new System.Diagnostics.Process
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo
                    {
                        CreateNoWindow         = true,
                        RedirectStandardOutput = true,
                        RedirectStandardInput  = true,
                        RedirectStandardError  = true,
                        UseShellExecute        = false,
                        FileName  = "git",
                        Arguments = "tag --sort=creatordate --merged",
                    },
                    EnableRaisingEvents = true
                };
                process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(
                    delegate(object sender, System.Diagnostics.DataReceivedEventArgs e)
                {
                    if (string.IsNullOrWhiteSpace(e.Data))
                    {
                        return;
                    }
                    errorString += e.Data + "\n";
                }
                    );
                process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler
                                              (
                    delegate(object sender, System.Diagnostics.DataReceivedEventArgs e)
                {
                    if (string.IsNullOrEmpty(e.Data))
                    {
                        return;
                    }
                    var match = versionRegExp.Match(e.Data);
                    if (!match.Success)
                    {
                        return;
                    }
                    lines.Add(e.Data);
                }
                                              );
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.Exited += (sender, args) =>
                {
                    if (!string.IsNullOrEmpty(errorString))
                    {
                        tcs.SetException(new Exception(errorString));
                    }
                    else
                    {
                        tcs.SetResult(lines);
                    }
                    process.CancelOutputRead();
                    process.CancelErrorRead();
                    process.Dispose();
                };
            }
            catch (Exception e)
            {
                tcs.SetException(e);
            }
            return(tcs.Task);
        }
Exemple #19
0
        /// <summary>
        /// Runs iwyu. Blocks until finished.
        /// </summary>
        static public async Task <string> RunIncludeWhatYouUse(string fullFileName, EnvDTE.Project project, IncludeWhatYouUseOptionsPage settings)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            string preprocessorDefintions;

            try
            {
                preprocessorDefintions = VSUtils.VCUtils.GetCompilerSetting_PreprocessorDefinitions(project);
            }
            catch (VCQueryFailure e)
            {
                await Output.Instance.ErrorMsg("Can't run IWYU: {0}", e.Message);

                return(null);
            }

            string output = "";

            using (var process = new System.Diagnostics.Process())
            {
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.FileName = settings.ExecutablePath;

                // Clang options
                var clangOptionList = new List <string>();
                // Disable all diagnostics
                clangOptionList.Add("-w");
                // ... despite of that "invalid token paste" comes through a lot. Disable it.
                clangOptionList.Add("-Wno-invalid-token-paste");
                // Assume C++14
                clangOptionList.Add("-std=c++14");
                // MSVC specific. See https://clang.llvm.org/docs/UsersManual.html#microsoft-extensions
                clangOptionList.Add("-fms-compatibility -fms-extensions -fdelayed-template-parsing");
                clangOptionList.Add($"-fmsc-version={VSUtils.GetMSCVerString()}");
                // Architecture
                try
                {
                    switch (VSUtils.VCUtils.GetLinkerSetting_TargetMachine(project))
                    {
                    // Most targets give an error of this form:
                    // "error: unknown target CPU 'x86'"
                    // It seems iwyu is only really fine with x86-64

                    /*case VCProjectUtils.Base.TargetMachineType.X86:
                     *  clangOptions.Add("-march=x86");
                     *  break;*/
                    case VCHelper.TargetMachineType.AMD64:
                        clangOptionList.Add("-march=x86-64");
                        break;

                        /*case VCProjectUtils.Base.TargetMachineType.ARM:
                         *  clangOptions.Add("-march=arm");
                         *  break;
                         * case VCProjectUtils.Base.TargetMachineType.MIPS:
                         *  clangOptions.Add(""-march=mips");
                         *  break;
                         * case VCProjectUtils.Base.TargetMachineType.THUMB:
                         *  clangOptions.Add(""-march=thumb");
                         *  break;*/
                    }
                }
                catch (VCQueryFailure e)
                {
                    await Output.Instance.ErrorMsg($"Failed to query for target machine: {e.Message}");
                }

                // icwyu options
                var iwyuOptionList = new List <string>();
                iwyuOptionList.Add("--verbose=" + settings.LogVerbosity);
                for (int i = 0; i < settings.MappingFiles.Length; ++i)
                {
                    iwyuOptionList.Add("--mapping_file=\"" + settings.MappingFiles[i] + "\"");
                }
                if (settings.NoDefaultMappings)
                {
                    iwyuOptionList.Add("--no_default_mappings");
                }
                if (settings.PCHInCode)
                {
                    iwyuOptionList.Add("--pch_in_code");
                }
                switch (settings.PrefixHeaderIncludes)
                {
                case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Add:
                    iwyuOptionList.Add("--prefix_header_includes=add");
                    break;

                case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Remove:
                    iwyuOptionList.Add("--prefix_header_includes=remove");
                    break;

                case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Keep:
                    iwyuOptionList.Add("--prefix_header_includes=keep");
                    break;
                }
                if (settings.TransitiveIncludesOnly)
                {
                    iwyuOptionList.Add("--transitive_includes_only");
                }

                // Set max line length so something large so we don't loose comment information.
                // Documentation:
                // --max_line_length: maximum line length for includes. Note that this only affects comments and alignment thereof,
                // the maximum line length can still be exceeded with long file names(default: 80).
                iwyuOptionList.Add("--max_line_length=1024");

                /// write support file with includes, defines and the targetgile. Long argument lists lead to an error. Support files are the solution here.
                /// https://github.com/Wumpf/IncludeToolbox/issues/36
                // Include-paths and Preprocessor.
                var includes        = string.Join(" ", VSUtils.GetProjectIncludeDirectories(project, false).Select(x => "-I \"" + x.Replace("\\", "\\\\") + "\""));
                var defines         = string.Join(" ", preprocessorDefintions.Split(';').Select(x => "-D" + x));
                var filename        = "\"" + fullFileName.Replace("\\", "\\\\") + "\"";
                var supportFilePath = Path.GetTempFileName();
                File.WriteAllText(supportFilePath, includes + " " + defines + " " + filename);

                var clangOptions = string.Join(" ", clangOptionList);
                // each include-what-you-use parameter has an -Xiwyu prefix
                var iwyuOptions = string.Join(" ", iwyuOptionList.Select(x => " -Xiwyu " + x));
                process.StartInfo.Arguments = $"{clangOptions} {iwyuOptions} {settings.AdditionalParameters} \"@{supportFilePath}\"";

                Output.Instance.Write("Running command '{0}' with following arguments:\n{1}\n\n", process.StartInfo.FileName, process.StartInfo.Arguments);

                // Start the child process.
                process.EnableRaisingEvents = true;
                process.OutputDataReceived += (s, args) =>
                {
                    Output.Instance.WriteLine(args.Data);
                    output += args.Data + "\n";
                };
                process.ErrorDataReceived += (s, args) =>
                {
                    Output.Instance.WriteLine(args.Data);
                    output += args.Data + "\n";
                };
                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                process.CancelOutputRead();
                process.CancelErrorRead();
            }

            return(output);
        }
Exemple #20
0
        public AppFinder(Platform p)
        {
            platform = p;
            if (p == Platform.MacOS)
            {
                ValkyrieDebug.Log("Attempting to locate AppId " + AppId() + " on MacOS.");
                System.Diagnostics.ProcessStartInfo processStartInfo;
                System.Diagnostics.Process          process;

                StringBuilder outputBuilder = new StringBuilder();

                processStartInfo = new System.Diagnostics.ProcessStartInfo();
                processStartInfo.CreateNoWindow         = true;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.RedirectStandardInput  = true;
                processStartInfo.UseShellExecute        = false;
                processStartInfo.Arguments = "SPApplicationsDataType -xml";
                processStartInfo.FileName  = "system_profiler";

                process = new System.Diagnostics.Process();
                ValkyrieDebug.Log("Starting system_profiler.");
                process.StartInfo = processStartInfo;
                // enable raising events because Process does not raise events by default
                process.EnableRaisingEvents = true;
                // attach the event handler for OutputDataReceived before starting the process
                process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler
                                              (
                    delegate(object sender, System.Diagnostics.DataReceivedEventArgs e)
                {
                    // append the new data to the data already read-in
                    outputBuilder.Append(e.Data);
                }
                                              );
                // start the process
                // then begin asynchronously reading the output
                // then wait for the process to exit
                // then cancel asynchronously reading the output
                process.Start();
                process.BeginOutputReadLine();
                process.WaitForExit();
                process.CancelOutputRead();


                string output = outputBuilder.ToString();

                ValkyrieDebug.Log("Looking for: " + "/" + Executable());
                // Quick hack rather than doing XML properly
                int foundAt = output.IndexOf("/" + Executable());
                if (foundAt > 0)
                {
                    ValkyrieDebug.Log("Name Index: " + foundAt);
                    int startPos = output.LastIndexOf("<string>", foundAt) + 8;
                    ValkyrieDebug.Log("Start Index: " + startPos);
                    location = output.Substring(startPos, output.IndexOf("</string>", startPos) - startPos).Trim();
                    ValkyrieDebug.Log("Using location: " + location);
                }
            }
            else if (platform == Platform.Linux)
            {
            }
            else if (platform == Platform.Android)
            {
                location = Path.GetTempPath() + "Valkyrie/Obb/Assets/Bin/Data";
                if (Directory.Exists(Path.GetTempPath() + "Valkyrie/Obb"))
                {
                    Directory.Delete(Path.GetTempPath() + "Valkyrie/Obb", true);
                }
            }
            else
            {
                // Attempt to get steam install location (current 32/64 level)
                location = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App " + AppId(), "InstallLocation", "");
                if (location.Equals(""))
                {
                    // If we are on a 64 bit system, need to read the 64bit registry from a 32 bit app (Valkyrie)
                    try
                    {
                        location = RegistryWOW6432.GetRegKey64(RegHive.HKEY_LOCAL_MACHINE, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App " + AppId(), "InstallLocation");
                    }
                    catch (Exception) { }
                }
            }

            if (location == null || location.Length == 0)
            {
                string[] args = System.Environment.GetCommandLineArgs();
                for (int i = 0; i < (args.Length - 1); i++)
                {
                    if (args[i] == "-import")
                    {
                        location = args[i + 1];
                        if (location.Length > 0)
                        {
                            if (location[location.Length - 1] == '/' || location[location.Length - 1] == '\\')
                            {
                                location = location.Substring(0, location.Length - 1);
                            }
                        }
                        ValkyrieDebug.Log("Using import flag location: " + location);
                    }
                }
            }
            exeLocation += location + "/" + Executable();
            location    += DataDirectory();
            ValkyrieDebug.Log("Asset location: " + location);
        }
        public string RunIncludeWhatYouUse(string fullFileName, EnvDTE.Project project, IncludeWhatYouUseOptionsPage settings)
        {
            string reasonForFailure;
            string preprocessorDefintions = VSUtils.VCUtils.GetCompilerSetting_PreprocessorDefinitions(project, out reasonForFailure);

            if (preprocessorDefintions == null)
            {
                Output.Instance.ErrorMsg("Can't run IWYU: {0}", reasonForFailure);
                return(null);
            }

            string output = "";

            using (var process = new System.Diagnostics.Process())
            {
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.FileName  = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), "include-what-you-use.exe");
                process.StartInfo.Arguments = "";

                // Includes and Preprocessor.
                var includeEntries = VSUtils.GetProjectIncludeDirectories(project, false);
                process.StartInfo.Arguments = includeEntries.Aggregate("", (current, inc) => current + ("-I \"" + inc + "\" "));
                process.StartInfo.Arguments = preprocessorDefintions.
                                              Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).
                                              Aggregate(process.StartInfo.Arguments, (current, def) => current + ("-D" + def + " "));
                process.StartInfo.Arguments += " -DM_X64 -DM_AMD64 ";// TODO!!!

                // Clang options
                process.StartInfo.Arguments += "-w -x c++ -std=c++14 -fcxx-exceptions -fexceptions -fms-compatibility -fms-extensions -fmsc-version=1900 -ferror-limit=0 -Wno-invalid-token-paste "; // todo fmsc-version!
                // icwyu options
                {
                    process.StartInfo.Arguments += "-Xiwyu --verbose=" + settings.LogVerbosity + " ";
                    for (int i = 0; i < settings.MappingFiles.Length; ++i)
                    {
                        process.StartInfo.Arguments += "-Xiwyu --mapping_file=" + settings.MappingFiles[i] + " ";
                    }
                    if (settings.NoDefaultMappings)
                    {
                        process.StartInfo.Arguments += "-Xiwyu --no_default_mappings ";
                    }
                    if (settings.PCHInCode)
                    {
                        process.StartInfo.Arguments += "-Xiwyu --pch_in_code ";
                    }
                    switch (settings.PrefixHeaderIncludes)
                    {
                    case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Add:
                        process.StartInfo.Arguments += "-Xiwyu --prefix_header_includes=add ";
                        break;

                    case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Remove:
                        process.StartInfo.Arguments += "-Xiwyu --prefix_header_includes=remove ";
                        break;

                    case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Keep:
                        process.StartInfo.Arguments += "-Xiwyu --prefix_header_includes=keep ";
                        break;
                    }
                    if (settings.TransitiveIncludesOnly)
                    {
                        process.StartInfo.Arguments += "-Xiwyu --transitive_includes_only ";
                    }
                }


                // Finally, the file itself.
                process.StartInfo.Arguments += "\"";
                process.StartInfo.Arguments += fullFileName;
                process.StartInfo.Arguments += "\"";

                Output.Instance.Write("Running command '{0}' with following arguments:\n{1}\n\n", process.StartInfo.FileName, process.StartInfo.Arguments);

                // Start the child process.
                process.EnableRaisingEvents = true;
                process.OutputDataReceived += (s, args) =>
                {
                    Output.Instance.WriteLine(args.Data);
                    output += args.Data + "\n";
                };
                process.ErrorDataReceived += (s, args) =>
                {
                    Output.Instance.WriteLine(args.Data);
                    output += args.Data + "\n";
                };
                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                process.CancelOutputRead();
                process.CancelErrorRead();
            }

            return(output);
        }
Exemple #22
0
        /// <summary>
        /// Launch a job by creating a new process
        /// that user the loaders and executes the users dll
        /// </summary>
        public void LaunchJob()
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            // what is actually run is the dotnet process with
            // the loader application loading their dll which
            // is located in the StartNode directory since that is where
            // it was read in.
            // argumnets to donet run
            // redirect standard output so we can send it back
            // redirect standard in, not using currently
            System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo
            {
                FileName  = "dotnet",
                Arguments = System.Reflection.Assembly.GetEntryAssembly().Location + " load " + _job.FileName,
                RedirectStandardOutput = true,
                RedirectStandardInput  = true,
                // run in the loader directory
                WorkingDirectory = ".",
                CreateNoWindow   = true
            };
            // give it the arguments required to section up work
            processStartInfo.Arguments += " " + _job.JobId + "," + _job.SectionId + "," + _job.TotalNodes;

            // Add in the user arguments
            foreach (var arg in _job.UserArgs)
            {
                processStartInfo.Arguments += " " + arg;
            }

            //processStartInfo.UseShellExecute = false;
            // setup the process info
            process.StartInfo = processStartInfo;
            // setup and allow an event
            process.EnableRaisingEvents = true;
            // for building output from standard out
            var outputBuilder = new StringBuilder();

            // add event handling for process
            process.OutputDataReceived += delegate(object sender, System.Diagnostics.DataReceivedEventArgs e)
            {
                outputBuilder.Append(e.Data);
            };
            try
            {
                // start
                process.Start();
                // read is async
                process.BeginOutputReadLine();
                // wait for user process to end
                process.WaitForExit();
                process.CancelOutputRead();
            }
            // if there was an error with the loader process or building the loader
            // internal user exceptions will be caught by the loader programs
            catch (Exception e)
            {
                var error = e.ToString();
                Console.WriteLine(error);
            }
            _parent.Logger.Log("JobLauncher: Process finished with ExitCode: " + process.ExitCode);
            // use the output
            var output = outputBuilder.ToString();

            _parent.QueueDataEvent(new NodeComm("finished|"
                                                + _job.JobId + "|" + output));
        }