Пример #1
0
        // Enumerates the code contexts for a given position in a source file.
        public int EnumCodeContexts(IDebugDocumentPosition2 docPosition, out IEnumDebugCodeContexts2 ppEnum)
        {
            string documentName;

            EngineUtils.CheckOk(docPosition.GetFileName(out documentName));

            // Get the location in the document
            TEXT_POSITION[] startPosition = new TEXT_POSITION[1];
            TEXT_POSITION[] endPosition   = new TEXT_POSITION[1];
            EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition));
            List <IDebugCodeContext2> codeContexts = new List <IDebugCodeContext2>();

            List <ulong> addresses = null;
            uint         line      = startPosition[0].dwLine + 1;

            _debuggedProcess.WorkerThread.RunOperation(async() =>
            {
                addresses = await DebuggedProcess.StartAddressesForLine(documentName, line);
            });

            if (addresses != null && addresses.Count > 0)
            {
                foreach (var a in addresses)
                {
                    var           codeCxt = new AD7MemoryAddress(this, a, null);
                    TEXT_POSITION pos;
                    pos.dwLine   = line;
                    pos.dwColumn = 0;
                    MITextPosition textPosition = new MITextPosition(documentName, pos, pos);
                    codeCxt.SetDocumentContext(new AD7DocumentContext(textPosition, codeCxt));
                    codeContexts.Add(codeCxt);
                }
                if (codeContexts.Count > 0)
                {
                    ppEnum = new AD7CodeContextEnum(codeContexts.ToArray());
                    return(Constants.S_OK);
                }
            }
            ppEnum = null;
            return(Constants.E_FAIL);
        }
Пример #2
0
        // Gets the file statement range of the document context.
        // A statement range is the range of the lines that contributed the code to which this document context refers.
        int IDebugDocumentContext2.GetStatementRange(TEXT_POSITION[] pBegPosition, TEXT_POSITION[] pEndPosition)
        {
            try
            {
                pBegPosition[0].dwColumn = _textPosition.BeginPosition.dwColumn;
                pBegPosition[0].dwLine   = _textPosition.BeginPosition.dwLine;

                pEndPosition[0].dwColumn = _textPosition.EndPosition.dwColumn;
                pEndPosition[0].dwLine   = _textPosition.EndPosition.dwLine;
            }
            catch (MIException e)
            {
                return(e.HResult);
            }
            catch (Exception e)
            {
                return(EngineUtils.UnexpectedException(e));
            }

            return(Constants.S_OK);
        }
Пример #3
0
        // Launches a process by means of the debug engine.
        // Normally, Visual Studio launches a program using the IDebugPortEx2::LaunchSuspended method and then attaches the debugger
        // to the suspended program. However, there are circumstances in which the debug engine may need to launch a program
        // (for example, if the debug engine is part of an interpreter and the program being debugged is an interpreted language),
        // in which case Visual Studio uses the IDebugEngineLaunch2::LaunchSuspended method
        // The IDebugEngineLaunch2::ResumeProcess method is called to start the process after the process has been successfully launched in a suspended state.
        int IDebugEngineLaunch2.LaunchSuspended(string pszServer, IDebugPort2 port, string exe, string args, string dir, string env, string options, enum_LAUNCH_FLAGS launchFlags, uint hStdInput, uint hStdOutput, uint hStdError, IDebugEventCallback2 ad7Callback, out IDebugProcess2 process)
        {
            Debug.Assert(_pollThread == null);
            Debug.Assert(_engineCallback == null);
            Debug.Assert(_debuggedProcess == null);
            Debug.Assert(_ad7ProgramId == Guid.Empty);

            // Check if the logger was enabled late.
            Logger.LoadMIDebugLogger(_configStore);

            process = null;

            _engineCallback = new EngineCallback(this, ad7Callback);

            Exception exception;

            try
            {
                bool noDebug = launchFlags.HasFlag(enum_LAUNCH_FLAGS.LAUNCH_NODEBUG);

                // Note: LaunchOptions.GetInstance can be an expensive operation and may push a wait message loop
                LaunchOptions launchOptions = LaunchOptions.GetInstance(_configStore, exe, args, dir, options, noDebug, _engineCallback, TargetEngine.Native, Logger);

                StartDebugging(launchOptions);

                EngineUtils.RequireOk(port.GetProcess(_debuggedProcess.Id, out process));
                return(Constants.S_OK);
            }
            catch (Exception e) when(ExceptionHelper.BeforeCatch(e, Logger, reportOnlyCorrupting: true))
            {
                exception = e;
                // Return from the catch block so that we can let the exception unwind - the stack can get kind of big
            }

            // If we just return the exception as an HRESULT, we will lose our message, so we instead send up an error event, and then
            // return E_ABORT.
            OnStartDebuggingFailed(exception);

            return(Constants.E_ABORT);
        }
Пример #4
0
        // Get the document context for this pending breakpoint. A document context is a abstract representation of a source file
        // location.
        public AD7DocumentContext GetDocumentContext(ulong address, string functionName)
        {
            if ((enum_BP_LOCATION_TYPE)_bpRequestInfo.bpLocation.bpLocationType == enum_BP_LOCATION_TYPE.BPLT_CODE_FILE_LINE)
            {
                IDebugDocumentPosition2 docPosition = HostMarshal.GetDocumentPositionForIntPtr(_bpRequestInfo.bpLocation.unionmember2);
                string documentName;
                EngineUtils.CheckOk(docPosition.GetFileName(out documentName));

                // Get the location in the document that the breakpoint is in.
                TEXT_POSITION[] startPosition = new TEXT_POSITION[1];
                TEXT_POSITION[] endPosition   = new TEXT_POSITION[1];
                EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition));

                AD7MemoryAddress codeContext = new AD7MemoryAddress(_engine, address, functionName);

                return(new AD7DocumentContext(new MITextPosition(documentName, startPosition[0], startPosition[0]), codeContext, _engine.DebuggedProcess));
            }
            else
            {
                return(null);
            }
        }
Пример #5
0
        // Determines whether the next statement can be set to the given stack frame and code context.
        int IDebugThread2.CanSetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext)
        {
            ulong         addr  = ((AD7MemoryAddress)codeContext).Address;
            AD7StackFrame frame = ((AD7StackFrame)stackFrame);

            if (frame.ThreadContext.Level != 0 || frame.Thread != this || !frame.ThreadContext.pc.HasValue)
            {
                return(Constants.S_FALSE);
            }
            if (addr == frame.ThreadContext.pc)
            {
                return(Constants.S_OK);
            }
            string toFunc   = EngineUtils.GetAddressDescription(_engine.DebuggedProcess, addr);
            string fromFunc = EngineUtils.GetAddressDescription(_engine.DebuggedProcess, frame.ThreadContext.pc.Value);

            if (toFunc != fromFunc)
            {
                return(Constants.S_FALSE);
            }
            return(Constants.S_OK);
        }
Пример #6
0
        private void SendStartDebuggingError(Exception exception)
        {
            if (exception is OperationCanceledException)
            {
                return; // don't show a message in this case
            }

            string description = EngineUtils.GetExceptionDescription(exception);
            string message     = string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_UnableToStartDebugging, description);

            var initializationException = exception as MIDebuggerInitializeFailedException;

            if (initializationException != null)
            {
                string outputMessage = string.Join("\r\n", initializationException.OutputLines) + "\r\n";

                // NOTE: We can't write to the output window by sending an AD7 event because this may be called before the session create event
                HostOutputWindow.WriteLaunchError(outputMessage);
            }

            _engineCallback.OnErrorImmediate(message);
        }
