_engine.py (10199B)
1 """Direct ctypes binding to dbgeng.dll, the Windows debugger engine. 2 3 No pykd, no compiled extension. The vtable layout and interface IDs come from _abi.py, 4 which is generated from the Windows SDK's DbgEng.h, so the method indices match the 5 installed dll. See the README for why this route instead of pykd. 6 7 This module is Windows only. It loads dbgeng.dll and its neighbours (dbghelp, symsrv) 8 from the Debugging Tools directory. 9 """ 10 11 from __future__ import annotations 12 13 import ctypes 14 import os 15 from ctypes import POINTER, byref, c_char_p, c_uint32, c_ulong, c_ulonglong, c_void_p 16 17 from . import _abi 18 19 # dbgeng constants (from DbgEng.h). 20 DEBUG_OUTCTL_THIS_CLIENT = 0x00000000 21 DEBUG_OUTPUT_NORMAL = 0x00000001 22 DEBUG_EXECUTE_DEFAULT = 0x00000000 23 DEBUG_ONLY_THIS_PROCESS = 0x00000002 24 CREATE_NO_WINDOW = 0x08000000 25 26 # Without this the engine lets a new process run free instead of stopping at its first 27 # instruction, so there is nothing to inspect and WaitForEvent blocks until the process exits. 28 DEBUG_ENGOPT_INITIAL_BREAK = 0x00000020 29 DEBUG_WAIT_DEFAULT = 0x00000000 30 INFINITE = 0xFFFFFFFF 31 DEBUG_END_ACTIVE_TERMINATE = 0x00000001 32 33 # Execution status values the engine reports and takes. 34 DEBUG_STATUS_GO = 1 35 DEBUG_STATUS_STEP_OVER = 4 36 DEBUG_STATUS_STEP_INTO = 5 37 DEBUG_STATUS_BREAK = 6 38 DEBUG_STATUS_NO_DEBUGGEE = 7 39 40 S_OK = 0 41 E_NOINTERFACE = ctypes.c_long(0x80004002).value 42 43 44 class GUID(ctypes.Structure): 45 _fields_ = [("Data1", c_uint32), ("Data2", ctypes.c_uint16), 46 ("Data3", ctypes.c_uint16), ("Data4", ctypes.c_ubyte * 8)] 47 48 49 def _guid(parts) -> GUID: 50 g = GUID() 51 g.Data1, g.Data2, g.Data3 = parts[0], parts[1], parts[2] 52 for i in range(8): 53 g.Data4[i] = parts[3 + i] 54 return g 55 56 57 class DbgEngError(Exception): 58 def __init__(self, where: str, hresult: int): 59 self.hresult = hresult & 0xFFFFFFFF 60 super().__init__(f"{where} failed: 0x{self.hresult:08X}") 61 62 63 def _load_dbgeng() -> ctypes.WinDLL: 64 """Loads dbgeng.dll from the Debugging Tools, so its matching dbghelp/symsrv load too.""" 65 candidates = [ 66 os.environ.get("DBGENG_DIR"), 67 r"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64", 68 r"C:\Program Files\Windows Kits\10\Debuggers\x64", 69 ] 70 for folder in candidates: 71 if folder and os.path.isfile(os.path.join(folder, "dbgeng.dll")): 72 os.add_dll_directory(folder) 73 return ctypes.WinDLL(os.path.join(folder, "dbgeng.dll")) 74 # Fall back to the copy in System32. It works but may lag the SDK's dbghelp. 75 return ctypes.WinDLL("dbgeng.dll") 76 77 78 _dbgeng = _load_dbgeng() 79 _DebugCreate = _dbgeng.DebugCreate 80 _DebugCreate.restype = ctypes.c_long 81 _DebugCreate.argtypes = [POINTER(GUID), POINTER(c_void_p)] 82 83 84 def _method(interface: str, name: str): 85 """(vtable index, ) for a method, looked up by name in the generated table.""" 86 return _abi.INTERFACES[interface]["methods"].index(name) 87 88 89 def _call(this: int, interface: str, name: str, restype, argtypes, *args): 90 """Calls a COM method through the object's vtable. `this` is the interface pointer.""" 91 index = _method(interface, name) 92 vtbl = ctypes.cast(this, POINTER(c_void_p))[0] 93 func_addr = ctypes.cast(vtbl, POINTER(c_void_p))[index] 94 proto = ctypes.WINFUNCTYPE(restype, c_void_p, *argtypes) 95 return proto(func_addr)(this, *args) 96 97 98 def _check(where: str, hr: int): 99 if hr < 0: 100 raise DbgEngError(where, hr) 101 return hr 102 103 104 def _query_interface(this: int, interface: str) -> int: 105 out = c_void_p() 106 iid = _guid(_abi.INTERFACES[interface]["iid"]) 107 _check(f"QueryInterface({interface})", 108 _call(this, "IDebugClient", "QueryInterface", ctypes.c_long, 109 [POINTER(GUID), POINTER(c_void_p)], byref(iid), byref(out))) 110 return out.value 111 112 113 # Function prototypes for the output-callback object we hand to the engine. 114 _QIType = ctypes.WINFUNCTYPE(ctypes.c_long, c_void_p, POINTER(GUID), POINTER(c_void_p)) 115 _RefType = ctypes.WINFUNCTYPE(c_ulong, c_void_p) 116 _OutputType = ctypes.WINFUNCTYPE(ctypes.c_long, c_void_p, c_ulong, c_char_p) 117 118 119 class _OutputSink: 120 """A COM IDebugOutputCallbacks object, built by hand, that appends engine text to a buffer.""" 121 122 def __init__(self): 123 self._chunks: list[str] = [] 124 self._output_iid = _guid(_abi.INTERFACES["IDebugOutputCallbacks"]["iid"]) 125 126 # Keep every callable and the vtable alive for as long as the sink exists. 127 self._qi = _QIType(self._query_interface) 128 self._addref = _RefType(lambda this: 1) 129 self._release = _RefType(lambda this: 1) 130 self._output = _OutputType(self._on_output) 131 132 VtblArray = c_void_p * 4 133 self._vtbl = VtblArray( 134 ctypes.cast(self._qi, c_void_p), ctypes.cast(self._addref, c_void_p), 135 ctypes.cast(self._release, c_void_p), ctypes.cast(self._output, c_void_p)) 136 self._obj = c_void_p(ctypes.cast(self._vtbl, c_void_p).value) 137 138 @property 139 def pointer(self) -> c_void_p: 140 """The address to pass to SetOutputCallbacks: &object, object[0] == &vtable.""" 141 return ctypes.cast(byref(self._obj), c_void_p) 142 143 def take(self) -> str: 144 text = "".join(self._chunks) 145 self._chunks.clear() 146 return text 147 148 def _query_interface(self, this, iid_ptr, out_ptr): 149 want = iid_ptr.contents 150 if bytes(want) == bytes(self._output_iid): 151 out_ptr[0] = this 152 return S_OK 153 out_ptr[0] = None 154 return E_NOINTERFACE 155 156 def _on_output(self, this, mask, text): 157 if text: 158 self._chunks.append(text.decode("utf-8", "replace")) 159 return S_OK 160 161 162 class Engine: 163 """One debugger engine instance. Drives one target at a time.""" 164 165 def __init__(self): 166 client = c_void_p() 167 iid = _guid(_abi.INTERFACES["IDebugClient"]["iid"]) 168 _check("DebugCreate", _DebugCreate(byref(iid), byref(client))) 169 self._client = client.value 170 self._control = _query_interface(self._client, "IDebugControl") 171 self._data = _query_interface(self._client, "IDebugDataSpaces") 172 173 self._sink = _OutputSink() 174 _check("SetOutputCallbacks", 175 _call(self._client, "IDebugClient", "SetOutputCallbacks", ctypes.c_long, 176 [c_void_p], self._sink.pointer)) 177 178 # Stop a freshly created process at its first instruction so there is state to inspect. 179 _check("AddEngineOptions", 180 _call(self._control, "IDebugControl", "AddEngineOptions", ctypes.c_long, 181 [c_ulong], DEBUG_ENGOPT_INITIAL_BREAK)) 182 183 def create_process(self, command_line: str, show_window: bool = False): 184 flags = DEBUG_ONLY_THIS_PROCESS | (0 if show_window else CREATE_NO_WINDOW) 185 buffer = ctypes.create_string_buffer(command_line.encode("utf-8")) 186 _check("CreateProcess", 187 _call(self._client, "IDebugClient", "CreateProcess", ctypes.c_long, 188 [c_ulonglong, c_char_p, c_ulong], 0, ctypes.cast(buffer, c_char_p), flags)) 189 190 def attach(self, pid: int, flags: int = 0): 191 _check("AttachProcess", 192 _call(self._client, "IDebugClient", "AttachProcess", ctypes.c_long, 193 [c_ulonglong, c_ulong, c_ulong], 0, pid, flags)) 194 195 def open_dump(self, path: str): 196 _check("OpenDumpFile", 197 _call(self._client, "IDebugClient", "OpenDumpFile", ctypes.c_long, 198 [c_char_p], path.encode("utf-8"))) 199 200 def wait_for_event(self, timeout_ms: int = INFINITE) -> int: 201 return _check("WaitForEvent", 202 _call(self._control, "IDebugControl", "WaitForEvent", ctypes.c_long, 203 [c_ulong, c_ulong], DEBUG_WAIT_DEFAULT, timeout_ms)) 204 205 def execute(self, command: str) -> str: 206 """Runs a debugger command and returns everything it printed.""" 207 self._sink.take() # drop anything buffered 208 _check("Execute", 209 _call(self._control, "IDebugControl", "Execute", ctypes.c_long, 210 [c_ulong, c_char_p, c_ulong], 211 DEBUG_OUTCTL_THIS_CLIENT, command.encode("utf-8"), DEBUG_EXECUTE_DEFAULT)) 212 return self._sink.take() 213 214 def execution_status(self) -> int: 215 status = c_ulong() 216 _check("GetExecutionStatus", 217 _call(self._control, "IDebugControl", "GetExecutionStatus", ctypes.c_long, 218 [POINTER(c_ulong)], byref(status))) 219 return status.value 220 221 def set_execution_status(self, status: int): 222 _check("SetExecutionStatus", 223 _call(self._control, "IDebugControl", "SetExecutionStatus", ctypes.c_long, 224 [c_ulong], status)) 225 226 def resume(self, status: int, timeout_ms: int = INFINITE) -> int: 227 """Sets execution going (go or a step), waits for the next stop, returns the new status.""" 228 self.set_execution_status(status) 229 try: 230 self.wait_for_event(timeout_ms) 231 except DbgEngError: 232 # A target that runs to exit leaves no event to wait for. Report that rather than raise. 233 if self.execution_status() == DEBUG_STATUS_NO_DEBUGGEE: 234 return DEBUG_STATUS_NO_DEBUGGEE 235 raise 236 return self.execution_status() 237 238 def go(self, timeout_ms: int = INFINITE) -> int: 239 return self.resume(DEBUG_STATUS_GO, timeout_ms) 240 241 def step_into(self, timeout_ms: int = INFINITE) -> int: 242 return self.resume(DEBUG_STATUS_STEP_INTO, timeout_ms) 243 244 def step_over(self, timeout_ms: int = INFINITE) -> int: 245 return self.resume(DEBUG_STATUS_STEP_OVER, timeout_ms) 246 247 def read_virtual(self, address: int, size: int) -> bytes: 248 buffer = (ctypes.c_ubyte * size)() 249 read = c_ulong() 250 _check("ReadVirtual", 251 _call(self._data, "IDebugDataSpaces", "ReadVirtual", ctypes.c_long, 252 [c_ulonglong, c_void_p, c_ulong, POINTER(c_ulong)], 253 address, ctypes.cast(buffer, c_void_p), size, byref(read))) 254 return bytes(buffer[:read.value]) 255 256 def end_session(self): 257 _call(self._client, "IDebugClient", "EndSession", ctypes.c_long, 258 [c_ulong], DEBUG_END_ACTIVE_TERMINATE)