Example #1
0
        public void CheckRegistersInterface()
        {
            DbgEngDll debugger = Context.Debugger as DbgEngDll;

            Assert.NotNull(debugger);
            Assert.NotNull(debugger.Registers);
        }
Example #2
0
        public void GetMemoryRegions()
        {
            DbgEngDll debugger = Context.Debugger as DbgEngDll;

            Assert.NotNull(debugger);
            Assert.True(debugger.GetMemoryRegions(Process.Current).Length > 0);
        }
Example #3
0
        protected override void ProcessRecord()
        {
            ConnectionState state = ConnectionState.GetConnectionState();

            state.IsConnected = true;
            state.ProcessPath = ProcessPath;

            if (SymbolPath == null)
            {
                SymbolPath = "srv*";
            }

            IDebugClient client = DebugClient.DebugCreateEx(0x60);

            ((IDebugSymbols5)client).SetSymbolPathWide(SymbolPath);
            ((IDebugClient7)client).CreateProcessAndAttach(0, ProcessPath, DebugCreateProcess.DebugOnlyThisProcess, 0, DebugAttach.Default);
            ((IDebugControl7)client).WaitForEvent(0, uint.MaxValue);

            // For live debugging disable caching.
            //
            Context.EnableUserCastedVariableCaching = false;
            Context.EnableVariableCaching           = false;

            IDebuggerEngine debugger       = new DbgEngDll(client);
            ISymbolProvider symbolProvider = new DiaSymbolProvider(debugger.GetDefaultSymbolProvider());

            Context.InitializeDebugger(debugger, symbolProvider);

            WriteDebug("Connection successfully initialized");
        }
Example #4
0
        public void CheckLiveDebugging()
        {
            DbgEngDll debugger = Context.Debugger as DbgEngDll;

            Assert.NotNull(debugger);
            Assert.False(debugger.IsLiveDebugging);
        }
Example #5
0
        public static int OpenUI(IntPtr client, [MarshalAs(UnmanagedType.LPStr)] string args)
        {
            string[] arguments = args.Split(" ".ToCharArray());
            bool     showModal = false;

            if (arguments.Length > 0 && !bool.TryParse(arguments[0], out showModal))
            {
                showModal = false;
            }

            try
            {
                IDebugClient debugClient = (IDebugClient)Marshal.GetUniqueObjectForIUnknown(client);

                DbgEngDll.InitializeContext(debugClient);
                new Task(() =>
                {
                    if (showModal)
                    {
                        InteractiveWindow.ShowModalWindow();
                    }
                    else
                    {
                        InteractiveWindow.ShowWindow();
                    }
                }).Start();
                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(ex.HResult);
            }
        }
Example #6
0
        public void GetModuleMappedImage()
        {
            DbgEngDll debugger = Context.Debugger as DbgEngDll;
            Module    module   = StackFrame.Current.Module;

            Assert.NotNull(debugger);
            Assert.Equal(module.MappedImageName, debugger.GetModuleMappedImage(module));
        }
        public WinDbgExtensionTests(NativeDumpTest_x64_dmp_Initialization initialization)
            : base(initialization)
        {
            string configuration = Environment.Is64BitProcess ? "x64" : "x86";
            string extensionPath = GetAbsoluteBinPath($"CsDebugScript.WinDbg.{configuration}.dll");
            string output        = DbgEngDll.ExecuteAndCapture($".load {extensionPath}");

            Assert.Equal("", output?.Trim());
        }
        private string Execute(string command, params string[] parameters)
        {
            IDebuggerEngine debugger       = Context.Debugger;
            ISymbolProvider symbolProvider = Context.SymbolProvider;
            string          output         = DbgEngDll.ExecuteAndCapture(command, parameters);

            Context.InitializeDebugger(debugger, symbolProvider);
            return(output);
        }