Пример #7
0
        // Determines whether the next statement can be set to the given stack frame and code context.
        int IDebugThread2.CanSetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext)
        {
            // CLRDBG TODO: This implementation should be changed to compare the method token
            ulong         addr  = ((AD7MemoryAddress)codeContext).Address;
            AD7StackFrame frame = ((AD7StackFrame)stackFrame);

            if (frame.ThreadContext.Level != 0 || frame.Thread != this || !frame.ThreadContext.pc.HasValue || _engine.DebuggedProcess.MICommandFactory.Mode == MIMode.Clrdbg)
            {
                return(Constants.S_FALSE);
            }
            if (addr == frame.ThreadContext.pc)
            {
                return(Constants.S_OK);
            }
            string toFunc   = EngineUtils.GetAddressDescription(_engine.DebuggedProcess, addr);
            string fromFunc = EngineUtils.GetAddressDescription(_engine.DebuggedProcess, frame.ThreadContext.pc.Value);

            if (toFunc != fromFunc)
            {
                return(Constants.S_FALSE);
            }
            return(Constants.S_OK);
        }
Пример #8
0
        // this is inefficient so we try and grab everything in one gulp
        internal static async Task <DisasmInstruction[]> Disassemble(DebuggedProcess process, ulong startAddr, ulong endAddr)
        {
            string  cmd     = "-data-disassemble -s " + EngineUtils.AsAddr(startAddr, process.Is64BitArch) + " -e " + EngineUtils.AsAddr(endAddr, process.Is64BitArch) + " -- 2";
            Results results = await process.CmdAsync(cmd, ResultClass.None);

            if (results.ResultClass != ResultClass.done)
            {
                return(null);
            }

            return(DecodeDisassemblyInstructions(results.Find <ValueListValue>("asm_insns").AsArray <TupleValue>()));
        }
Пример #9
0
 public string GetAddressDescription(ulong ip)
 {
     return(EngineUtils.GetAddressDescription(_debuggedProcess, ip));
 }
Пример #10
0
        // Launches a process by means of the debug engine.
        // Normally, Visual Studio launches a program using the IDebugPortEx2::LaunchSuspended method and then attaches the debugger
        // to the suspended program. However, there are circumstances in which the debug engine may need to launch a program
        // (for example, if the debug engine is part of an interpreter and the program being debugged is an interpreted language),
        // in which case Visual Studio uses the IDebugEngineLaunch2::LaunchSuspended method
        // The IDebugEngineLaunch2::ResumeProcess method is called to start the process after the process has been successfully launched in a suspended state.
        int IDebugEngineLaunch2.LaunchSuspended(string pszServer, IDebugPort2 port, string exe, string args, string dir, string env, string options, enum_LAUNCH_FLAGS launchFlags, uint hStdInput, uint hStdOutput, uint hStdError, IDebugEventCallback2 ad7Callback, out IDebugProcess2 process)
        {
            Debug.Assert(_pollThread == null);
            Debug.Assert(_engineCallback == null);
            Debug.Assert(_debuggedProcess == null);
            Debug.Assert(_ad7ProgramId == Guid.Empty);

            process = null;

            _engineCallback = new EngineCallback(this, ad7Callback);

            Exception exception;

            try
            {
                // Note: LaunchOptions.GetInstance can be an expensive operation and may push a wait message loop
                LaunchOptions launchOptions = LaunchOptions.GetInstance(_registryRoot, exe, args, dir, options, _engineCallback);

                // We are being asked to debug a process when we currently aren't debugging anything
                _pollThread = new WorkerThread();
                var cancellationTokenSource = new CancellationTokenSource();

                using (cancellationTokenSource)
                {
                    _pollThread.RunOperation(ResourceStrings.InitializingDebugger, cancellationTokenSource, (MICore.WaitLoop waitLoop) =>
                    {
                        try
                        {
                            _debuggedProcess = new DebuggedProcess(true, launchOptions, _engineCallback, _pollThread, _breakpointManager, this);
                        }
                        finally
                        {
                            // If there is an exception from the DebuggeedProcess constructor, it is our responsibility to dispose the DeviceAppLauncher,
                            // otherwise the DebuggedProcess object takes ownership.
                            if (_debuggedProcess == null && launchOptions.DeviceAppLauncher != null)
                            {
                                launchOptions.DeviceAppLauncher.Dispose();
                            }
                        }

                        _pollThread.PostedOperationErrorEvent += _debuggedProcess.OnPostedOperationError;

                        return(_debuggedProcess.Initialize(waitLoop, cancellationTokenSource.Token));
                    });
                }

                EngineUtils.RequireOk(port.GetProcess(_debuggedProcess.Id, out process));

                return(Constants.S_OK);
            }
            catch (Exception e)
            {
                exception = e;
                // Return from the catch block so that we can let the exception unwind - the stack can get kind of big
            }

            // If we just return the exception as an HRESULT, we will loose our message, so we instead send up an error event, and then
            // return E_ABORT.
            Logger.Flush();
            SendStartDebuggingError(exception);

            Dispose();

            return(Constants.E_ABORT);
        }
