GetProcessById() public static method

public static GetProcessById ( int processId ) : System.Diagnostics.Process
processId int
return System.Diagnostics.Process
Esempio n. 1
0
        /// <summary>
        /// Start experimental instance of Visual Studio. This will be killed on cleanup, except if a debugger is attached (in which case it can reuse the existing instance).
        /// </summary>
        private static (DTE, Process, bool) InitDTE()
        {
            bool    killVisualStudioProcessDuringTearDown;
            var     visualStudioPath = VSLocator.VisualStudioPath;
            Process process;

            // First, we try to check if an existing instance was launched
            var searcher            = new ManagementObjectSearcher($"select CommandLine,ProcessId from Win32_Process where ExecutablePath='{visualStudioPath.Replace(@"\", @"\\")}' and CommandLine like '% /RootSuffix Exp'");
            var retObjectCollection = searcher.Get();
            var result = retObjectCollection.Cast <ManagementObject>().FirstOrDefault();

            if (result != null)
            {
                var processId = (uint)result["ProcessId"];
                process = Process.GetProcessById((int)processId);
                killVisualStudioProcessDuringTearDown = false;
            }
            else
            {
                var psi = new ProcessStartInfo
                {
                    FileName         = visualStudioPath,
                    WorkingDirectory = Path.GetDirectoryName(visualStudioPath),
                    Arguments        = StartArguments,
                    UseShellExecute  = false,
                };

                // Override Xenko dir with path relative to test directory
                psi.EnvironmentVariables["XenkoDir"] = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..\..");

                process = Process.Start(psi);
                if (process == null)
                {
                    throw new InvalidOperationException("Could not start Visual Studio instance");
                }

                // Since we are the one starting it, let's close it when we are done
                // (except if a debugger is attached, we assume developer want to iterate several time on it and will exit Visual Studio himself)
                killVisualStudioProcessDuringTearDown = !Debugger.IsAttached;
            }

            // Wait for 60 sec
            for (int i = 0; i < 60; ++i)
            {
                if (process.HasExited)
                {
                    throw new InvalidOperationException($"Visual Studio process {process.Id} exited before we could connect to it");
                }

                var matchingDte = VisualStudioDTE.GetDTEByProcess(process.Id);
                if (matchingDte != null)
                {
                    return(matchingDte, process, killVisualStudioProcessDuringTearDown);
                }

                Thread.Sleep(1000);
            }

            throw new InvalidOperationException($"Could not find the Visual Studio DTE for process {process.Id}, or it didn't start in time");
        }
