Exemple #1
0
        public string GuessGsdevice(string gs)
        {
            string gsdevice = "";
            var    enUS     = new System.Globalization.CultureInfo("en-US");

            // Ghostscriptのバージョンを取得する.
            using (var proc = new System.Diagnostics.Process()) {
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError  = true;
                proc.StartInfo.UseShellExecute        = false;
                proc.StartInfo.CreateNoWindow         = true;
                proc.StartInfo.FileName  = gs;
                proc.StartInfo.Arguments = "-v";
                //string errmsg = "";
                proc.ErrorDataReceived += ((s, e) => {});
                try {
                    proc.Start();
                    proc.BeginErrorReadLine();
                    string msg = proc.StandardOutput.ReadToEnd();
                    proc.WaitForExit(2000);
                    proc.CancelErrorRead();
                    if (!proc.HasExited)
                    {
                        proc.Kill();
                    }
                    var reg = new System.Text.RegularExpressions.Regex("Ghostscript ([0-9]+)\\.([0-9]+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    var m   = reg.Match(msg);
                    if (m.Success)
                    {
                        int major = int.Parse(m.Groups[1].Value, enUS);
                        int minor = int.Parse(m.Groups[2].Value, enUS);
                        //System.Diagnostics.Debug.WriteLine("major = " + major.ToString() + ", minor = " + minor.ToString());
                        // 9.15以上ならばeps2write,そうでないならepwsrite
                        if (major > 9 || (major == 9 && minor >= 15))
                        {
                            gsdevice = "eps2write";
                        }
                        else
                        {
                            gsdevice = "epswrite";
                        }
                    }
                }
                catch (System.InvalidOperationException) { }
                catch (System.FormatException) { }
                catch (System.ComponentModel.Win32Exception) { }
            }
            return(gsdevice);
        }
Exemple #2
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 #5
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);
        }
Exemple #6
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 #7
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 #8
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 #10
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);
        }
        /// <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 { }
                });
            }
        }
        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);
        }