Пример #11
0
        public DebuggedProcess(bool bLaunched, LaunchOptions launchOptions, ISampleEngineCallback callback, WorkerThread worker, BreakpointManager bpman, AD7Engine engine)
        {
            uint processExitCode = 0;

            g_Process          = this;
            _bStarted          = false;
            _pendingMessages   = new StringBuilder(400);
            _worker            = worker;
            _launchOptions     = launchOptions;
            _breakpointManager = bpman;
            Engine             = engine;
            _libraryLoaded     = new List <string>();
            _loadOrder         = 0;
            MICommandFactory   = MICommandFactory.GetInstance(launchOptions.DebuggerMIMode, this);
            _waitDialog        = MICommandFactory.SupportsStopOnDynamicLibLoad() ? new WaitDialog(ResourceStrings.LoadingSymbolMessage, ResourceStrings.LoadingSymbolCaption) : null;
            Natvis             = new Natvis.Natvis(this);

            // we do NOT have real Win32 process IDs, so we use a guid
            AD_PROCESS_ID pid = new AD_PROCESS_ID();

            pid.ProcessIdType = (int)enum_AD_PROCESS_ID.AD_PROCESS_ID_GUID;
            pid.guidProcessId = Guid.NewGuid();
            this.Id           = pid;

            SourceLineCache = new SourceLineCache(this);

            _callback   = callback;
            _moduleList = new List <DebuggedModule>();
            ThreadCache = new ThreadCache(callback, this);
            Disassembly = new Disassembly(this);

            VariablesToDelete = new List <string>();

            MessageEvent += delegate(object o, string message)
            {
                // We can get messages before we have started the process
                // but we can't send them on until it is
                if (_bStarted)
                {
                    _callback.OnOutputString(message);
                }
                else
                {
                    _pendingMessages.Append(message);
                }
            };

            LibraryLoadEvent += delegate(object o, EventArgs args)
            {
                ResultEventArgs results = args as MICore.Debugger.ResultEventArgs;
                string          file    = results.Results.TryFindString("host-name");
                if (!string.IsNullOrEmpty(file) && MICommandFactory.SupportsStopOnDynamicLibLoad())
                {
                    _libraryLoaded.Add(file);
                    if (_waitDialog != null)
                    {
                        _waitDialog.ShowWaitDialog(file);
                    }
                }
                else if (this.MICommandFactory.Mode == MIMode.Clrdbg)
                {
                    string id            = results.Results.FindString("id");
                    ulong  baseAddr      = results.Results.FindAddr("base-address");
                    uint   size          = results.Results.FindUint("size");
                    bool   symbolsLoaded = results.Results.FindInt("symbols-loaded") != 0;
                    var    module        = new DebuggedModule(id, file, baseAddr, size, symbolsLoaded, string.Empty, _loadOrder++);
                    lock (_moduleList)
                    {
                        _moduleList.Add(module);
                    }
                    _callback.OnModuleLoad(module);
                }
                else if (!string.IsNullOrEmpty(file))
                {
                    string addr = results.Results.TryFindString("loaded_addr");
                    if (string.IsNullOrEmpty(addr) || addr == "-")
                    {
                        return; // identifies the exe, not a real load
                    }
                    // generate module
                    string id         = results.Results.TryFindString("name");
                    bool   symsLoaded = true;
                    string symPath    = null;
                    if (results.Results.Contains("symbols-path"))
                    {
                        symPath = results.Results.FindString("symbols-path");
                        if (string.IsNullOrEmpty(symPath))
                        {
                            symsLoaded = false;
                        }
                    }
                    else
                    {
                        symPath = file;
                    }
                    ulong loadAddr = results.Results.FindAddr("loaded_addr");
                    uint  size     = results.Results.FindUint("size");
                    if (String.IsNullOrEmpty(id))
                    {
                        id = file;
                    }
                    var module = FindModule(id);
                    if (module == null)
                    {
                        module = new DebuggedModule(id, file, loadAddr, size, symsLoaded, symPath, _loadOrder++);
                        lock (_moduleList)
                        {
                            _moduleList.Add(module);
                        }
                        _callback.OnModuleLoad(module);
                    }
                }
            };

            if (_launchOptions is LocalLaunchOptions)
            {
                this.Init(new MICore.LocalTransport(), _launchOptions);
            }
            else if (_launchOptions is PipeLaunchOptions)
            {
                this.Init(new MICore.PipeTransport(), _launchOptions);
            }
            else if (_launchOptions is TcpLaunchOptions)
            {
                this.Init(new MICore.TcpTransport(), _launchOptions);
            }
            else if (_launchOptions is SerialLaunchOptions)
            {
                string port = ((SerialLaunchOptions)_launchOptions).Port;
                this.Init(new MICore.SerialTransport(port), _launchOptions);
            }
            else
            {
                throw new ArgumentOutOfRangeException("LaunchInfo.options");
            }

            MIDebugCommandDispatcher.AddProcess(this);

            // When the debuggee exits, we need to exit the debugger
            ProcessExitEvent += delegate(object o, EventArgs args)
            {
                // NOTE: Exceptions leaked from this method may cause VS to crash, be careful

                ResultEventArgs results = args as MICore.Debugger.ResultEventArgs;

                if (results.Results.Contains("exit-code"))
                {
                    processExitCode = results.Results.FindUint("exit-code");
                }

                // quit MI Debugger
                _worker.PostOperation(CmdExitAsync);
                if (_waitDialog != null)
                {
                    _waitDialog.EndWaitDialog();
                }
            };

            // When the debugger exits, we tell AD7 we are done
            DebuggerExitEvent += delegate(object o, EventArgs args)
            {
                // NOTE: Exceptions leaked from this method may cause VS to crash, be careful

                // this is the last AD7 Event we can ever send
                // Also the transport is closed when this returns
                _callback.OnProcessExit(processExitCode);

                Dispose();
            };

            DebuggerAbortedEvent += delegate(object o, EventArgs args)
            {
                // NOTE: Exceptions leaked from this method may cause VS to crash, be careful

                // The MI debugger process unexpectedly exited.
                _worker.PostOperation(() =>
                {
                    // If the MI Debugger exits before we get a resume call, we have no way of sending program destroy. So just let start debugging fail.
                    if (!_connected)
                    {
                        return;
                    }

                    _callback.OnError(MICoreResources.Error_MIDebuggerExited);
                    _callback.OnProcessExit(uint.MaxValue);

                    Dispose();
                });
            };

            ModuleLoadEvent += async delegate(object o, EventArgs args)
            {
                // NOTE: This is an async void method, so make sure exceptions are caught and somehow reported

                if (_libraryLoaded.Count != 0)
                {
                    string moduleNames = string.Join(", ", _libraryLoaded);

                    try
                    {
                        _libraryLoaded.Clear();
                        SourceLineCache.OnLibraryLoad();

                        await _breakpointManager.BindAsync();
                        await CheckModules();

                        _bLastModuleLoadFailed = false;
                    }
                    catch (Exception e)
                    {
                        if (this.ProcessState == MICore.ProcessState.Exited)
                        {
                            return; // ignore exceptions after the process has exited
                        }

                        string exceptionDescription = EngineUtils.GetExceptionDescription(e);
                        string message = string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_ExceptionProcessingModules, moduleNames, exceptionDescription);

                        // to avoid spamming the user, if the last module failed, we send the next failure to the output windiw instead of a message box
                        if (!_bLastModuleLoadFailed)
                        {
                            _callback.OnError(message);
                            _bLastModuleLoadFailed = true;
                        }
                        else
                        {
                            _callback.OnOutputMessage(message, enum_MESSAGETYPE.MT_OUTPUTSTRING);
                        }
                    }
                }
                if (_waitDialog != null)
                {
                    _waitDialog.EndWaitDialog();
                }
                if (MICommandFactory.SupportsStopOnDynamicLibLoad())
                {
                    CmdContinueAsync();
                }
            };

            // When we break we need to gather information
            BreakModeEvent += async delegate(object o, EventArgs args)
            {
                // NOTE: This is an async void method, so make sure exceptions are caught and somehow reported

                ResultEventArgs results = args as MICore.Debugger.ResultEventArgs;
                if (_waitDialog != null)
                {
                    _waitDialog.EndWaitDialog();
                }

                if (!this._connected)
                {
                    _initialBreakArgs = results;
                    return;
                }

                try
                {
                    await HandleBreakModeEvent(results);
                }
                catch (Exception e)
                {
                    if (this.ProcessState == MICore.ProcessState.Exited)
                    {
                        return; // ignore exceptions after the process has exited
                    }

                    string exceptionDescription = EngineUtils.GetExceptionDescription(e);
                    string message = string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_FailedToEnterBreakState, exceptionDescription);
                    _callback.OnError(message);

                    Terminate();
                }
            };

            RunModeEvent += delegate(object o, EventArgs args)
            {
                // NOTE: Exceptions leaked from this method may cause VS to crash, be careful

                if (!_bStarted)
                {
                    _bStarted = true;

                    // Send any strings we got before the process came up
                    if (_pendingMessages.Length != 0)
                    {
                        try
                        {
                            _callback.OnOutputString(_pendingMessages.ToString());
                        }
                        catch
                        {
                            // If something goes wrong sending the output, lets not crash VS
                        }
                    }
                    _pendingMessages = null;
                }
            };

            ErrorEvent += delegate(object o, EventArgs args)
            {
                // NOTE: Exceptions leaked from this method may cause VS to crash, be careful

                ResultEventArgs result = (ResultEventArgs)args;
                _callback.OnError(result.Results.FindString("msg"));
            };

            ThreadCreatedEvent += delegate(object o, EventArgs args)
            {
                ResultEventArgs result = (ResultEventArgs)args;
                ThreadCache.ThreadEvent(result.Results.FindInt("id"), /*deleted */ false);
            };

            ThreadExitedEvent += delegate(object o, EventArgs args)
            {
                ResultEventArgs result = (ResultEventArgs)args;
                ThreadCache.ThreadEvent(result.Results.FindInt("id"), /*deleted*/ true);
            };

            BreakChangeEvent += _breakpointManager.BreakpointModified;
        }