Example #9
0
        public void GetStackTraceFromContext()
        {
            DbgEngDll          debugger = Context.Debugger as DbgEngDll;
            StackFrame         frame    = GetFrame($"{DefaultModuleName}!TestDbgEngDll");
            VariableCollection locals   = frame.Locals;
            Variable           context  = locals["context"];

            Assert.NotNull(debugger);
            Assert.NotNull(debugger.GetStackTraceFromContext(context.GetCodeType().Module.Process, context.GetPointerAddress()));
        }
Example #10
0
        public void ReadUnicodeString()
        {
            DbgEngDll          debugger   = Context.Debugger as DbgEngDll;
            StackFrame         frame      = GetFrame($"{DefaultModuleName}!TestDbgEngDll");
            VariableCollection locals     = frame.Locals;
            Variable           testString = locals["testWString"];

            Assert.NotNull(debugger);
            Assert.Equal("Testing...", debugger.ReadUnicodeString(testString.GetCodeType().Module.Process, testString.GetPointerAddress()));
        }
        /// <summary>
        /// Creates the output callbacks switcher.
        /// </summary>
        /// <param name="callbacks">The callbacks.</param>
        public static OutputCallbacksSwitcher Create(DebuggerOutputToTextWriter callbacks)
        {
            DbgEngDll dbgEngDll = Context.Debugger as DbgEngDll;

            if (dbgEngDll != null)
            {
                return(new DbgEngOutputCallbacksSwitcher(dbgEngDll, (DbgEngDebuggerOutputToTextWriter)callbacks));
            }

            return(null);
        }
Example #12
0
        public void CheckIsLiveModeDebugging() => ContinousTestExecutionWrapper(() =>
        {
            InitializeProcess(TestProcessPath, ProcessArguments, DefaultSymbolPath);
            DbgEngDll debugger = Context.Debugger as DbgEngDll;

            Assert.NotNull(debugger);
            Assert.True(debugger.IsLiveDebugging);

            Debugger.ContinueExecution();
            Debugger.BreakExecution();
        }, DefaultTimeout);
Example #13
0
        static void Main(string[] args)
        {
            Options options = null;

            Parser.Default.ParseArguments <Options>(args)
            .WithParsed(o => options = o);

            if (options == null)
            {
                return;
            }

            DebuggerInitialization.OpenDump(options.DumpPath, options.SymbolPath);
            Console.WriteLine("Threads: {0}", Thread.All.Length);
            Console.WriteLine("Current thread: {0}", Thread.Current.Id);
            var frames = Thread.Current.StackTrace.Frames;

            Console.WriteLine("Call stack:");
            foreach (var frame in frames)
            {
                try
                {
                    Console.WriteLine("  {0,3:x} {1}+0x{2:x}   ({3}:{4})", frame.FrameNumber, frame.FunctionName, frame.FunctionDisplacement, frame.SourceFileName, frame.SourceFileLine);
                }
                catch (Exception)
                {
                    Console.WriteLine("  {0,3:x} {1}+0x{2:x}", frame.FrameNumber, frame.FunctionName, frame.FunctionDisplacement);
                }
            }

            // In order to use console output and error in scripts, we must set it to debug client
            DebugOutput captureFlags = DebugOutput.Normal | DebugOutput.Error | DebugOutput.Warning | DebugOutput.Verbose
                                       | DebugOutput.Prompt | DebugOutput.PromptRegisters | DebugOutput.ExtensionWarning | DebugOutput.Debuggee
                                       | DebugOutput.DebuggeePrompt | DebugOutput.Symbols | DebugOutput.Status;
            var callbacks = DebuggerOutputToTextWriter.Create(Console.Out, captureFlags);

            using (OutputCallbacksSwitcher switcher = OutputCallbacksSwitcher.Create(callbacks))
            {
                Action action = () =>
                {
                    ScriptExecution.Execute(@"..\..\samples\script.csx", args);
                };
                DbgEngDll dbgEngDll = Context.Debugger as DbgEngDll;

                if (dbgEngDll != null)
                {
                    dbgEngDll.ExecuteAction(action);
                }
                else
                {
                    action();
                }
            }
        }