Esempio n. 2
0
        public static int ShutdownHandler(bool verbose)
        {
            // Update the system status.
            UpdateStatus(verbose);

            if (!bottleExistedAtStart)
            {
                Console.WriteLine("genie: no bottle exists.");
                return(EINVAL);
            }

            if (startedWithinBottle)
            {
                Console.WriteLine("genie: cannot shut down bottle from inside bottle; exiting.");
                return(EINVAL);
            }

            Rootify();

            if (verbose)
            {
                Console.WriteLine("genie: running systemctl poweroff within bottle");
            }

            var sd = Process.GetProcessById(systemdPid);

            // Call systemctl to trigger shutdown.
            Chain("nsenter",
                  String.Concat($"-t {systemdPid} -m -p systemctl poweroff"),
                  "running command failed; nsenter");

            if (verbose)
            {
                Console.WriteLine("genie: waiting for systemd to exit");
            }

            // Wait for systemd to exit (maximum 16 s).
            sd.WaitForExit(16000);

            if (updateHostname)
            {
                // Drop the in-bottle hostname.
                if (verbose)
                {
                    Console.WriteLine("genie: dropping in-bottle hostname");
                }

                Thread.Sleep(500);

                Chain("umount", "/etc/hostname");
                File.Delete("/run/hostname-wsl");

                Chain("hostname", "-F /etc/hostname");
            }

            Unrootify();

            return(0);
        }
        /// <summary>
        /// This function is the callback used to execute a command when the a menu item is clicked.
        /// See the Initialize method to see how the menu item is associated to this function using
        /// the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            var proj = DTE.ActiveDocument.ProjectItem.ContainingProject;

            DTE.Solution.SolutionBuild.BuildProject(DTE.Solution.SolutionBuild.ActiveConfiguration.Name,
                                                    proj.UniqueName, true);

            var outputPath = GetOutputPath(proj);

            if (!File.Exists(outputPath))
            {
                return;
            }
            var dir = Directory.GetParent(outputPath).ToString();

            if (processId.HasValue)
            {
                try
                {
                    var p = Process.GetProcessById(processId.Value);
                    p.CloseMainWindow();
                    p.WaitForExit(5000);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Failed to kill previous powershell process.");
                    Debug.WriteLine(ex);
                }
            }

            try
            {
                var p = new System.Diagnostics.Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName         = @"C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe",
                        WorkingDirectory = dir,
                        Arguments        = $"-NoExit -Command \"& {{Import-Module '{outputPath}'}}\""
                    }
                };
                p.Start();
                processId = p.Id;

                var dteProcess = DTE.Debugger.LocalProcesses.Cast <EnvDTE.Process>().FirstOrDefault(prop => prop.ProcessID == processId);

                if (dteProcess != null)
                {
                    dteProcess.Attach();
                    DTE.Debugger.CurrentProcess = dteProcess;
                }
            }
            catch (Exception ex)
            {
                ActivityLog.LogError("OpenForPSCmdlet", $@"Failed to launch powershell
{ex.Message}
{ex.StackTrace}");
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Retrieves Process from the current ReloadedProcess.
        /// </summary>
        /// <returns>Process class for the current Reloaded Process.</returns>
        public SystemProcess GetProcessFromReloadedProcess()
        {
            if (_localSystemProcess == null)
            {
                _localSystemProcess = SystemProcess.GetProcessById((int)ProcessId);
            }

            return(_localSystemProcess);
        }
        private static DTE GetDTE(int processId, Version version)
        {
            MessageFilter.Register();

            var    process    = Process.GetProcessById(processId);
            string progIdName = "VisualStudio";

            switch (process.MainModule.ModuleName.ToLowerInvariant())
            {
            case "wdexpress.exe":
                progIdName = "WDExpress";
                break;

            case "vwdexpress.exe":
                progIdName = "VWDExpress";
                break;
            }

            string progId        = string.Format("!{0}.DTE.{1}:{2}", progIdName, version, processId);
            object runningObject = null;

            IBindCtx            bindCtx      = null;
            IRunningObjectTable rot          = null;
            IEnumMoniker        enumMonikers = null;

            Marshal.ThrowExceptionForHR(CreateBindCtx(reserved: 0, ppbc: out bindCtx));
            bindCtx.GetRunningObjectTable(out rot);
            rot.EnumRunning(out enumMonikers);

            IMoniker[] moniker       = new IMoniker[1];
            uint       numberFetched = 0;

            while (enumMonikers.Next(1, moniker, out numberFetched) == 0)
            {
                IMoniker runningObjectMoniker = moniker[0];

                string name = null;

                try {
                    if (runningObjectMoniker != null)
                    {
                        runningObjectMoniker.GetDisplayName(bindCtx, null, out name);
                    }
                } catch (UnauthorizedAccessException) {
                    // Do nothing, there is something in the ROT that we do not have access to.
                }

                if (!string.IsNullOrEmpty(name) && string.Equals(name, progId, StringComparison.Ordinal))
                {
                    rot.GetObject(runningObjectMoniker, out runningObject);
                    break;
                }
            }

            return((DTE)runningObject);
        }
Esempio n. 6
0
        /// <summary></summary>
        /// <param name="p">Process form which to take visualt studio</param>
        /// <param name="vs">Visual Studio instance to be set.</param>
        /// <returns></returns>
        private static bool TryGetVsInstance(Process p, out _DTE vs)
        {
            if (p == null)
            {
                vs = null; return(false);
            }
            IntPtr numFetched = IntPtr.Zero;

            IMoniker[] monikers = new IMoniker[1];

            GetRunningObjectTable(0, out var rot);
            rot.EnumRunning(out var monikerEnumerator);
            monikerEnumerator.Reset();

            var names = new List <string>(10);
            int roPID = -1;             //running object process id

            while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
            {
                IBindCtx ctx;
                CreateBindCtx(0, out ctx);

                monikers[0].GetDisplayName(ctx, null, out var ron);                 //running object name
                names.Add(ron);

                rot.GetObject(monikers[0], out var ro);

                if (!(ro is _DTE) || !ron.StartsWith(VSName))
                {
                    continue;
                }
                roPID = int.Parse(ron.Split(':')[1]);
                if (roPID != p.Id)
                {
                    continue;
                }
                vs = (_DTE)ro; return(true);
            }
            vs = null;

            if (roPID >= 0)
            {
                WriteLine($@"No object instance named ""{VSName}"" was found on specifed process ""{p}"".");
                WriteLine($@"Last checked object with such name was running on ""{Process.GetProcessById(roPID)}"" process.");
            }
            else
            {
                WriteLine($@"Couldn't find Visual Studio instance named ""{VSName}"" running in ""{p}"" process.");
                WriteLine($@"Try setting {nameof(VSName)} variable to be start of one of fallowing names:");
                foreach (var n in names)
                {
                    WriteLine($"	{n}");
                }
            }
            return(false);
        }
Esempio n. 7
0
 private static Process GetProcessById(int processId)
 {
     try
     {
         return(Process.GetProcessById(processId));
     }
     catch (ArgumentException)
     {
         return(null);
     }
 }
Esempio n. 8
0
 /*
  *
  * Class for holding current process information.
  * ToDo: Need to save a pointer for adress of current process.
  *
  */
 public Process(IntPtr adress, String processTitle)
 {
     if (adress.Equals(IntPtr.Zero) || processTitle == "")
     {
         throw new Exception("Invalid arguments passed to constructor in class \"Process\"");
     }
     else
     {
         this.adress       = adress;
         this.processName  = IProcess.GetProcessById(getWindowProcessId(adress.ToInt32())).ProcessName;
         this.processTitle = processTitle;
     }
 }
 protected virtual void Dispose(bool disposing)
 {
     MessageFilter.Revoke();
     if (_killOnDispose)
     {
         try {
             Process.GetProcessById(_processId).Kill();
         } catch (ArgumentException) {
         } catch (InvalidOperationException) {
         } catch (Win32Exception) {
         }
     }
 }
 public static void HandleDoProcessKill(DoProcessKill command, Networking.Client client)
 {
     try
     {
         Process.GetProcessById(command.Pid).Kill();
     }
     catch
     {
     }
     finally
     {
         HandleGetProcesses(new GetProcesses(), client);
     }
 }
Esempio n. 11
0
        private static bool IsDisappearing()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var query = "SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = " + Process.GetCurrentProcess().Id;
                var mos   = new ManagementObjectSearcher(@"root\CIMV2", query);

                var processId   = (int)(uint)mos.Get().Cast <ManagementBaseObject>().First()["ParentProcessId"];
                var processName = Process.GetProcessById(processId).ProcessName;

                Console.WriteLine(processName);
                return(processName == "explorer");
            }

            return(true);
        }