Пример #12
0
        internal async Task BindAsync()
        {
            if (CanBind())
            {
                string          documentName  = null;
                string          functionName  = null;
                TEXT_POSITION[] startPosition = new TEXT_POSITION[1];
                TEXT_POSITION[] endPosition   = new TEXT_POSITION[1];
                string          condition     = null;

                lock (_boundBreakpoints)
                {
                    if (_bp != null)   // already bound
                    {
                        Debug.Fail("Breakpoint already bound");
                        return;
                    }
                    if ((_bpRequestInfo.dwFields & enum_BPREQI_FIELDS.BPREQI_BPLOCATION) != 0)
                    {
                        if (_bpRequestInfo.bpLocation.bpLocationType == (uint)enum_BP_LOCATION_TYPE.BPLT_CODE_FUNC_OFFSET)
                        {
                            IDebugFunctionPosition2 functionPosition = HostMarshal.GetDebugFunctionPositionForIntPtr(_bpRequestInfo.bpLocation.unionmember2);
                            EngineUtils.CheckOk(functionPosition.GetFunctionName(out functionName));
                        }
                        else if (_bpRequestInfo.bpLocation.bpLocationType == (uint)enum_BP_LOCATION_TYPE.BPLT_CODE_FILE_LINE)
                        {
                            IDebugDocumentPosition2 docPosition = HostMarshal.GetDocumentPositionForIntPtr(_bpRequestInfo.bpLocation.unionmember2);

                            // Get the name of the document that the breakpoint was put in
                            EngineUtils.CheckOk(docPosition.GetFileName(out documentName));

                            // Get the location in the document that the breakpoint is in.
                            EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition));
                        }
                    }
                    if ((_bpRequestInfo.dwFields & enum_BPREQI_FIELDS.BPREQI_CONDITION) != 0 &&
                        _bpRequestInfo.bpCondition.styleCondition == enum_BP_COND_STYLE.BP_COND_WHEN_TRUE)
                    {
                        condition = _bpRequestInfo.bpCondition.bstrCondition;
                    }
                }
                PendingBreakpoint.BindResult bindResult;
                // Bind all breakpoints that match this source and line number.
                if (documentName != null)
                {
                    bindResult = await PendingBreakpoint.Bind(documentName, startPosition[0].dwLine + 1, startPosition[0].dwColumn, _engine.DebuggedProcess, condition, this);
                }
                else
                {
                    bindResult = await PendingBreakpoint.Bind(functionName, _engine.DebuggedProcess, condition, this);
                }

                lock (_boundBreakpoints)
                {
                    if (bindResult.PendingBreakpoint != null)
                    {
                        _bp = bindResult.PendingBreakpoint;    // an MI breakpoint object exists: TODO: lock?
                    }
                    if (bindResult.BoundBreakpoints == null || bindResult.BoundBreakpoints.Count == 0)
                    {
                        _BPError = new AD7ErrorBreakpoint(this, bindResult.ErrorMessage);
                        _engine.Callback.OnBreakpointError(_BPError);
                    }
                    else
                    {
                        Debug.Assert(_bp != null);
                        foreach (BoundBreakpoint bp in bindResult.BoundBreakpoints)
                        {
                            AddBoundBreakpoint(bp);
                        }
                    }
                }
            }
        }
Пример #13
0
        // Retrieves a list of the stack frames for this thread.
        // For the sample engine, enumerating the stack frames requires walking the callstack in the debuggee for this thread
        // and coverting that to an implementation of IEnumDebugFrameInfo2.
        // Real engines will most likely want to cache this information to avoid recomputing it each time it is asked for,
        // and or construct it on demand instead of walking the entire stack.
        int IDebugThread2.EnumFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, out IEnumDebugFrameInfo2 enumObject)
        {
            enumObject = null;
            try
            {
                uint radix = _engine.CurrentRadix();
                if (radix != _engine.DebuggedProcess.MICommandFactory.Radix)
                {
                    _engine.DebuggedProcess.WorkerThread.RunOperation(async() =>
                    {
                        await _engine.UpdateRadixAsync(radix);
                    });
                }

                // get the thread's stack frames
                System.Collections.Generic.List <ThreadContext> stackFrames = null;
                _engine.DebuggedProcess.WorkerThread.RunOperation(async() => stackFrames = await _engine.DebuggedProcess.ThreadCache.StackFrames(_debuggedThread));
                int         numStackFrames = stackFrames != null ? stackFrames.Count : 0;
                FRAMEINFO[] frameInfoArray;

                if (numStackFrames == 0)
                {
                    // failed to walk any frames. Return an empty stack.
                    frameInfoArray = new FRAMEINFO[0];
                }
                else
                {
                    uint low  = stackFrames[0].Level;
                    uint high = stackFrames[stackFrames.Count - 1].Level;
                    FilterUnknownFrames(stackFrames);
                    numStackFrames = stackFrames.Count;
                    frameInfoArray = new FRAMEINFO[numStackFrames];
                    List <ArgumentList> parameters = null;

                    if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS) != 0 && !_engine.DebuggedProcess.MICommandFactory.SupportsFrameFormatting)
                    {
                        _engine.DebuggedProcess.WorkerThread.RunOperation(async() => parameters = await _engine.DebuggedProcess.GetParameterInfoOnly(this, (dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_VALUES) != 0,
                                                                                                                                                     (dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_TYPES) != 0, low, high));
                    }

                    for (int i = 0; i < numStackFrames; i++)
                    {
                        var p = parameters != null?parameters.Find((ArgumentList t) => t.Item1 == stackFrames[i].Level) : null;

                        AD7StackFrame frame = new AD7StackFrame(_engine, this, stackFrames[i]);
                        frame.SetFrameInfo(dwFieldSpec, out frameInfoArray[i], p != null ? p.Item2 : null);
                    }
                }

                enumObject = new AD7FrameInfoEnum(frameInfoArray);
                return(Constants.S_OK);
            }
            catch (MIException e)
            {
                return(e.HResult);
            }
            catch (Exception e)
            {
                return(EngineUtils.UnexpectedException(e));
            }
        }
Пример #14
0
        // Gets the MODULE_INFO that describes this module.
        // This is how the debugger obtains most of the information about the module.
        int IDebugModule2.GetInfo(enum_MODULE_INFO_FIELDS dwFields, MODULE_INFO[] infoArray)
        {
            try
            {
                MODULE_INFO info = new MODULE_INFO();

                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_NAME) != 0)
                {
                    info.m_bstrName     = System.IO.Path.GetFileName(this.DebuggedModule.Name);
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_NAME;
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_URL) != 0)
                {
                    info.m_bstrUrl      = this.DebuggedModule.Name;
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_URL;
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_LOADADDRESS) != 0)
                {
                    info.m_addrLoadAddress = (ulong)this.DebuggedModule.BaseAddress;
                    info.dwValidFields    |= enum_MODULE_INFO_FIELDS.MIF_LOADADDRESS;
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_PREFFEREDADDRESS) != 0)
                {
                    // A debugger that actually supports showing the preferred base should read the PE header and get
                    // that field. This debugger does not do that, so assume the module loaded where it was suppose to.
                    info.m_addrPreferredLoadAddress = (ulong)this.DebuggedModule.BaseAddress;
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_PREFFEREDADDRESS;;
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_SIZE) != 0)
                {
                    info.m_dwSize       = (uint)this.DebuggedModule.Size;
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_SIZE;
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_LOADORDER) != 0)
                {
                    info.m_dwLoadOrder  = this.DebuggedModule.GetLoadOrder();
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_LOADORDER;
                }
                if (this.Process.LaunchOptions is LocalLaunchOptions localLaunchOptions &&
                    string.IsNullOrWhiteSpace(localLaunchOptions.MIDebuggerServerAddress) && string.IsNullOrWhiteSpace(localLaunchOptions.DebugServer) &&
                    (dwFields & enum_MODULE_INFO_FIELDS.MIF_TIMESTAMP) != 0 &&
                    this.DebuggedModule.Name != null)
                {
                    try
                    {
                        long ft   = File.GetLastWriteTimeUtc(this.DebuggedModule.Name).ToFileTime();
                        uint low  = (uint)(ft & 0xFFFFFFFF);
                        uint high = (uint)((ulong)(ft >> 32));
                        info.m_TimeStamp = new FILETIME()
                        {
                            dwLowDateTime  = low,
                            dwHighDateTime = high
                        };
                        info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_TIMESTAMP;
                    } catch {}
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_URLSYMBOLLOCATION) != 0)
                {
                    if (this.DebuggedModule.SymbolsLoaded)
                    {
                        info.m_bstrUrlSymbolLocation = this.DebuggedModule.SymbolPath;
                        info.dwValidFields          |= enum_MODULE_INFO_FIELDS.MIF_URLSYMBOLLOCATION;
                    }
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_FLAGS) != 0)
                {
                    info.m_dwModuleFlags = 0;
                    if (this.DebuggedModule.SymbolsLoaded)
                    {
                        info.m_dwModuleFlags |= (enum_MODULE_FLAGS.MODULE_FLAG_SYMBOLS);
                    }

                    if (this.Process.Is64BitArch)
                    {
                        info.m_dwModuleFlags |= enum_MODULE_FLAGS.MODULE_FLAG_64BIT;
                    }

                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_FLAGS;
                }


                infoArray[0] = info;

                return(Constants.S_OK);
            }
            catch (MIException e)
            {
                return(e.HResult);
            }
            catch (Exception e)
            {
                return(EngineUtils.UnexpectedException(e));
            }
        }