Example #14
0
        public DbgEngDumpInitialization(string dumpPath, string defaultModuleName, string symbolPath = DefaultDumpPath, bool addSymbolServer = true, bool useDia = true, bool useDwarf = false)
            : base(dumpPath, defaultModuleName, FixSymbolPath(symbolPath, addSymbolServer))
        {
            IDebugClient client = DebugClient.OpenDumpFile(DumpPath, SymbolPath);

            DbgEngDll.InitializeContext(client);
            if (!useDia && !useDwarf)
            {
                Context.InitializeDebugger(Context.Debugger);
            }
            else if (useDwarf)
            {
                Context.InitializeDebugger(Context.Debugger, new DwarfSymbolProvider.DwarfSymbolProvider());
            }
        }
        /// <summary>
        /// Reads the command from the user.
        /// </summary>
        /// <param name="prompt">The prompt.</param>
        private static string ReadCommand(string prompt)
        {
            // Write prompt
            prompt = prompt.Replace("%", "%%");
            Console.Write(prompt);

            // Read string
            DbgEngDll dbgEngDll = Context.Debugger as DbgEngDll;

            if (dbgEngDll != null)
            {
                return(dbgEngDll.ReadInput());
            }
            else
            {
                return(Console.ReadLine());
            }
        }
Example #16
0
        public DbgEngDumpInitialization(string dumpPath, string defaultModuleName, string symbolPath = DefaultDumpPath, bool addSymbolServer = true, bool useDia = true, bool useDwarf = false, bool useILCodeGen = false)
            : base(dumpPath, defaultModuleName, FixSymbolPath(symbolPath, addSymbolServer), useILCodeGen)
        {
            // Clear all processes being debugged with DbgEng.dll...
            (Context.Debugger as DbgEngDll)?.Client?.EndSession(DebugEnd.ActiveTerminate);

            IDebugClient client = DebugClient.OpenDumpFile(DumpPath, SymbolPath);

            DbgEngDll.InitializeContext(client);
            if (!useDia && !useDwarf)
            {
                Context.InitializeDebugger(Context.Debugger);
            }
            else if (useDwarf)
            {
                Context.InitializeDebugger(Context.Debugger, new DwarfSymbolProvider.DwarfSymbolProvider());
            }
        }
Example #17
0
        /// <summary>
        /// Initializes the test class with the specified process file.
        /// </summary>
        /// <param name="processPath">Path to the process to be started.</param>
        /// <param name="processArguments">Arguments for process to be started.</param>
        /// <param name="symbolPath">Symbol path.</param>
        /// <param name="addSymbolServer">if set to <c>true</c> symbol server will be added to the symbol path.</param>
        /// <param name="debugEngineOptions">Debug create options. Default is to start in break mode, and break on process exit.</param>
        protected static void InitializeProcess(string processPath, string processArguments, string symbolPath, bool addSymbolServer = true, uint debugEngineOptions = (uint)(Defines.DebugEngoptInitialBreak | Defines.DebugEngoptFinalBreak))
        {
            processPath = GetAbsoluteBinPath(processPath);
            symbolPath  = GetAbsoluteBinPath(symbolPath);
            if (addSymbolServer)
            {
                symbolPath += ";srv*";
            }

            // Disable caching.
            //
            Context.EnableUserCastedVariableCaching = false;
            Context.EnableVariableCaching           = false;

            IDebugClient client = DebugClient.OpenProcess(processPath, processArguments, symbolPath, debugEngineOptions);

            DbgEngDll.InitializeContext(client);
        }
Example #18
0
        protected override void ProcessRecord()
        {
            ConnectionState state = ConnectionState.GetConnectionState();

            state.IsConnected = true;
            state.ProcessPath = ProcessPath;

            if (SymbolPath == null)
            {
                SymbolPath = "srv*";
            }

            IDebugClient client = DebugClient.OpenProcess(ProcessPath, null, SymbolPath, (uint)(Defines.DebugEngoptInitialBreak | Defines.DebugEngoptFinalBreak));

            WriteDebug("Connection successfully initialized");

            DbgEngDll.InitializeContext(client);
        }