Esempio n. 12
0
        /// <summary>
        /// Creates an instance of ReloadedProcess from a supplied process ID.
        /// </summary>
        /// <param name="processId">The process ID (PID) to create the Reloaded Process from.</param>
        public ReloadedProcess(uint processId)
        {
            // Set Process ID
            ProcessId = (IntPtr)processId;

            // Get Process Handle
            ProcessHandle = Native.Native.OpenProcess(Native.Native.PROCESS_ALL_ACCESS, false, (int)ProcessId);

            // Get C# Process by ID
            var process = SystemProcess.GetProcessById((int)processId);

            // Set thread id and handle to be that of first thread.
            ThreadId = (IntPtr)process.Threads[0].Id;

            // Set thread handle to be that of the first thread.
            ThreadHandle = OpenThread(THREAD_ALL_ACCESS, false, (int)ThreadId);
        }
Esempio n. 13
0
        /// <summary>
        /// Returns the window handle of the Vista start menu orb.
        /// </summary>
        /// <param name="taskBarWnd">windo handle of taskbar</param>
        /// <returns>window handle of start menu</returns>
        private static IntPtr GetVistaStartMenuWnd(IntPtr taskBarWnd)
        {
            // get process that owns the taskbar window
            int procId;

            GetWindowThreadProcessId(taskBarWnd, out procId);

            ProcessSD p = ProcessSD.GetProcessById(procId);

            if (p != null)
            {
                // enumerate all threads of that process...
                foreach (ProcessThread t in p.Threads)
                {
                    EnumThreadWindows(t.Id, MyEnumThreadWindowsProc, IntPtr.Zero);
                }
            }
            return(vistaStartMenuWnd);
        }