Пример #15
0
        internal async Task BindAsync()
        {
            if (CanBind())
            {
                string                 documentName  = null;
                string                 functionName  = null;
                TEXT_POSITION[]        startPosition = new TEXT_POSITION[1];
                TEXT_POSITION[]        endPosition   = new TEXT_POSITION[1];
                string                 condition     = null;
                string                 address       = null;
                ulong                  codeAddress   = 0;
                uint                   size          = 0;
                IEnumerable <Checksum> checksums     = null;

                lock (_boundBreakpoints)
                {
                    if (_bp != null)   // already bound
                    {
                        Debug.Fail("Breakpoint already bound");
                        return;
                    }
                    if ((_bpRequestInfo.dwFields & enum_BPREQI_FIELDS.BPREQI_CONDITION) != 0 &&
                        _bpRequestInfo.bpCondition.styleCondition == enum_BP_COND_STYLE.BP_COND_WHEN_TRUE)
                    {
                        condition = _bpRequestInfo.bpCondition.bstrCondition;
                    }
                    if ((_bpRequestInfo.dwFields & enum_BPREQI_FIELDS.BPREQI_BPLOCATION) != 0)
                    {
                        switch ((enum_BP_LOCATION_TYPE)_bpRequestInfo.bpLocation.bpLocationType)
                        {
                        case enum_BP_LOCATION_TYPE.BPLT_CODE_FUNC_OFFSET:
                        {
                            IDebugFunctionPosition2 functionPosition = HostMarshal.GetDebugFunctionPositionForIntPtr(_bpRequestInfo.bpLocation.unionmember2);
                            EngineUtils.CheckOk(functionPosition.GetFunctionName(out functionName));
                            break;
                        }

                        case enum_BP_LOCATION_TYPE.BPLT_CODE_CONTEXT:
                        {
                            IDebugCodeContext2 codePosition = HostMarshal.GetDebugCodeContextForIntPtr(_bpRequestInfo.bpLocation.unionmember1);
                            if (!(codePosition is AD7MemoryAddress))
                            {
                                goto default;           // context is not from this engine
                            }
                            codeAddress = ((AD7MemoryAddress)codePosition).Address;
                            break;
                        }

                        case enum_BP_LOCATION_TYPE.BPLT_CODE_FILE_LINE:
                        {
                            IDebugDocumentPosition2 docPosition = HostMarshal.GetDocumentPositionForIntPtr(_bpRequestInfo.bpLocation.unionmember2);

                            // Get the name of the document that the breakpoint was put in
                            EngineUtils.CheckOk(docPosition.GetFileName(out documentName));

                            // Get the location in the document that the breakpoint is in.
                            EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition));

                            // Get the document checksum
                            // TODO: This and all other AD7 interface calls need to be moved so that they are only
                            // executed from the main thread.
                            // Github issue: https://github.com/Microsoft/MIEngine/issues/350
                            if (_engine.DebuggedProcess.MICommandFactory.SupportsBreakpointChecksums())
                            {
                                try
                                {
                                    checksums = GetSHA1Checksums();
                                }
                                catch (Exception)
                                {
                                    // If we fail to get a checksum there's nothing else we can do
                                }
                            }

                            break;
                        }

                        case enum_BP_LOCATION_TYPE.BPLT_DATA_STRING:
                        {
                            address = HostMarshal.GetDataBreakpointStringForIntPtr(_bpRequestInfo.bpLocation.unionmember3);
                            size    = (uint)_bpRequestInfo.bpLocation.unionmember4;
                            if (condition != null)
                            {
                                goto default;           // mi has no conditions on watchpoints
                            }
                            break;
                        }

                        default:
                        {
                            this.SetError(new AD7ErrorBreakpoint(this, ResourceStrings.UnsupportedBreakpoint), true);
                            return;
                        }
                        }
                    }
                }
                PendingBreakpoint.BindResult bindResult;
                // Bind all breakpoints that match this source and line number.
                if (documentName != null)
                {
                    bindResult = await PendingBreakpoint.Bind(documentName, startPosition[0].dwLine + 1, startPosition[0].dwColumn, _engine.DebuggedProcess, condition, _enabled, checksums, this);
                }
                else if (functionName != null)
                {
                    bindResult = await PendingBreakpoint.Bind(functionName, _engine.DebuggedProcess, condition, _enabled, this);
                }
                else if (codeAddress != 0)
                {
                    bindResult = await PendingBreakpoint.Bind(codeAddress, _engine.DebuggedProcess, condition, _enabled, this);
                }
                else
                {
                    bindResult = await PendingBreakpoint.Bind(address, size, _engine.DebuggedProcess, condition, this);
                }

                lock (_boundBreakpoints)
                {
                    if (bindResult.PendingBreakpoint != null)
                    {
                        _bp = bindResult.PendingBreakpoint;    // an MI breakpoint object exists: TODO: lock?
                    }
                    if (bindResult.BoundBreakpoints == null || bindResult.BoundBreakpoints.Count == 0)
                    {
                        this.SetError(new AD7ErrorBreakpoint(this, bindResult.ErrorMessage), true);
                    }
                    else
                    {
                        Debug.Assert(_bp != null);
                        foreach (BoundBreakpoint bp in bindResult.BoundBreakpoints)
                        {
                            AddBoundBreakpoint(bp);
                        }
                    }
                }
            }
        }
Пример #16
0
        // Gets the breakpoint resolution information that describes this breakpoint.
        int IDebugBreakpointResolution2.GetResolutionInfo(enum_BPRESI_FIELDS dwFields, BP_RESOLUTION_INFO[] pBPResolutionInfo)
        {
            if ((dwFields & enum_BPRESI_FIELDS.BPRESI_BPRESLOCATION) != 0)
            {
                BP_RESOLUTION_LOCATION location = new BP_RESOLUTION_LOCATION();
                location.bpType = (uint)_breakType;
                if (_breakType == enum_BP_TYPE.BPT_CODE)
                {
                    // The debugger will not QI the IDebugCodeContex2 interface returned here. We must pass the pointer
                    // to IDebugCodeContex2 and not IUnknown.
                    AD7MemoryAddress codeContext = new AD7MemoryAddress(_engine, Addr, _functionName);
                    codeContext.SetDocumentContext(_documentContext);
                    location.unionmember1 = HostMarshal.RegisterCodeContext(codeContext);
                    pBPResolutionInfo[0].bpResLocation = location;
                    pBPResolutionInfo[0].dwFields     |= enum_BPRESI_FIELDS.BPRESI_BPRESLOCATION;
                }
                else if (_breakType == enum_BP_TYPE.BPT_DATA)
                {
                    location.unionmember1 = HostMarshal.GetIntPtrForDataBreakpointAddress(EngineUtils.AsAddr(Addr, _engine.DebuggedProcess.Is64BitArch));
                    pBPResolutionInfo[0].bpResLocation = location;
                    pBPResolutionInfo[0].dwFields     |= enum_BPRESI_FIELDS.BPRESI_BPRESLOCATION;
                }
            }

            if ((dwFields & enum_BPRESI_FIELDS.BPRESI_PROGRAM) != 0)
            {
                pBPResolutionInfo[0].pProgram  = (IDebugProgram2)_engine;
                pBPResolutionInfo[0].dwFields |= enum_BPRESI_FIELDS.BPRESI_PROGRAM;
            }

            return(Constants.S_OK);
        }
Пример #17
0
 public static AD_PROCESS_ID GetProcessId(IDebugProcess2 process)
 {
     AD_PROCESS_ID[] pid = new AD_PROCESS_ID[1];
     EngineUtils.RequireOk(process.GetPhysicalProcessId(pid));
     return(pid[0]);
 }
