Ejemplo n.º 1
0
        internal static void KillProcessTree(int processId)
        {
            if (processId <= 0)
            {
                return;
            }

            var searcher = new ManagementObjectSearcher($"Select * From Win32_Process Where ParentProcessID={processId}");

            var results = searcher.Get();

            foreach (var baseObject in results)
            {
                var managementObject = (ManagementObject)baseObject;

                KillProcessTree(Convert.ToInt32(managementObject["ProcessID"]));
            }

            try
            {
                var process = Process.GetProcessById(processId);

                process.Kill();
            }
            catch (ArgumentException)
            {
                // Process already exited.
            }
        }
Ejemplo n.º 2
0
        public static void HandleGetConnections(Networking.Client client, GetConnections packet)
        {
            var table = GetTable();

            var connections = new Models.TcpConnection[table.Length];

            for (int i = 0; i < table.Length; i++)
            {
                string processName;
                try
                {
                    var p = Process.GetProcessById((int)table[i].owningPid);
                    processName = p.ProcessName;
                }
                catch
                {
                    processName = $"PID: {table[i].owningPid}";
                }

                connections[i] = new Models.TcpConnection {
                    ProcessName   = processName,
                    LocalAddress  = table[i].LocalAddress.ToString(),
                    LocalPort     = table[i].LocalPort,
                    RemoteAddress = table[i].RemoteAddress.ToString(),
                    RemotePort    = table[i].RemotePort,
                    State         = (ConnectionState)table[i].state
                };
            }

            client.Send(new GetConnectionsResponse {
                Connections = connections
            });
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates and injects the current <see cref="VirtualizedProcess"/>,
        /// and sets the created process component to the <see cref="_process"/> variable.
        /// </summary>
        /// <exception cref="FileNotFoundException"></exception>
        private void CreateAndInject()
        {
            int processId;
            // Get the location of the library to inject
            string libraryLocation = HostCore.Configuration.Application.LibtoInject;

            if (!File.Exists(libraryLocation))
            {
                throw new FileNotFoundException("Unable to locate the library to inject.", libraryLocation);
            }
            RemoteHooking.CreateAndInject(
                Path.Combine(_startInfo.WorkingDirectory.FileName, _startInfo.Files.Executable.FileName),
                // Optional command line parameters for process creation
                _startInfo.Arguments,
                // ProcessCreationFlags, no conditions are set on the created process.
                0,
                // Absolute paths of the libraries to inject, we use the same one for 32bit and 64bit
                libraryLocation, libraryLocation,
                // The process ID of the newly created process
                out processId,
                // Extra parameters being passed to the injected library entry points Run() and Initialize()
                _connection.ChannelName);
            // The process has been created, set the _process variable.
            _process = SystemProcess.GetProcessById(processId, HostCore.Runtime.CurrentProcess.MachineName);
            _process.EnableRaisingEvents = true;
            _process.Exited += Process_Exited;
        }
Ejemplo n.º 4
0
        private static Process FindOrCreateProcess(string application, IEnumerable <string> args, bool suspended)
        {
            var processes = Process.GetProcessesByName(application);

            if (processes.Length > 0)
            {
                return(processes[0]);
            }

            var startupInfo = new StartupInfo();
            var arguments   = args.Select(arg => arg.Contains(" ") ? $"\"{arg}\"" : arg);

            Kernel32.CreateProcess(
                $"{application}.exe",
                $"{application}.exe {string.Join(" ", arguments)}",
                IntPtr.Zero,
                IntPtr.Zero,
                false,
                suspended
                    ? ProcessCreationFlags.CreateSuspended
                    : ProcessCreationFlags.None,
                IntPtr.Zero,
                null,
                ref startupInfo,
                out var processInformation
                );

            return(Process.GetProcessById(processInformation.dwProcessId));
        }
Ejemplo n.º 5
0
        // Shut down the bottle and clean up.
        public static int ShutdownHandler(bool verbose)
        {
            // Get the bottle state.
            var state = GetBottleState(verbose);

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

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

            using (var r = new RootPrivilege())
            {
                if (verbose)
                {
                    Console.WriteLine("genie: running systemctl poweroff within bottle");
                }

                var systemdPid = Helpers.GetSystemdPid();
                var sd         = Process.GetProcessById(systemdPid);

                Helpers.Chain("nsenter",
                              new string[] { "-t", systemdPid.ToString(), "-m", "-p", "systemctl", "poweroff" },
                              "running command failed; nsenter");

                Console.Write("Waiting for systemd exit...");

                // Wait for systemd to exit.
                int timeout = Config.SystemdStartupTimeout;

                while (!sd.WaitForExit(1000))
                {
                    Console.Write(".");
                    timeout--;

                    if (timeout < 0)
                    {
                        Console.WriteLine("\n\nTimed out waiting for systemd to exit.\nThis may indicate a systemd configuration error.\nAttempting to continue.");
                        break;
                    }
                }

                Console.WriteLine();

                if (Config.UpdateHostname)
                {
                    Thread.Sleep(500);
                    Helpers.DropHostname(verbose);
                }
            }

            return(0);
        }
        /// <summary>
        /// Retrieves Process from the current ReloadedProcess.
        /// </summary>
        /// <returns>Process class for the current Reloaded Process.</returns>
        public SystemProcess GetProcessFromReloadedProcess()
        {
            if (Process != null)
            {
                return(Process);
            }

            Process = SystemProcess.GetProcessById((int)ProcessId);
            return(Process);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// A method called on click event of 'Kill process' button.
        /// Kill all processes which IDs are stored in the list _processIdToKill.
        /// </summary>
        /// <param name="o">Reference to the button object</param>
        /// <param name="args">Event arguments</param>
        private void KillProcess(object o, EventArgs args)
        {
            // KillDialog - a dialog that pops up to confirm process assassination
            using (KillDialog killDialog = new KillDialog(_window, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null))
            {
                int processesToKillCount = _processIdToKill.Count;

                if (processesToKillCount == 0)
                {
                    return;
                }
                if (processesToKillCount == 1)
                {
                    int     processId = _processIdToKill[0];
                    Process process   = Process.GetProcessById(processId);
                    killDialog.Text =
                        $"Are you sure you want to end the selected process \"{process.ProcessName}\" (PID: {processId.ToString()})?";
                    process.Dispose();
                }
                else
                {
                    killDialog.Text =
                        $"Are you sure you want to end the {processesToKillCount.ToString()} selected processes?";
                }

                // Add a callback to click event on any button within KillDialog
                killDialog.Response += (o1, responseArgs) =>
                {
                    switch (responseArgs.ResponseId)
                    {
                    // Click on YES button
                    case ResponseType.Yes:
                        foreach (var id in _processIdToKill)
                        {
                            Process process = Process.GetProcessById(id);
                            process.Kill();

                            Console.WriteLine($"{id.ToString()} killed");

                            // Cleaning up
                            process.Dispose();
                        }

                        break;

                    // Click on NO button
                    case ResponseType.No:
                        Console.WriteLine("Abort killing.");
                        break;
                    }
                };

                killDialog.Run();
            }
        }
Ejemplo n.º 8
0
 private static Process GetProcessById(int processId)
 {
     try
     {
         return(Process.GetProcessById(processId));
     }
     catch (ArgumentException)
     {
         return(null);
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Waits for completion of the process.
        /// </summary>
        /// <inheritdoc />
        public void WaitForCompletion()
        {
            var parentProcessId = GetVariable <int>(ZappVariables.ParentProcessIdEnvKey);

            var process = WinProcess
                          .GetProcessById(parentProcessId);

            process.EnableRaisingEvents = true;
            process.Exited += (s, e) => Cancel();

            resetEvent.WaitOne();
        }
Ejemplo n.º 10
0
        // Shut down the bottle and clean up.
        public static int ShutdownHandler(bool verbose)
        {
            // Get the bottle state.
            var state = GetBottleState(verbose);

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

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

            using (var r = new RootPrivilege())
            {
                if (verbose)
                {
                    Console.WriteLine("genie: running systemctl poweroff within bottle");
                }

                var systemdPid = Helpers.GetSystemdPid();
                var sd         = Process.GetProcessById(systemdPid);

                Helpers.Chain("nsenter",
                              new string[] { "-t", systemdPid.ToString(), "-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 (Config.UpdateHostname)
                {
                    Thread.Sleep(500);
                    Helpers.DropHostname(verbose);
                }
            }

            return(0);
        }
        public int AttachDebugger(List <string> portNumbers, string filter)
        {
            List <int> portNumbersParsed = ParsePortNumbers(portNumbers);

            if (portNumbersParsed == null)
            {
                return(-1);
            }

            List <Process> vsProcessesOtherThanThisOne = GetVSProcessesOtherThanThisOne()?.FilterProcesses(filter);

            if (vsProcessesOtherThanThisOne.Count == 0)
            {
                _consoleWriter.PrintNoOtherVSInstancesAreOpenToUseAsDebugger();
                return(-1);
            }

            List <Process> targetProcesses = new List <Process>();

            foreach (int port in portNumbersParsed)
            {
                int targetProcessId = _lowerLevelOpertationsService.GetProcessIdByPortNumber(port);

                Process targetProcess = Process.GetProcessById(targetProcessId);

                _consoleWriter.PrintTargetProcessDetails(targetProcess, port);

                targetProcesses.Add(targetProcess);
            }

            Process vsInstanceToAttachTo = vsProcessesOtherThanThisOne.Count > 1
                ? GetBestVsInstanceToAttachAsDebugger(vsProcessesOtherThanThisOne, filter)
                : vsProcessesOtherThanThisOne[0];

            bool attached = _lowerLevelOpertationsService.AttachVisualStudioToProcess(vsInstanceToAttachTo, targetProcesses);

            if (!attached)
            {
                return(-1);
            }

            _consoleWriter.PrintAttachedSuccess(targetProcesses, vsInstanceToAttachTo);

            _consoleWriter.PrintApplicationsJobCompleteAndExit();

            return(0);
        }
Ejemplo 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 = Native.Native.OpenThread(Native.Native.THREAD_ALL_ACCESS, false, (int)ThreadId);
        }
Ejemplo n.º 13
0
        public VsDebuggerAttacher(ILogger logger, int processId)
        {
            _logger = logger;
            _visualStudioProcess = Process.GetProcessById(processId);

            _DTE visualStudioInstance;

            if (NativeMethods.TryGetVsInstance(_visualStudioProcess.Id, out visualStudioInstance))
            {
                _visualStudioInstance = visualStudioInstance;
            }
            else
            {
                logger.LogError("Could not find Visual Studio instance");
                throw new InvalidOperationException("Could not find Visual Studio instance");
            }
        }
Ejemplo n.º 14
0
        private void childUpdateTimer_Tick(object sender, EventArgs e)
        {
            // remove any stale processes
            for (int i = 0; i < m_Children.Count; i++)
            {
                try
                {
                    // if this throws an exception the process no longer exists so we'll remove it
                    Process.GetProcessById(m_Children[i].PID);
                }
                catch (Exception)
                {
                    if (m_Children[i].added)
                    {
                        childProcesses.Items.RemoveByKey(m_Children[i].PID.ToString());
                    }

                    // process expired/doesn't exist anymore
                    m_Children.RemoveAt(i);

                    // don't increment i, check the next element at i (if we weren't at the end
                    i--;
                }
            }

            for (int i = 0; i < m_Children.Count; i++)
            {
                if (!m_Children[i].added)
                {
                    string text = String.Format("{0} [PID {1}]", m_Children[i].name, m_Children[i].PID);

                    m_Children[i].added = true;
                    childProcesses.Items.Add(m_Children[i].PID.ToString(), text, 0).Tag = m_Children[i].ident;
                }
            }

            if (m_Children.Count > 0)
            {
                childProcessLabel.Visible = childProcesses.Visible = true;
            }
            else
            {
                childProcessLabel.Visible = childProcesses.Visible = false;
            }
        }
Ejemplo n.º 15
0
        /// <summary>Determines whether this instance this instance can be started.</summary>
        /// <returns><c>true</c> if this instance can be started; otherwise <c>false</c>.</returns>
        private static bool CanStartThisInstance()
        {
            // check for the "newinstance" argument
            var forceNewInstance = false;

            foreach (var arg in Program.Arguments)
            {
                if (arg == ValidArgs.NewInstance)
                {
                    forceNewInstance = true;
                }
                else if (arg.StartsWith(ValidArgs.ParentProcId))
                {
                    var id = int.Parse(arg.Replace(ValidArgs.ParentProcId, "").Trim());
                    _parentProc  = Process.GetProcessById(id);
                    _isChildProc = true;
                }
            }

            if (forceNewInstance)
            {
                return(true);                  // force starting process
            }
            // check for a previous instance
            var appExeFile = new System.IO.FileInfo(AppPath).Name;

            appExeFile = appExeFile.Remove(appExeFile.LastIndexOf('.')); // remove the extension

            var procs    = Process.GetProcessesByName(appExeFile);
            var thisProc = Process.GetCurrentProcess();

            debuggerAttached = System.Diagnostics.Debugger.IsAttached;

            /*
             * Conditions for starting this instance:
             *  1. This is the only process
             *  2. More than one process and one of the existing processes is this one's parent
             *  3. A debugger is attached to this process
             */
            return((procs.Length == 1 && procs[0].Id == thisProc.Id) ||     // condition 1
                   (procs.Length > 1 && _parentProc != null &&
                    procs.Select(p => p.Id).Contains(_parentProc.Id)) ||    // condition 2
                   debuggerAttached);                                       // condition 3
        }
Ejemplo n.º 16
0
        public IProcess GetProcessById(int processId)
        {
            NativeProcess process;

            try
            {
                process = NativeProcess.GetProcessById(processId);
            }
            catch
            {
                return(null);
            }

            return(new Process
            {
                Id = process.Id,
                MainWindowTitle = process.MainWindowTitle,
                ProcessName = process.ProcessName
            });
        }
Ejemplo n.º 17
0
        public void LaunchTraceTargets(IReadOnlyList <TraceLaunchTarget> targets)
        {
            if (!IsAutoLogEnabled || runningSession != null || !autoLogProfile.IsUsable())
            {
                return;
            }

            autoLogExitCts?.Cancel();
            autoLogExitCts = new CancellationTokenSource();

            var processTasks = targets.Select(
                x => {
                try {
                    return(Process.GetProcessById((int)x.ProcessId).WaitForExitAsync(autoLogExitCts.Token));
                } catch (ArgumentException) {
                    // The launched process is not running (anymore).
                    return(null);
                }
            }).Where(x => x != null).ToList();

            if (processTasks.Count == 0)
            {
                return; // All launched processes have ended already.
            }
            var profile = AugmentTraceProfile(autoLogProfile, targets);

            if (asyncAutoLog)
            {
                StartSessionAsync(profile).Forget();
            }
            else
            {
                StartSession(profile);
            }

            Task.WhenAll(processTasks).ContinueWith(t => {
                ExitTraceTargets(targets);
            }, autoLogExitCts.Token, TaskContinuationOptions.None, TaskScheduler.Default).Forget();
        }
Ejemplo n.º 18
0
 private void WaitForProcess(int processId)
 {
     // Wait for launcher to close (failure is fatal)
     try
     {
         Log("Waiting for launcher to close...");
         Process process = Process.GetProcessById(processId);
         if (!process.WaitForExit(ExitProcessTimeoutInMs))
         {
             Log("Launcher hasn't closed gracefully; killing launcher process...");
             // Process failed to exit gracefully; murder it
             process.Kill();
         }
     }
     catch (ArgumentException) { }         // Process doesn't exist; already closed
     catch (InvalidOperationException) { } // Process doesn't exist; already closed
     catch (Win32Exception e) // Process couldn't be killed; update failed
     {
         throw new CannotKillProcessException($"Unable to kill launcher process", e);
     }
     // Process has ended successfully
     Log("Launcher closed; applying update...");
 }
Ejemplo n.º 19
0
        private void ConnectionThreadEntry()
        {
            try
            {
                string username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

                m_Connection = StaticExports.CreateTargetControl(m_Host, m_RemoteIdent, username, true);

                if (m_Connection.Connected)
                {
                    string api = "No API detected";
                    if (m_Connection.API.Length > 0)
                    {
                        api = m_Connection.API;
                    }
                    this.BeginInvoke((MethodInvoker) delegate
                    {
                        if (m_Connection.PID == 0)
                        {
                            connectionStatus.Text = String.Format("Connection established to {0} ({1})", m_Connection.Target, api);
                            SetText(String.Format("{0}", m_Connection.Target));
                        }
                        else
                        {
                            connectionStatus.Text = String.Format("Connection established to {0} [PID {1}] ({2})",
                                                                  m_Connection.Target, m_Connection.PID, api);
                            SetText(String.Format("{0} [PID {1}]", m_Connection.Target, m_Connection.PID));
                        }
                        connectionIcon.Image = global::renderdocui.Properties.Resources.connect;
                    });
                }
                else
                {
                    throw new ReplayCreateException(ReplayCreateStatus.NetworkIOFailed);
                }

                while (m_Connection.Connected)
                {
                    m_Connection.ReceiveMessage();

                    if (m_TriggerCapture)
                    {
                        m_Connection.TriggerCapture((uint)m_CaptureNumFrames);
                        m_TriggerCapture = false;
                    }

                    if (m_QueueCapture)
                    {
                        m_Connection.QueueCapture((uint)m_CaptureFrameNum);
                        m_QueueCapture    = false;
                        m_CaptureFrameNum = 0;
                    }

                    if (m_CopyLogLocalPath != "")
                    {
                        m_Connection.CopyCapture(m_CopyLogID, m_CopyLogLocalPath);
                        m_CopyLogLocalPath = "";
                        m_CopyLogID        = uint.MaxValue;
                    }

                    List <uint> dels = new List <uint>();
                    lock (m_DeleteLogs)
                    {
                        dels.AddRange(m_DeleteLogs);
                        m_DeleteLogs.Clear();
                    }

                    foreach (var del in dels)
                    {
                        m_Connection.DeleteCapture(del);
                    }

                    if (m_Disconnect)
                    {
                        m_Connection.Shutdown();
                        m_Connection = null;
                        return;
                    }

                    if (m_Connection.InfoUpdated)
                    {
                        this.BeginInvoke((MethodInvoker) delegate
                        {
                            if (m_Connection.PID == 0)
                            {
                                connectionStatus.Text = String.Format("Connection established to {0} ({1})", m_Connection.Target, m_Connection.API);
                                SetText(String.Format("{0}", m_Connection.Target));
                            }
                            else
                            {
                                connectionStatus.Text = String.Format("Connection established to {0} [PID {1}] ({2})",
                                                                      m_Connection.Target, m_Connection.PID, m_Connection.API);
                                SetText(String.Format("{0} [PID {1}]", m_Connection.Target, m_Connection.PID));
                            }
                            connectionIcon.Image = global::renderdocui.Properties.Resources.connect;
                        });

                        m_Connection.InfoUpdated = false;
                    }

                    if (m_Connection.CaptureExists)
                    {
                        uint     capID     = m_Connection.CaptureFile.ID;
                        DateTime timestamp = new DateTime(1970, 1, 1, 0, 0, 0);
                        timestamp = timestamp.AddSeconds(m_Connection.CaptureFile.timestamp).ToLocalTime();
                        byte[] thumb       = m_Connection.CaptureFile.thumbnail;
                        int    thumbWidth  = m_Connection.CaptureFile.thumbWidth;
                        int    thumbHeight = m_Connection.CaptureFile.thumbHeight;
                        string path        = m_Connection.CaptureFile.path;
                        bool   local       = m_Connection.CaptureFile.local;

                        this.BeginInvoke((MethodInvoker) delegate
                        {
                            CaptureAdded(capID, m_Connection.Target, m_Connection.API, thumb, thumbWidth, thumbHeight, timestamp, path, local);
                        });
                        m_Connection.CaptureExists = false;
                    }

                    if (m_Connection.CaptureCopied)
                    {
                        uint   capID = m_Connection.CaptureFile.ID;
                        string path  = m_Connection.CaptureFile.path;

                        this.BeginInvoke((MethodInvoker) delegate
                        {
                            CaptureCopied(capID, path);
                        });

                        m_Connection.CaptureCopied = false;
                    }

                    if (m_Connection.ChildAdded)
                    {
                        if (m_Connection.NewChild.PID != 0)
                        {
                            try
                            {
                                ChildProcess c = new ChildProcess();
                                c.PID   = (int)m_Connection.NewChild.PID;
                                c.ident = m_Connection.NewChild.ident;
                                c.name  = Process.GetProcessById((int)m_Connection.NewChild.PID).ProcessName;

                                lock (m_Children)
                                {
                                    m_Children.Add(c);
                                }
                            }
                            catch (Exception)
                            {
                                // process expired/doesn't exist anymore
                            }
                        }

                        m_Connection.ChildAdded = false;
                    }
                }

                this.BeginInvoke((MethodInvoker) delegate
                {
                    connectionStatus.Text = "Connection closed";
                    connectionIcon.Image  = global::renderdocui.Properties.Resources.disconnect;

                    numFrames.Enabled          = captureDelay.Enabled = captureFrame.Enabled =
                        triggerCapture.Enabled = queueCap.Enabled = false;

                    ConnectionClosed();
                });
            }
            catch (ReplayCreateException)
            {
                this.BeginInvoke((MethodInvoker) delegate
                {
                    SetText("Connection failed");
                    connectionStatus.Text = "Connection failed";
                    connectionIcon.Image  = global::renderdocui.Properties.Resources.delete;

                    ConnectionClosed();
                });
            }
        }
Ejemplo n.º 20
0
        private void ConnectionThreadEntry()
        {
            try
            {
                string username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

                m_Connection = StaticExports.CreateRemoteAccessConnection(m_Host, m_RemoteIdent, username, true);

                if (m_Connection.Connected)
                {
                    string api = "...";
                    if (m_Connection.API.Length > 0)
                    {
                        api = m_Connection.API;
                    }
                    this.BeginInvoke((MethodInvoker) delegate
                    {
                        if (m_Connection.PID == 0)
                        {
                            connectionStatus.Text = String.Format("Connection established to {0} ({1})", m_Connection.Target, api);
                            Text = String.Format("{0} ({1})", m_Connection.Target, api);
                        }
                        else
                        {
                            connectionStatus.Text = String.Format("Connection established to {0} [PID {1}] ({2})",
                                                                  m_Connection.Target, m_Connection.PID, api);
                            Text = String.Format("{0} [PID {1}] ({2})", m_Connection.Target, m_Connection.PID, api);
                        }
                        connectionIcon.Image = global::renderdocui.Properties.Resources.connect;
                    });
                }
                else
                {
                    throw new ApplicationException();
                }

                while (m_Connection.Connected)
                {
                    m_Connection.ReceiveMessage();

                    if (m_TriggerCapture)
                    {
                        m_Connection.TriggerCapture();
                        m_TriggerCapture = false;
                    }

                    if (m_QueueCapture)
                    {
                        m_Connection.QueueCapture((uint)m_CaptureFrameNum);
                        m_QueueCapture    = false;
                        m_CaptureFrameNum = 0;
                    }

                    if (m_Disconnect)
                    {
                        m_Connection.Shutdown();
                        m_Connection = null;
                        return;
                    }

                    if (m_Connection.InfoUpdated)
                    {
                        this.BeginInvoke((MethodInvoker) delegate
                        {
                            connectionStatus.Text = String.Format("Connection established to {0} ({1})", m_Connection.Target, m_Connection.API);
                            Text = String.Format("{0} ({1})", m_Connection.Target, m_Connection.API);
                            connectionIcon.Image = global::renderdocui.Properties.Resources.connect;
                        });

                        m_Connection.InfoUpdated = false;
                    }

                    if (m_Connection.CaptureExists)
                    {
                        uint     capID     = m_Connection.CaptureFile.ID;
                        DateTime timestamp = new DateTime(1970, 1, 1, 0, 0, 0);
                        timestamp = timestamp.AddSeconds(m_Connection.CaptureFile.timestamp).ToLocalTime();
                        byte[] thumb = m_Connection.CaptureFile.thumbnail;
                        string path  = m_Connection.CaptureFile.localpath;

                        if (path.Length == 0 || File.Exists(path))
                        {
                            this.BeginInvoke((MethodInvoker) delegate
                            {
                                CaptureAdded(capID, m_Connection.Target, m_Connection.API, thumb, timestamp);
                                if (path.Length > 0)
                                {
                                    CaptureRetrieved(capID, path);
                                }
                            });
                            m_Connection.CaptureExists = false;

                            if (path.Length == 0)
                            {
                                m_Connection.CopyCapture(capID, m_Core.TempLogFilename("remotecopy_" + m_Connection.Target));
                            }
                        }
                    }

                    if (m_Connection.CaptureCopied)
                    {
                        uint   capID = m_Connection.CaptureFile.ID;
                        string path  = m_Connection.CaptureFile.localpath;

                        this.BeginInvoke((MethodInvoker) delegate
                        {
                            CaptureRetrieved(capID, path);
                        });
                        m_Connection.CaptureCopied = false;
                    }

                    if (m_Connection.ChildAdded)
                    {
                        if (m_Connection.NewChild.PID != 0)
                        {
                            try
                            {
                                ChildProcess c = new ChildProcess();
                                c.PID   = (int)m_Connection.NewChild.PID;
                                c.ident = m_Connection.NewChild.ident;
                                c.name  = Process.GetProcessById((int)m_Connection.NewChild.PID).ProcessName;

                                lock (m_Children)
                                {
                                    m_Children.Add(c);
                                }
                            }
                            catch (Exception)
                            {
                                // process expired/doesn't exist anymore
                            }
                        }

                        m_Connection.ChildAdded = false;
                    }
                }

                this.BeginInvoke((MethodInvoker) delegate
                {
                    connectionStatus.Text = "Connection closed";
                    connectionIcon.Image  = global::renderdocui.Properties.Resources.disconnect;

                    ConnectionClosed();
                });
            }
            catch (ApplicationException)
            {
                this.BeginInvoke((MethodInvoker) delegate
                {
                    Text = (m_Host.Length > 0 ? (m_Host + " - ") : "") + "Connection failed";
                    connectionStatus.Text = "Connection failed";
                    connectionIcon.Image  = global::renderdocui.Properties.Resources.delete;

                    ConnectionClosed();
                });
            }
        }
Ejemplo n.º 21
0
        private static DTE GetDTE(int processId)
        {
            MessageFilter.Register();

            var prefix = Process.GetProcessById(processId).ProcessName;

            if ("devenv".Equals(prefix, StringComparison.OrdinalIgnoreCase))
            {
                prefix = "VisualStudio";
            }

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

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

            try {
                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;
                    }
                }
            } finally {
                if (enumMonikers != null)
                {
                    Marshal.ReleaseComObject(enumMonikers);
                }

                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }

                if (bindCtx != null)
                {
                    Marshal.ReleaseComObject(bindCtx);
                }
            }

            return((DTE)runningObject);
        }
Ejemplo n.º 22
0
        private static DTE GetDTE(int processId)
        {
#if DEV15
            // VS 2017 doesn't install some assemblies to the GAC that are needed to work with the
            // debugger, and as the tests don't execute in the devenv.exe process, those assemblies
            // fail to load - so load them manually from PublicAssemblies.

            // Use the executable name, as this is only needed for the out of proc test execution
            // that may interact with the debugger (vstest.executionengine.x86.exe).
            if (!DTELoaded)
            {
                string currentProc = Process.GetCurrentProcess().MainModule.FileName;
                if (StringComparer.OrdinalIgnoreCase.Equals(
                        Path.GetFileName(currentProc), "vstest.executionengine.x86.exe"))
                {
                    string baseDir          = Path.GetDirectoryName(currentProc);
                    string publicAssemblies = Path.Combine(baseDir, "..\\..\\..\\PublicAssemblies");

                    Assembly.LoadFrom(Path.Combine(publicAssemblies, "Microsoft.VisualStudio.OLE.Interop.dll"));
                    Assembly.LoadFrom(Path.Combine(publicAssemblies, "envdte90.dll"));
                    Assembly.LoadFrom(Path.Combine(publicAssemblies, "envdte80.dll"));
                    Assembly.LoadFrom(Path.Combine(publicAssemblies, "envdte.dll"));
                }
                DTELoaded = true;
            }
#endif
            MessageFilter.Register();

            var prefix = Process.GetProcessById(processId).ProcessName;
            if ("devenv".Equals(prefix, StringComparison.OrdinalIgnoreCase))
            {
                prefix = "VisualStudio";
            }

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

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

            try {
                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;
                    }
                }
            } finally {
                if (enumMonikers != null)
                {
                    Marshal.ReleaseComObject(enumMonikers);
                }

                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }

                if (bindCtx != null)
                {
                    Marshal.ReleaseComObject(bindCtx);
                }
            }

            return((DTE)runningObject);
        }