Example #19
0
        protected override void OnExecuteWinDbgCommand()
        {
            BackgroundExecute((string documentText, out string textOutput, out string errorOutput, out IEnumerable <object> result) =>
            {
                // Setting results
                textOutput  = "";
                errorOutput = "";

                try
                {
                    textOutput = DbgEngDll.ExecuteAndCapture(documentText);
                }
                catch (Exception ex)
                {
                    errorOutput = ex.ToString();
                }
                result  = results;
                results = new List <object>();
            }, false);
        }
Example #20
0
        private static int ExecuteAction(IntPtr client, Action action)
        {
            try
            {
                IDebugClient debugClient = (IDebugClient)Marshal.GetUniqueObjectForIUnknown(client);

                DbgEngDll.InitializeContext(debugClient);
                Context.ClrProvider = new CLR.ClrMdProvider();
                DbgEngDll dbgEngDll = Context.Debugger as DbgEngDll;

                dbgEngDll.ExecuteAction(action);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(ex.HResult);
            }
            finally
            {
                DbgEngDll.InitializeContext(null);
            }

            return(0);
        }
Example #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DebuggeeFlowController"/> class.
        /// </summary>
        /// <param name="dbgEngDll">The DbgEngDll.</param>
        public DebuggeeFlowController(DbgEngDll dbgEngDll)
        {
            // Default is that we start in break mode.
            // TODO: Needs to be changed when we allow non intrusive attach/start for example.
            //
            DebugStatusGo    = new System.Threading.AutoResetEvent(false);
            DebugStatusBreak = new System.Threading.AutoResetEvent(true);

            this.dbgEngDll = dbgEngDll;
            lock (eventCallbacksReady)
            {
                debuggerStateLoop =
                    new System.Threading.Thread(() => DebuggerStateLoop())
                {
                    IsBackground = true
                };
                debuggerStateLoop.SetApartmentState(System.Threading.ApartmentState.MTA);
                debuggerStateLoop.Start();

                // Wait for loop thread to become ready.
                //
                System.Threading.Monitor.Wait(eventCallbacksReady);
            }
        }
Example #22
0
 /// <summary>
 /// Initializes debugger as DbgEng from the specified debug client interface.
 /// </summary>
 /// <param name="debugClient">The debug client interface that will initialize debugger.</param>
 private static void InitializeDbgEng(IDebugClient debugClient)
 {
     DbgEngDll.InitializeContext(debugClient);
     Context.InitializeDebugger(Context.Debugger, new DwarfSymbolProvider.DwarfSymbolProvider());
     Context.ClrProvider = new CLR.ClrMdProvider();
 }
Example #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StateCache"/> class.
 /// </summary>
 public StateCache(DbgEngDll dbgEngDll)
 {
     CurrentThread = new DictionaryCache<Process, Thread>(CacheCurrentThread);
     CurrentStackFrame = new DictionaryCache<Thread, StackFrame>(CacheCurrentStackFrame);
     this.dbgEngDll = dbgEngDll;
 }