Пример #18
0
        // Compares the memory context to each context in the given array in the manner indicated by compare flags,
        // returning an index of the first context that matches.
        public int Compare(enum_CONTEXT_COMPARE contextCompare, IDebugMemoryContext2[] compareToItems, uint compareToLength, out uint foundIndex)
        {
            foundIndex = uint.MaxValue;

            try
            {
                for (uint c = 0; c < compareToLength; c++)
                {
                    AD7MemoryAddress compareTo = compareToItems[c] as AD7MemoryAddress;
                    if (compareTo == null)
                    {
                        continue;
                    }

                    if (!AD7Engine.ReferenceEquals(_engine, compareTo._engine))
                    {
                        continue;
                    }

                    bool result;

                    switch (contextCompare)
                    {
                    case enum_CONTEXT_COMPARE.CONTEXT_EQUAL:
                        result = (_address == compareTo._address);
                        break;

                    case enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN:
                        result = (_address < compareTo._address);
                        break;

                    case enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN:
                        result = (_address > compareTo._address);
                        break;

                    case enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN_OR_EQUAL:
                        result = (_address <= compareTo._address);
                        break;

                    case enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN_OR_EQUAL:
                        result = (_address >= compareTo._address);
                        break;

                    // The debug engine doesn't understand scopes
                    case enum_CONTEXT_COMPARE.CONTEXT_SAME_SCOPE:
                        result = (_address == compareTo._address);
                        break;

                    case enum_CONTEXT_COMPARE.CONTEXT_SAME_FUNCTION:
                        if (_address == compareTo._address)
                        {
                            result = true;
                            break;
                        }
                        string funcThis = Engine.GetAddressDescription(_address);
                        if (string.IsNullOrEmpty(funcThis))
                        {
                            result = false;
                            break;
                        }
                        string funcCompareTo = Engine.GetAddressDescription(compareTo._address);
                        result = (funcThis == funcCompareTo);
                        break;

                    case enum_CONTEXT_COMPARE.CONTEXT_SAME_MODULE:
                        result = (_address == compareTo._address);
                        if (result == false)
                        {
                            DebuggedModule module = _engine.DebuggedProcess.ResolveAddress(_address);

                            if (module != null)
                            {
                                result = module.AddressInModule(compareTo._address);
                            }
                        }
                        break;

                    case enum_CONTEXT_COMPARE.CONTEXT_SAME_PROCESS:
                        result = true;
                        break;

                    default:
                        // A new comparison was invented that we don't support
                        return(Constants.E_NOTIMPL);
                    }

                    if (result)
                    {
                        foundIndex = c;
                        return(Constants.S_OK);
                    }
                }

                return(Constants.S_FALSE);
            }
            catch (MIException e)
            {
                return(e.HResult);
            }
            catch (Exception e)
            {
                return(EngineUtils.UnexpectedException(e));
            }
        }
Пример #19
0
        // Construct a FRAMEINFO for this stack frame with the requested information.
        public void SetFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, out FRAMEINFO frameInfo, List <SimpleVariableInformation> parameters)
        {
            frameInfo = new FRAMEINFO();

            DebuggedModule module = ThreadContext.FindModule(Engine.DebuggedProcess);

            // The debugger is asking for the formatted name of the function which is displayed in the callstack window.
            // There are several optional parts to this name including the module, argument types and values, and line numbers.
            // The optional information is requested by setting flags in the dwFieldSpec parameter.
            if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME) != 0)
            {
                // If there is source information, construct a string that contains the module name, function name, and optionally argument names and values.
                if (_textPosition != null)
                {
                    frameInfo.m_bstrFuncName = "";

                    if (module != null && (dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_MODULE) != 0)
                    {
                        frameInfo.m_bstrFuncName = System.IO.Path.GetFileName(module.Name) + "!";
                    }

                    frameInfo.m_bstrFuncName += _functionName;

                    if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS) != 0 && !Engine.DebuggedProcess.MICommandFactory.SupportsFrameFormatting)
                    {
                        frameInfo.m_bstrFuncName += "(";
                        if (parameters != null && parameters.Count > 0)
                        {
                            for (int i = 0; i < parameters.Count; i++)
                            {
                                if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_TYPES) != 0)
                                {
                                    frameInfo.m_bstrFuncName += parameters[i].TypeName + " ";
                                }

                                if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_NAMES) != 0)
                                {
                                    frameInfo.m_bstrFuncName += parameters[i].Name;
                                }

                                if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_NAMES) != 0 &&
                                    (dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_VALUES) != 0)
                                {
                                    frameInfo.m_bstrFuncName += "=";
                                }

                                if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_VALUES) != 0)
                                {
                                    frameInfo.m_bstrFuncName += parameters[i].Value;
                                }

                                if (i < parameters.Count - 1)
                                {
                                    frameInfo.m_bstrFuncName += ", ";
                                }
                            }
                        }
                        frameInfo.m_bstrFuncName += ")";
                    }

                    if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_LINES) != 0)
                    {
                        frameInfo.m_bstrFuncName += string.Format(CultureInfo.CurrentCulture, " Line {0}", _textPosition.BeginPosition.dwLine + 1);
                    }
                }
                else
                {
                    // No source information, so only return the module name and the instruction pointer.
                    if (_functionName != null)
                    {
                        if (module != null)
                        {
                            frameInfo.m_bstrFuncName = System.IO.Path.GetFileName(module.Name) + '!' + _functionName;
                        }
                        else
                        {
                            frameInfo.m_bstrFuncName = _functionName;
                        }
                    }
                    else if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_MODULE) != 0 && module != null)
                    {
                        frameInfo.m_bstrFuncName = module.Name + '!' + EngineUtils.GetAddressDescription(Engine.DebuggedProcess, ThreadContext.pc.Value);
                    }
                    else
                    {
                        frameInfo.m_bstrFuncName = EngineUtils.GetAddressDescription(Engine.DebuggedProcess, ThreadContext.pc.Value);
                    }
                }
                frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FUNCNAME;
            }

            // The debugger is requesting the name of the module for this stack frame.
            if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_MODULE) != 0)
            {
                if (module != null)
                {
                    frameInfo.m_bstrModule = module.Name;
                }
                else
                {
                    frameInfo.m_bstrModule = "";
                }
                frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_MODULE;
            }

            // The debugger is requesting the range of memory addresses for this frame.
            // For the sample engine, this is the contents of the frame pointer.
            if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_STACKRANGE) != 0)
            {
                frameInfo.m_addrMin        = ThreadContext.sp;
                frameInfo.m_addrMax        = ThreadContext.sp;
                frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_STACKRANGE;
            }

            // The debugger is requesting the IDebugStackFrame2 value for this frame info.
            if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FRAME) != 0)
            {
                frameInfo.m_pFrame         = this;
                frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FRAME;
            }

            // Does this stack frame of symbols loaded?
            if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_DEBUGINFO) != 0)
            {
                frameInfo.m_fHasDebugInfo  = _textPosition != null ? 1 : 0;
                frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_DEBUGINFO;
            }

            // Is this frame stale?
            if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_STALECODE) != 0)
            {
                frameInfo.m_fStaleCode     = 0;
                frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_STALECODE;
            }

            // The debugger would like a pointer to the IDebugModule2 that contains this stack frame.
            if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP) != 0)
            {
                if (module != null)
                {
                    AD7Module ad7Module = (AD7Module)module.Client;
                    Debug.Assert(ad7Module != null);
                    frameInfo.m_pModule        = ad7Module;
                    frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP;
                }
            }

            if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FLAGS) != 0)
            {
                if (_codeCxt == null && _documentCxt == null)
                {
                    frameInfo.m_dwFlags |= (uint)enum_FRAMEINFO_FLAGS_VALUES.FIFV_ANNOTATEDFRAME;
                }
                frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FLAGS;
            }

            if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_LANGUAGE) != 0)
            {
                Guid unused = Guid.Empty;
                if (GetLanguageInfo(ref frameInfo.m_bstrLanguage, ref unused) == 0)
                {
                    frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_LANGUAGE;
                }
            }
        }