Esempio n. 14
0
        void ShowKestrelLog_OnClick(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
            var    service = GetServiceByTag(sender);
            var    pid     = service.ProcId;
            IntPtr mainWindowHandle;

            do
            {
                mainWindowHandle = Process.GetProcessById(pid).MainWindowHandle;
                var pr = ParentProcessUtilities.GetParentProcess(pid);
                pid = pr?.Id ?? 0;
            } while (mainWindowHandle == IntPtr.Zero && pid != 0);

            if (mainWindowHandle != IntPtr.Zero)
            {
                WindowApi.ShowWindow(mainWindowHandle);
            }
            else
            {
                MessageBox.Show("Last Kestrel process was attached to none console window style.\n So if you want to see Kestrel log window, please stop and start Microserice again.", "There is not kestrel window-habdle");
            }
        }
Esempio n. 15
0
        public static bool RunFastInjection(string executable, string arguments, string dll, string function)
        {
            uint pid;
            var  handle  = LaunchProcessSuspended(executable, arguments, 0, out pid);
            var  process = Process.GetProcessById((int)pid);

            if (!Inject(process, "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\SOS.dll"))
            {
                return(false);
            }
            if (!Inject(process, dll))
            {
                return(false);
            }

            //Thread.Sleep(500);
            //SuspendProcess(process);

            var success = CallExport(process, dll, function);

            ResumeProcess(process);

            return(success);
        }
Esempio n. 16
0
        private ProcessInfo GetProcessInfo()
        {
            Proc[] procs = new Proc[0];

            try
            {
                if (Pid.HasValue)
                {
                    procs = new Proc[] { Proc.GetProcessById(Pid.Value) }
                }
                ;
                else
                {
                    procs = Proc.GetProcessesByName(ProcessName);
                }

                var p = procs.FirstOrDefault();

                if (p != null)
                {
                    return(ProcessInfo.Instance.Snapshot(p));
                }
            }
            catch
            {
            }
            finally
            {
                foreach (var p in procs)
                {
                    p.Close();
                }
            }

            return(null);
        }