Ejemplo n.º 23
0
        // Shut down the bottle and clean up.
        public static int ShutdownHandler(bool verbose)
        {
            // Get the bottle state.
            var state = GetBottleState(verbose);

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

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

            using (var r = new RootPrivilege())
            {
                if (verbose)
                {
                    Console.WriteLine("genie: running systemctl poweroff within bottle");
                }

                var systemdPid = Helpers.GetSystemdPid();
                var sd         = Process.GetProcessById(systemdPid);

                Helpers.Chain("nsenter",
                              new string[] { "-t", systemdPid.ToString(), "-m", "-p", "systemctl", "poweroff" },
                              "running command failed; nsenter");

                Console.Write("Waiting for systemd exit...");

                // Wait for systemd to exit.
                int timeout = Config.SystemdStartupTimeout;

                while (!sd.WaitForExit(1000))
                {
                    Console.Write(".");
                    timeout--;

                    if (timeout < 0)
                    {
                        Console.WriteLine("\n\nTimed out waiting for systemd to exit.\nThis may indicate a systemd configuration error.\nAttempting to continue.");
                        break;
                    }
                }

                Console.WriteLine();

                // Having unmounted the binfmts fs before starting systemd, we remount it now as
                // a courtesy. But remember, genie is not guaranteed to be idempotent, so don't
                // rely on this, for the love of Thompson and Ritchie!
                if (!Directory.Exists("/proc/sys/fs/binfmt_misc"))
                {
                    if (verbose)
                    {
                        Console.WriteLine("genie: remounting binfmt_misc filesystem as a courtesy");
                    }

                    if (!MountHelpers.Mount("binfmt_misc", "/proc/sys/fs/binfmt_misc", FsType.BinaryFormats))
                    {
                        Console.WriteLine("genie: failed to remount binfmt_misc filesystem; attempting to continue");
                    }
                }

                if (Config.ResolvedStub)
                {
                    Helpers.RemoveResolvSymlink(verbose);
                }

                if (Config.UpdateHostname)
                {
                    Thread.Sleep(500);
                    Helpers.DropHostname(verbose);
                }
            }

            return(0);
        }
Ejemplo n.º 24
0
 /// <summary>
 ///     Returns a new <see cref="System.Diagnostics.Process" /> component, given the identifier of a process.
 /// </summary>
 /// <param name="processId">The system-unique identifier of a process resource.</param>
 /// <returns>
 ///     A <see cref="System.Diagnostics.Process" /> component that is associated with the local process resource
 ///     identified by the processId parameter.
 /// </returns>
 public static SystemProcess FromProcessId(int processId)
 {
     return(SystemProcess.GetProcessById(processId));
 }