Пример #20
0
        // Attach the debug engine to a program.
        public int Attach(IDebugProgram2[] portProgramArray, IDebugProgramNode2[] programNodeArray, uint celtPrograms, IDebugEventCallback2 ad7Callback, enum_ATTACH_REASON dwReason)
        {
            Debug.Assert(_ad7ProgramId == Guid.Empty);

            if (celtPrograms != 1)
            {
                Debug.Fail("SampleEngine only expects to see one program in a process");
                throw new ArgumentException();
            }
            IDebugProgram2 portProgram = portProgramArray[0];

            Exception exception = null;

            try
            {
                IDebugProcess2 process;
                EngineUtils.RequireOk(portProgram.GetProcess(out process));

                AD_PROCESS_ID processId = EngineUtils.GetProcessId(process);

                EngineUtils.RequireOk(portProgram.GetProgramId(out _ad7ProgramId));

                // Attach can either be called to attach to a new process, or to complete an attach
                // to a launched process
                if (_pollThread == null)
                {
                    if (processId.ProcessIdType != (uint)enum_AD_PROCESS_ID.AD_PROCESS_ID_SYSTEM)
                    {
                        Debug.Fail("Invalid process to attach to");
                        throw new ArgumentException();
                    }

                    IDebugPort2 port;
                    EngineUtils.RequireOk(process.GetPort(out port));

                    Debug.Assert(_engineCallback == null);
                    Debug.Assert(_debuggedProcess == null);

                    _engineCallback = new EngineCallback(this, ad7Callback);
                    LaunchOptions launchOptions = CreateAttachLaunchOptions(processId.dwProcessId, port);
                    StartDebugging(launchOptions);
                }
                else
                {
                    if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id))
                    {
                        Debug.Fail("Asked to attach to a process while we are debugging");
                        return(Constants.E_FAIL);
                    }
                }

                AD7EngineCreateEvent.Send(this);
                AD7ProgramCreateEvent.Send(this);
                this.ProgramCreateEventSent = true;

                return(Constants.S_OK);
            }
            catch (Exception e) when(ExceptionHelper.BeforeCatch(e, Logger, reportOnlyCorrupting: true))
            {
                exception = e;
            }

            // If we just return the exception as an HRESULT, we will lose our message, so we instead send up an error event, and
            // return that the attach was canceled
            OnStartDebuggingFailed(exception);
            return(AD7_HRESULT.E_ATTACH_USER_CANCELED);
        }
Пример #21
0
        // Gets the MODULE_INFO that describes this module.
        // This is how the debugger obtains most of the information about the module.
        int IDebugModule2.GetInfo(enum_MODULE_INFO_FIELDS dwFields, MODULE_INFO[] infoArray)
        {
            try
            {
                MODULE_INFO info = new MODULE_INFO();

                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_NAME) != 0)
                {
                    info.m_bstrName     = System.IO.Path.GetFileName(this.DebuggedModule.Name);
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_NAME;
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_URL) != 0)
                {
                    info.m_bstrUrl      = this.DebuggedModule.Name;
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_URL;
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_LOADADDRESS) != 0)
                {
                    info.m_addrLoadAddress = (ulong)this.DebuggedModule.BaseAddress;
                    info.dwValidFields    |= enum_MODULE_INFO_FIELDS.MIF_LOADADDRESS;
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_PREFFEREDADDRESS) != 0)
                {
                    // A debugger that actually supports showing the preferred base should read the PE header and get
                    // that field. This debugger does not do that, so assume the module loaded where it was suppose to.
                    info.m_addrPreferredLoadAddress = (ulong)this.DebuggedModule.BaseAddress;
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_PREFFEREDADDRESS;;
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_SIZE) != 0)
                {
                    info.m_dwSize       = (uint)this.DebuggedModule.Size;
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_SIZE;
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_LOADORDER) != 0)
                {
                    info.m_dwLoadOrder  = this.DebuggedModule.GetLoadOrder();
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_LOADORDER;
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_URLSYMBOLLOCATION) != 0)
                {
                    if (this.DebuggedModule.SymbolsLoaded)
                    {
                        info.m_bstrUrlSymbolLocation = this.DebuggedModule.SymbolPath;
                        info.dwValidFields          |= enum_MODULE_INFO_FIELDS.MIF_URLSYMBOLLOCATION;
                    }
                }
                if ((dwFields & enum_MODULE_INFO_FIELDS.MIF_FLAGS) != 0)
                {
                    info.m_dwModuleFlags = 0;
                    if (this.DebuggedModule.SymbolsLoaded)
                    {
                        info.m_dwModuleFlags |= (enum_MODULE_FLAGS.MODULE_FLAG_SYMBOLS);
                    }

                    if (this.Process.Is64BitArch)
                    {
                        info.m_dwModuleFlags |= enum_MODULE_FLAGS.MODULE_FLAG_64BIT;
                    }

                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_FLAGS;
                }


                infoArray[0] = info;

                return(Constants.S_OK);
            }
            catch (MIException e)
            {
                return(e.HResult);
            }
            catch (Exception e)
            {
                return(EngineUtils.UnexpectedException(e));
            }
        }