Esempio n. 17
0
        void TraceCore(TraceEventCache eventCache,
                       string source, TraceEventType eventType, int id,
                       bool hasRelatedActivity, Guid relatedActivity,
                       int level, bool wrapData, params object [] data)
        {
            Process p = eventCache != null?
                        Process.GetProcessById(eventCache.ProcessId) :
                            Process.GetCurrentProcess();

            w.WriteStartElement("E2ETraceEvent", e2e_ns);

            // <System>
            w.WriteStartElement("System", sys_ns);
            w.WriteStartElement("EventID", sys_ns);
            w.WriteString(XmlConvert.ToString(id));
            w.WriteEndElement();
            // FIXME: find out what should be written
            w.WriteStartElement("Type", sys_ns);
            w.WriteString("3");
            w.WriteEndElement();
            w.WriteStartElement("SubType", sys_ns);
            // FIXME: it does not seem always to match eventType value ...
            w.WriteAttributeString("Name", eventType.ToString());
            // FIXME: find out what should be written
            w.WriteString("0");
            w.WriteEndElement();
            // FIXME: find out what should be written
            w.WriteStartElement("Level", sys_ns);
            w.WriteString(level.ToString());
            w.WriteEndElement();
            w.WriteStartElement("TimeCreated", sys_ns);
            w.WriteAttributeString("SystemTime", XmlConvert.ToString(eventCache != null ? eventCache.DateTime : DateTime.Now));
            w.WriteEndElement();
            w.WriteStartElement("Source", sys_ns);
            w.WriteAttributeString("Name", source);
            w.WriteEndElement();
            w.WriteStartElement("Correlation", sys_ns);
            w.WriteAttributeString("ActivityID", String.Concat("{", Guid.Empty, "}"));
            w.WriteEndElement();
            w.WriteStartElement("Execution", sys_ns);
            // FIXME: which should I use here?
            //w.WriteAttributeString ("ProcessName", p.ProcessName);
            w.WriteAttributeString("ProcessName", p.MainModule.ModuleName);
            w.WriteAttributeString("ProcessID", p.Id.ToString());
            w.WriteAttributeString("ThreadID", eventCache != null ? eventCache.ThreadId : Thread.CurrentThread.ManagedThreadId.ToString());
            w.WriteEndElement();
            w.WriteStartElement("Channel", sys_ns);
            // FIXME: find out what should be written.
            w.WriteEndElement();
            w.WriteStartElement("Computer");
            w.WriteString(p.MachineName);
            w.WriteEndElement();

            w.WriteEndElement();

            // <ApplicationData>
            w.WriteStartElement("ApplicationData", e2e_ns);
            w.WriteStartElement("TraceData", e2e_ns);
            foreach (object o in data)
            {
                if (wrapData)
                {
                    w.WriteStartElement("DataItem", e2e_ns);
                }
                if (o is XPathNavigator)
                {
                    // the output ignores xmlns difference between the parent (E2ETraceEvent and the content node).
                    // To clone such behavior, I took this approach.
                    w.WriteRaw(XPathNavigatorToString((XPathNavigator)o));
                }
                else if (o != null)
                {
                    w.WriteString(o.ToString());
                }
                if (wrapData)
                {
                    w.WriteEndElement();
                }
            }
            w.WriteEndElement();
            w.WriteEndElement();

            w.WriteEndElement();

            w.Flush();            // for XmlWriter
            Flush();              // for TextWriter
        }
Esempio n. 18
0
        private void _StartProcess()
        {
            if (!_CommandExists())
            {
                throw new PeachException("CrashWrangler: Could not find command \"" + _command + "\"");
            }

            if (File.Exists(_cwPidFile))
            {
                File.Delete(_cwPidFile);
            }

            if (File.Exists(_cwLogFile))
            {
                File.Delete(_cwLogFile);
            }

            if (File.Exists(_cwLockFile))
            {
                File.Delete(_cwLockFile);
            }

            var si = new ProcessStartInfo();

            si.FileName        = _execHandler;
            si.Arguments       = "\"" + _command + "\"" + (_arguments.Length == 0 ? "" : " ") + _arguments;
            si.UseShellExecute = false;

            foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
            {
                si.EnvironmentVariables[de.Key.ToString()] = de.Value.ToString();
            }

            si.EnvironmentVariables["CW_NO_CRASH_REPORTER"] = "1";
            si.EnvironmentVariables["CW_QUIET"]             = "1";
            si.EnvironmentVariables["CW_LOG_PATH"]          = _cwLogFile;
            si.EnvironmentVariables["CW_PID_FILE"]          = _cwPidFile;
            si.EnvironmentVariables["CW_LOCK_FILE"]         = _cwLockFile;

            if (_useDebugMalloc)
            {
                si.EnvironmentVariables["CW_USE_GMAL"] = "1";
            }

            if (_exploitableReads)
            {
                si.EnvironmentVariables["CW_EXPLOITABLE_READS"] = "1";
            }

            _procHandler           = new Proc();
            _procHandler.StartInfo = si;

            try
            {
                _procHandler.Start();
            }
            catch (Win32Exception ex)
            {
                string err = GetLastError(ex.NativeErrorCode);
                throw new PeachException(string.Format("CrashWrangler: Could not start handler \"{0}\" - {1}", _execHandler, err), ex);
            }

            _totalProcessorTime = 0;

            // Wait for pid file to exist, open it up and read it
            while (!File.Exists(_cwPidFile) && !_procHandler.HasExited)
            {
                Thread.Sleep(250);
            }

            string strPid = File.ReadAllText(_cwPidFile);
            int    pid    = Convert.ToInt32(strPid);

            try
            {
                _procCommand = Proc.GetProcessById(pid);
            }
            catch (ArgumentException ex)
            {
                if (!_procHandler.HasExited)
                {
                    throw new PeachException("CrashWrangler: Could not open handle to command \"" + _command + "\" with pid \"" + pid + "\"", ex);
                }

                var ret = _procHandler.ExitCode;
                var log = File.Exists(_cwLogFile);

                // If the exit code non-zero and no log means it was unable to run the command
                if (ret != 0 && !log)
                {
                    throw new PeachException("CrashWrangler: Handler could not run command \"" + _command + "\"", ex);
                }

                // If the exit code is 0 or there is a log, the program ran to completion
                if (_procCommand != null)
                {
                    _procCommand.Close();
                    _procCommand = null;
                }
            }
        }
