/// <summary>
        /// 连接远程计算机,并附加到进程
        /// </summary>
        /// <param name="ip">远程计算机ip</param>
        /// <param name="remotePort">远程调试工具的端口</param>
        /// <returns></returns>
        public static bool AttachProcess(DTE2 dte, string ip, string remotePort)
        {
            Debugger2 debug = (Debugger2)dte.Debugger;

            DteTransport = debug.Transports.Item(2);
            Processes processes = debug.GetProcesses(DteTransport, ip + ":" + remotePort);

            Logger.Instance.Info("成功连接到远程计算机,并获取远程目标机上所有进程");
            bool found = false;

            foreach (Process2 process in processes)
            {
                if (process.ProcessID == int.Parse(RemoteDebug.PidString))
                {
                    foreach (Engine engine in DteTransport.Engines)
                    {
                        //{FB0D4648-F776-4980-95F8-BB7F36EBC1EE}这是托管4.5模式下的调试器
                        if (new[] { "{FB0D4648-F776-4980-95F8-BB7F36EBC1EE}", }.Any(temp => string.Equals(engine.ID, temp)))
                        {
                            process.Attach2(new[] { engine });
                        }
                    }
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                MessageBox.Show("Selected processes are not running. Try to run your application first.", "Debug Attach History Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }
            return(true);
        }
Ejemplo n.º 2
0
        private void OnProcessComboGetList(object sender, EventArgs e)
        {
            if ((null == e) || (e == EventArgs.Empty))
            {
                // --- We should never get here; EventArgs are required.
                throw (new ArgumentNullException(Resources.EventArgsRequired));
            }
            OleMenuCmdEventArgs eventArgs = e as OleMenuCmdEventArgs;

            if (eventArgs == null)
            {
                throw (new ArgumentException(Resources.EventArgsRequired));
            }

            if (eventArgs.InValue != null)
            {
                throw (new ArgumentException(Resources.ParamNull));
            }

            if (eventArgs.OutValue != IntPtr.Zero)
            {
                DTE       dte       = (DTE)this.GetService(typeof(DTE));
                Debugger2 debugger  = dte.Debugger as Debugger2;
                Processes processes = debugger.GetProcesses(m_Transport, m_Qualifier);

                m_ProcessNames.Clear();
                foreach (Process p in processes)
                {
                    m_ProcessNames.Add(p.Name);
                }
                Marshal.GetNativeVariantForObject(m_ProcessNames.ToArray(), eventArgs.OutValue);
            }
        }
Ejemplo n.º 3
0
        private static EnvDTE.Processes GetDebugProcesses(string remoteServer, long?remoteServerPort)
        {
            if (string.IsNullOrEmpty(remoteServer))
            {
                return(((Debugger2)DebugAttachManagerPackage.DTE.Debugger).LocalProcesses);
            }
            Debugger2 db    = (Debugger2)DebugAttachManagerPackage.DTE.Debugger;
            Transport trans = db.Transports.Item("Default");

            return(db.GetProcesses(trans, remoteServerPort == null ? remoteServer : $"{remoteServer}:{remoteServerPort}"));
        }
Ejemplo n.º 4
0
        private void ConnectOnClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtServerName.Text))
            {
                MessageBox.Show("Server name is required.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (PortNumber == -1)
            {
                MessageBox.Show("Invalid port number.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            Debugger2 db    = (Debugger2)DebugAttachManagerPackage.DTE.Debugger;
            Transport trans = db.Transports.Item("Default");

            try
            {
                db.GetProcesses(trans, PortNumber == null ? txtServerName.Text : $"{txtServerName.Text}:{_portNumber}");
            }
            catch
            {
                MessageBox.Show($"Unable to connect to {txtServerName.Text}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            ConnectionOptions options = new ConnectionOptions
            {
                Impersonation    = ImpersonationLevel.Default,
                EnablePrivileges = true,
                Authentication   = AuthenticationLevel.PacketPrivacy
            };

            var scope = new ManagementScope($@"\\{txtServerName.Text}\root\cimv2", options);

            try
            {
                scope.Connect();
            }
            catch
            {
                MessageBoxResult result = MessageBox.Show($"Unable to connect to {txtServerName.Text} WMI service. Please check permissions. You can use WBEMTest.exe to test your WMI access. If you are not in a Domain, UAC on remote machine will prevent remote access.", "Warning", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                if (result == MessageBoxResult.Cancel)
                {
                    return;
                }
            }

            DialogResult = true;
            Settings.Default.RemoteServer = txtServerName.Text;
            Settings.Default.Save();
            Close();
        }
Ejemplo n.º 5
0
        private void Execute()
        {
            var model = ShowWacProcessesList();

            if (model == null || !model.SelectedProcesses.Any())
            {
                return;
            }

            model.DebuggerEngines.PersistSelectionToRegistry();

            Processes envProcesses;

            if (model.Host == Environment.MachineName)
            {
                envProcesses = _dte.Debugger.LocalProcesses;
            }
            else
            {
                Debugger2 debugger           = (Debugger2)_dte.Debugger;
                Transport transport          = debugger.Transports.Item("Remote (No Authentication)");
                string    transportQualifier = model.Host;
                if (!string.IsNullOrWhiteSpace(model.Port))
                {
                    transportQualifier += ":" + model.Port;
                }
                envProcesses = debugger.GetProcesses(transport, transportQualifier);
            }

            var manuallySelectedDebuggerEngineIds = model.DebuggerEngines.ManuallySelectedEngines.Select(debuggerEngine => debuggerEngine.ID).ToArray();
            var selectedProcesses = envProcesses.Cast <Process2>().Where(p => model.SelectedProcesses.Contains(p.ProcessID));

            foreach (var process in selectedProcesses)
            {
                if (model.DebuggerEngines.IsAutomatic)
                {
                    process.Attach();
                }
                else
                {
                    process.Attach2(manuallySelectedDebuggerEngineIds);
                }
            }
        }
Ejemplo n.º 6
0
        private void OnAttach(object sender, EventArgs e)
        {
            try {
                DTE       dte       = (DTE)this.GetService(typeof(DTE));
                Debugger2 debugger  = dte.Debugger as Debugger2;
                Processes processes = debugger.GetProcesses(m_Transport, m_Qualifier);

                Process process = null;

                try {
                    process = processes.Item(m_ProcessName);
                } catch (System.ArgumentException) {
                    throw (new System.Exception(Resources.ProcessNameNotFound));
                }

                process.Attach();
            } catch (System.Exception ex) {
                CallMessageBox(ex.Message);
            }
        }
Ejemplo n.º 7
0
        public bool AttachToProcess(int processId)
        {
            Debugger2 dbg   = _dteReference.Debugger as Debugger2;
            Transport trans = dbg.Transports.Item("Default");
            Engine    eng;

            eng = trans.Engines.Item("Managed");

            try
            {
                var processes = dbg.GetProcesses(trans, "");

                foreach (EnvDTE80.Process2 process in processes)
                {
                    try
                    {
                        int    pid  = process.ProcessID;
                        string name = process.Name;

                        if (process.ProcessID == processId)
                        {
                            process.Attach2(eng);

                            return(true);
                        }
                    }
                    catch { }
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Invalid index."))
                {
                    return(false);
                }
            }

            return(false);
        }
Ejemplo n.º 8
0
        private static IEnumerable <ProcessExt> GetProcesses(string remoteServer, long?remoteServerPort)
        {
            var result = new List <ProcessExt>();

            if (string.IsNullOrEmpty(remoteServer))
            {
                foreach (EnvDTE.Process p in ((Debugger2)DebugAttachManagerPackage.DTE.Debugger).LocalProcesses)
                {
                    result.Add(new ProcessExt(p.Name, p.ProcessID, remoteServer, remoteServerPort));
                }
            }
            else
            {
                Debugger2 db    = (Debugger2)DebugAttachManagerPackage.DTE.Debugger;
                Transport trans = db.Transports.Item("Default");

                foreach (EnvDTE.Process p in db.GetProcesses(trans, remoteServerPort == null ? remoteServer : $"{remoteServer}:{remoteServerPort}"))
                {
                    result.Add(new ProcessExt(p.Name, p.ProcessID, remoteServer, remoteServerPort));
                }
            }
            return(result);
        }
Ejemplo n.º 9
0
        public bool ReAttach(ReAttachTarget target)
        {
            if (target == null)
            {
                return(false);
            }
            List <Process3> candidates;

            if (!target.IsLocal)
            {
                var transport = _dteDebugger.Transports.Item("Default");
                var processes = _dteDebugger.GetProcesses(transport, target.ServerName).OfType <Process3>();
                candidates = processes.Where(p => p.Name == target.ProcessPath).ToList();
            }
            else
            {
                var processes = _dteDebugger.LocalProcesses.OfType <Process3>();

                var tmp = processes.Select(p => new { Name = p.Name, UserName = p.UserName }).ToArray();
                Console.WriteLine(tmp);

                candidates = processes.Where(p =>
                                             p.Name == target.ProcessPath &&
                                             p.UserName == target.ProcessUser).ToList();

                if (!candidates.Any())                 // Do matching on processes running in exclusive mode.
                {
                    candidates = processes.Where(p =>
                                                 p.Name == target.ProcessName &&
                                                 string.IsNullOrEmpty(p.UserName)).ToList();
                }
            }

            if (!candidates.Any())
            {
                return(false);
            }

            Process3 process = null;             // First try to use the pid.

            if (target.ProcessId > 0)
            {
                process = candidates.FirstOrDefault(p => p.ProcessID == target.ProcessId);
            }

            // If we don't have an exact match, just go for the highest PID matching.
            if (process == null)
            {
                var maxPid = candidates.Max(p => p.ProcessID);
                process = candidates.FirstOrDefault(p => p.ProcessID == maxPid);
            }

            if (process == null)
            {
                return(false);
            }

            try
            {
                if (target.Engines != null && target.Engines.Any())
                {
                    var engines = target.Engines.Where(e => _engines.ContainsKey(e)).Select(e => _engines[e]).ToArray();
                    process.Attach2(engines);
                }
                else
                {
                    process.Attach();
                }
                return(true);
            }
            catch (COMException e)
            {
                _package.Reporter.ReportError("Unable to ReAttach to process {0} ({1}) based on target {2}. Message: {3}.",
                                              process.Name, process.ProcessID, target, e.Message);

                // It's either this or returning this HRESULT to shell with Shell.ReportError method, shows UAC box btw.
                const int E_ELEVATION_REQUIRED = unchecked ((int)0x800702E4);
                Marshal.ThrowExceptionForHR(E_ELEVATION_REQUIRED);
                return(false);
            }
            catch (Exception e)
            {
                _package.Reporter.ReportError("Unable to ReAttach to process {0} ({1}) based on target {2}. Message: {3}.",
                                              process.Name, process.ProcessID, target, e.Message);
            }
            return(false);
        }
Ejemplo n.º 10
0
        public ReAttachResult ReAttach(ReAttachTarget target)
        {
            if (target == null)
            {
                return(ReAttachResult.Failed);
            }

            List <Process3> candidates;

            if (!target.IsLocal)
            {
                var transport = _dteDebugger.Transports.Item("Default");
                var processes = _dteDebugger.GetProcesses(transport, target.ServerName).OfType <Process3>();
                candidates = processes.Where(p => p.IsMatchingRemoteProcess(target)).ToList();
            }
            else
            {
                var processes = _dteDebugger.LocalProcesses.OfType <Process3>();
                candidates = processes.Where(p => p.IsMatchingLocalProcess(target)).ToList();
                if (!candidates.Any()) // Do matching on processes running in exclusive mode.
                {
                    candidates = processes.Where(p => p.IsMatchingExclusively(target)).ToList();
                }
            }

            if (!candidates.Any())
            {
                return(ReAttachResult.NotStarted);
            }

            Process3 process = null; // First try to use the pid.

            if (target.ProcessId > 0)
            {
                process = candidates.FirstOrDefault(p => p.ProcessID == target.ProcessId);
            }

            // If we don't have an exact match, just go for the highest PID matching.
            if (process == null)
            {
                var maxPid = candidates.Max(p => p.ProcessID);
                process = candidates.FirstOrDefault(p => p.ProcessID == maxPid);
            }

            if (process == null)
            {
                return(ReAttachResult.NotStarted);
            }

            try
            {
                if (target.Engines != null && target.Engines.Any())
                {
                    var engines = target.Engines.Where(e => _engines.ContainsKey(e)).Select(e => _engines[e]).ToArray();
                    process.Attach2(engines);
                }
                else
                {
                    process.Attach();
                }
                return(ReAttachResult.Success);
            }
            catch (COMException)
            {
                return(ReAttachResult.ElevationRequired);
            }
            catch (Exception e)
            {
                ReAttachUtils.ShowError($"Unable to ReAttach to process {process.Name} ({process.ProcessID}) based on target {target}", e.Message);
            }
            return(ReAttachResult.Failed);
        }