Пример #22
0
        // Binds this pending breakpoint to one or more code locations.
        int IDebugPendingBreakpoint2.Bind()
        {
            try
            {
                if (CanBind())
                {
                    // Make sure that HostMarshal calls happen on main thread instead of poll thread.
                    lock (_boundBreakpoints)
                    {
                        if (_bp != null)   // already bound
                        {
                            Debug.Fail("Breakpoint already bound");
                            return(Constants.S_FALSE);
                        }
                        if ((_bpRequestInfo.dwFields & enum_BPREQI_FIELDS.BPREQI_CONDITION) != 0 &&
                            _bpRequestInfo.bpCondition.styleCondition == enum_BP_COND_STYLE.BP_COND_WHEN_TRUE)
                        {
                            _condition = _bpRequestInfo.bpCondition.bstrCondition;
                        }
                        if ((_bpRequestInfo.dwFields & enum_BPREQI_FIELDS.BPREQI_BPLOCATION) != 0)
                        {
                            switch ((enum_BP_LOCATION_TYPE)_bpRequestInfo.bpLocation.bpLocationType)
                            {
                            case enum_BP_LOCATION_TYPE.BPLT_CODE_FUNC_OFFSET:
                                try
                                {
                                    IDebugFunctionPosition2 functionPosition = HostMarshal.GetDebugFunctionPositionForIntPtr(_bpRequestInfo.bpLocation.unionmember2);
                                    EngineUtils.CheckOk(functionPosition.GetFunctionName(out _functionName));
                                }
                                finally
                                {
                                    HostMarshal.Release(_bpRequestInfo.bpLocation.unionmember2);
                                }
                                break;

                            case enum_BP_LOCATION_TYPE.BPLT_CODE_CONTEXT:
                                try
                                {
                                    IDebugCodeContext2 codePosition = HostMarshal.GetDebugCodeContextForIntPtr(_bpRequestInfo.bpLocation.unionmember1);
                                    if (!(codePosition is AD7MemoryAddress))
                                    {
                                        goto default;       // context is not from this engine
                                    }
                                    _codeAddress = ((AD7MemoryAddress)codePosition).Address;
                                }
                                finally
                                {
                                    HostMarshal.Release(_bpRequestInfo.bpLocation.unionmember1);
                                }
                                break;

                            case enum_BP_LOCATION_TYPE.BPLT_CODE_FILE_LINE:
                                try
                                {
                                    IDebugDocumentPosition2 docPosition = HostMarshal.GetDocumentPositionForIntPtr(_bpRequestInfo.bpLocation.unionmember2);
                                    // Get the name of the document that the breakpoint was put in
                                    EngineUtils.CheckOk(docPosition.GetFileName(out _documentName));

                                    // Get the location in the document that the breakpoint is in.
                                    EngineUtils.CheckOk(docPosition.GetRange(_startPosition, _endPosition));
                                }
                                finally
                                {
                                    HostMarshal.Release(_bpRequestInfo.bpLocation.unionmember2);
                                }

                                // Get the document checksum
                                if (_engine.DebuggedProcess.MICommandFactory.SupportsBreakpointChecksums())
                                {
                                    try
                                    {
                                        _checksums = GetSHA1Checksums();
                                    }
                                    catch (Exception)
                                    {
                                        // If we fail to get a checksum there's nothing else we can do
                                    }
                                }

                                break;

                            case enum_BP_LOCATION_TYPE.BPLT_DATA_STRING:
                                _address = HostMarshal.GetDataBreakpointStringForIntPtr(_bpRequestInfo.bpLocation.unionmember3);
                                _size    = (uint)_bpRequestInfo.bpLocation.unionmember4;
                                if (_condition != null)
                                {
                                    goto default;       // mi has no conditions on watchpoints
                                }
                                break;

                            default:
                                this.SetError(new AD7ErrorBreakpoint(this, ResourceStrings.UnsupportedBreakpoint), true);
                                return(Constants.S_FALSE);
                            }
                        }
                    }

                    Task bindTask = null;
                    _engine.DebuggedProcess.WorkerThread.RunOperation(() =>
                    {
                        bindTask = _engine.DebuggedProcess.AddInternalBreakAction(this.BindAsync);
                    });

                    bindTask.Wait(_engine.GetBPLongBindTimeout());
                    if (!bindTask.IsCompleted)
                    {
                        //send a low severity warning bp. This will allow the UI to respond quickly, and if the mi debugger doesn't end up binding, this warning will get
                        //replaced by the real mi debugger error text
                        this.SetError(new AD7ErrorBreakpoint(this, ResourceStrings.LongBind, enum_BP_ERROR_TYPE.BPET_SEV_LOW | enum_BP_ERROR_TYPE.BPET_TYPE_WARNING), true);
                        return(Constants.S_FALSE);
                    }
                    else
                    {
                        return(Constants.S_OK);
                    }
                }
                else
                {
                    // The breakpoint could not be bound. This may occur for many reasons such as an invalid location, an invalid expression, etc...
                    _engine.Callback.OnBreakpointError(_BPError);
                    return(Constants.S_FALSE);
                }
            }
            catch (MIException e)
            {
                return(e.HResult);
            }
            catch (AggregateException e)
            {
                if (e.GetBaseException() is InvalidCoreDumpOperationException)
                {
                    return(AD7_HRESULT.E_CRASHDUMP_UNSUPPORTED);
                }
                else
                {
                    return(EngineUtils.UnexpectedException(e));
                }
            }
            catch (InvalidCoreDumpOperationException)
            {
                return(AD7_HRESULT.E_CRASHDUMP_UNSUPPORTED);
            }
            catch (Exception e)
            {
                return(EngineUtils.UnexpectedException(e));
            }
        }
Пример #23
0
        // Binds this pending breakpoint to one or more code locations.
        int IDebugPendingBreakpoint2.Bind()
        {
            try
            {
                if (CanBind())
                {
                    // Make sure that HostMarshal calls happen on main thread instead of poll thread.
                    lock (_boundBreakpoints)
                    {
                        if (_bp != null)   // already bound
                        {
                            Debug.Fail("Breakpoint already bound");
                            return(Constants.S_FALSE);
                        }
                        if ((_bpRequestInfo.dwFields & enum_BPREQI_FIELDS.BPREQI_CONDITION) != 0 &&
                            _bpRequestInfo.bpCondition.styleCondition == enum_BP_COND_STYLE.BP_COND_WHEN_TRUE)
                        {
                            _condition = _bpRequestInfo.bpCondition.bstrCondition;
                        }
                        if ((_bpRequestInfo.dwFields & enum_BPREQI_FIELDS.BPREQI_BPLOCATION) != 0)
                        {
                            switch ((enum_BP_LOCATION_TYPE)_bpRequestInfo.bpLocation.bpLocationType)
                            {
                            case enum_BP_LOCATION_TYPE.BPLT_CODE_FUNC_OFFSET:
                                try
                                {
                                    IDebugFunctionPosition2 functionPosition = HostMarshal.GetDebugFunctionPositionForIntPtr(_bpRequestInfo.bpLocation.unionmember2);
                                    EngineUtils.CheckOk(functionPosition.GetFunctionName(out _functionName));
                                }
                                finally
                                {
                                    HostMarshal.Release(_bpRequestInfo.bpLocation.unionmember2);
                                }
                                break;

                            case enum_BP_LOCATION_TYPE.BPLT_CODE_CONTEXT:
                                try
                                {
                                    IDebugCodeContext2 codePosition = HostMarshal.GetDebugCodeContextForIntPtr(_bpRequestInfo.bpLocation.unionmember1);
                                    if (!(codePosition is AD7MemoryAddress))
                                    {
                                        goto default;       // context is not from this engine
                                    }
                                    _codeAddress = ((AD7MemoryAddress)codePosition).Address;
                                }
                                finally
                                {
                                    HostMarshal.Release(_bpRequestInfo.bpLocation.unionmember1);
                                }
                                break;

                            case enum_BP_LOCATION_TYPE.BPLT_CODE_FILE_LINE:
                                try
                                {
                                    IDebugDocumentPosition2 docPosition = HostMarshal.GetDocumentPositionForIntPtr(_bpRequestInfo.bpLocation.unionmember2);
                                    // Get the name of the document that the breakpoint was put in
                                    EngineUtils.CheckOk(docPosition.GetFileName(out _documentName));

                                    // Get the location in the document that the breakpoint is in.
                                    EngineUtils.CheckOk(docPosition.GetRange(_startPosition, _endPosition));
                                }
                                finally
                                {
                                    HostMarshal.Release(_bpRequestInfo.bpLocation.unionmember2);
                                }

                                // Get the document checksum
                                if (_engine.DebuggedProcess.MICommandFactory.SupportsBreakpointChecksums())
                                {
                                    try
                                    {
                                        _checksums = GetSHA1Checksums();
                                    }
                                    catch (Exception)
                                    {
                                        // If we fail to get a checksum there's nothing else we can do
                                    }
                                }

                                break;

                            case enum_BP_LOCATION_TYPE.BPLT_DATA_STRING:
                                string address = HostMarshal.GetDataBreakpointStringForIntPtr(_bpRequestInfo.bpLocation.unionmember3);
                                if (address.Contains(","))
                                {
                                    this.AddressId = address;
                                    _address       = address.Split(',')[0];
                                }
                                else
                                {
                                    this.AddressId = null;
                                    _address       = address;
                                }
                                _size = (uint)_bpRequestInfo.bpLocation.unionmember4;
                                if (_condition != null)
                                {
                                    goto default;       // mi has no conditions on watchpoints
                                }
                                break;

                            default:
                                this.SetError(new AD7ErrorBreakpoint(this, ResourceStrings.UnsupportedBreakpoint), true);
                                return(Constants.S_FALSE);
                            }
                        }
                    }

                    if (!_enabled && IsHardwareBreakpoint)
                    {
                        return(Constants.S_OK);
                    }

                    return(BindWithTimeout());
                }
                else
                {
                    // The breakpoint could not be bound. This may occur for many reasons such as an invalid location, an invalid expression, etc...
                    _engine.Callback.OnBreakpointError(_BPError);
                    return(Constants.S_FALSE);
                }
            }
            catch (MIException e)
            {
                return(e.HResult);
            }
            catch (AggregateException e)
            {
                if (e.GetBaseException() is InvalidCoreDumpOperationException)
                {
                    return(AD7_HRESULT.E_CRASHDUMP_UNSUPPORTED);
                }
                else
                {
                    return(EngineUtils.UnexpectedException(e));
                }
            }
            catch (InvalidCoreDumpOperationException)
            {
                return(AD7_HRESULT.E_CRASHDUMP_UNSUPPORTED);
            }
            catch (Exception e)
            {
                return(EngineUtils.UnexpectedException(e));
            }
        }