Esempio n. 19
0
        void TraceCore(TraceEventCache eventCache,
                       string source, TraceEventType eventType, int id,
                       bool hasRelatedActivity, Guid relatedActivity,
                       int level, bool wrapData, params object [] data)
        {
            Process p = eventCache != null?
                        Process.GetProcessById(eventCache.ProcessId) :
                            Process.GetCurrentProcess();

            w.WriteStartElement("E2ETraceEvent", e2e_ns);

            // <System>
            w.WriteStartElement("System", sys_ns);
            w.WriteStartElement("EventID", sys_ns);
            w.WriteString(XmlConvert.ToString(id));
            w.WriteEndElement();
            // FIXME: find out what should be written
            w.WriteStartElement("Type", sys_ns);
            w.WriteString("3");
            w.WriteEndElement();
            w.WriteStartElement("SubType", sys_ns);
            // FIXME: it does not seem always to match eventType value ...
            w.WriteAttributeString("Name", eventType.ToString());
            // FIXME: find out what should be written
            w.WriteString("0");
            w.WriteEndElement();
            // FIXME: find out what should be written
            w.WriteStartElement("Level", sys_ns);
            w.WriteString(level.ToString());
            w.WriteEndElement();
            w.WriteStartElement("TimeCreated", sys_ns);
            w.WriteAttributeString("SystemTime", XmlConvert.ToString(eventCache != null ? eventCache.DateTime : DateTime.Now));
            w.WriteEndElement();
            w.WriteStartElement("Source", sys_ns);
            w.WriteAttributeString("Name", source);
            w.WriteEndElement();
            w.WriteStartElement("Correlation", sys_ns);
            w.WriteAttributeString("ActivityID", String.Concat("{", Guid.Empty, "}"));
            w.WriteEndElement();
            w.WriteStartElement("Execution", sys_ns);
            // FIXME: which should I use here?
            //w.WriteAttributeString ("ProcessName", p.ProcessName);
            w.WriteAttributeString("ProcessName", p.MainModule.ModuleName);
            w.WriteAttributeString("ProcessID", p.Id.ToString());
            w.WriteAttributeString("ThreadID", eventCache != null ? eventCache.ThreadId : Thread.CurrentThread.ManagedThreadId.ToString());
            w.WriteEndElement();
            w.WriteStartElement("Channel", sys_ns);
            // FIXME: find out what should be written.
            w.WriteEndElement();
            w.WriteStartElement("Computer");
            w.WriteString(p.MachineName);
            w.WriteEndElement();

            w.WriteEndElement();

            // <ApplicationData>
            w.WriteStartElement("ApplicationData", e2e_ns);
            foreach (object o in data)
            {
                if (wrapData)
                {
                    w.WriteStartElement("TraceData", e2e_ns);
                }
                if (o != null)
                {
                    w.WriteString(o.ToString());
                }
                if (wrapData)
                {
                    w.WriteEndElement();
                }
            }
            w.WriteEndElement();

            w.WriteEndElement();
        }
Esempio n. 20
0
 public void GetProcessById() => Process.GetProcessById(_currentProcessId).Dispose();