Example #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DebuggerTextWriter" /> class.
 /// </summary>
 /// <param name="dbgEngDll">The DbgEngDll debugger engine.</param>
 /// <param name="outputType">Type of the output.</param>
 public DebuggerTextWriter(DbgEngDll dbgEngDll, DebugOutput outputType)
 {
     OutputType          = outputType;
     outputCallbacksWide = dbgEngDll.Client.GetOutputCallbacksWide();
     outputCallbacks     = dbgEngDll.Client.GetOutputCallbacks();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DbgEngSymbolProvider"/> class.
 /// </summary>
 /// <param name="dbgEngDll">The DbgEngDll debugger engine</param>
 public DbgEngSymbolProvider(DbgEngDll dbgEngDll)
 {
     this.dbgEngDll = dbgEngDll;
 }
Example #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DbgEngSymbolProvider"/> class.
 /// </summary>
 public DbgEngSymbolProvider(DbgEngDll dbgEngDll)
 {
     DbgEngDll = dbgEngDll;
 }
Example #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StateCache"/> class.
 /// </summary>
 public StateCache(DbgEngDll dbgEngDll)
 {
     CurrentThread     = new DictionaryCache <Process, Thread>(CacheCurrentThread);
     CurrentStackFrame = new DictionaryCache <Thread, StackFrame>(CacheCurrentStackFrame);
     this.dbgEngDll    = dbgEngDll;
 }
Example #28
0
        /// <summary>
        /// Constructor for creating new breakpoints.
        /// </summary>
        /// <param name="breakpointSpec">Spec describing this breakpoint.</param>
        /// <param name="invalidateCache">Invalidate cache action.</param>
        /// <param name="dbgEngDll">DbgEngDll interface.</param>
        /// <remarks>
        /// This about adding some sort of factory pattern here.
        /// </remarks>
        public DbgEngBreakpoint(BreakpointSpec breakpointSpec, Action invalidateCache, DbgEngDll dbgEngDll)
        {
            this.breakpointAction = breakpointSpec.BreakpointAction;
            this.invalidateCache  = invalidateCache;

            unchecked
            {
                if (breakpointSpec.BreakpointType == BreakpointType.Code)
                {
                    breakpoint = dbgEngDll.Control.AddBreakpoint2((uint)Defines.DebugBreakpointCode, (uint)Defines.DebugAnyId);
                }
                else
                {
                    throw new NotImplementedException("Only supports Code breakpoints");
                }
            }

            breakpoint.SetOffset(breakpointSpec.BreakpointAddress);
            breakpoint.SetFlags((uint)Defines.DebugBreakpointEnabled);
            breakpointStatusEnabled = true;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DbgEngOutputCallbacksSwitcher" /> class.
 /// </summary>
 /// <param name="dbgEngDll">The DbgEngDll debugger engine.</param>
 /// <param name="newCallbacks">The new callbacks interface.</param>
 public DbgEngOutputCallbacksSwitcher(DbgEngDll dbgEngDll, IDebugOutputCallbacksWide newCallbacks)
 {
     previousCallbacks = dbgEngDll.Client.GetOutputCallbacksWide();
     dbgEngDll.Client.SetOutputCallbacksWide(newCallbacks);
     this.dbgEngDll = dbgEngDll;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DebuggerTextWriter" /> class.
 /// </summary>
 /// <param name="dbgEngDll">The DbgEngDll debugger engine.</param>
 /// <param name="outputType">Type of the output.</param>
 public DebuggerTextWriter(DbgEngDll dbgEngDll, DebugOutput outputType)
 {
     OutputType = outputType;
     outputCallbacksWide = dbgEngDll.Client.GetOutputCallbacksWide();
     outputCallbacks = dbgEngDll.Client.GetOutputCallbacks();
 }
        private void InterpretInteractive(string code)
        {
            DbgEngDll dbgEngDll = Context.Debugger as DbgEngDll;

            dbgEngDll.ExecuteAction(() => DumpInitialization.InteractiveExecution.Interpret(code));
        }
Example #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DbgEngOutputCallbacksSwitcher" /> class.
 /// </summary>
 /// <param name="dbgEngDll">The DbgEngDll debugger engine.</param>
 /// <param name="newCallbacks">The new callbacks interface.</param>
 public DbgEngOutputCallbacksSwitcher(DbgEngDll dbgEngDll, IDebugOutputCallbacksWide newCallbacks)
 {
     previousCallbacks = dbgEngDll.Client.GetOutputCallbacksWide();
     dbgEngDll.Client.SetOutputCallbacksWide(newCallbacks);
     this.dbgEngDll = dbgEngDll;
 }