worker.py (4033B)
1 """Debugger worker. Runs under Windows Python, owns one dbgeng engine, and speaks 2 line-delimited JSON on stdin/stdout. The MCP server spawns one of these per session. 3 4 Kept in its own process on purpose: dbgeng is stateful and blocking, and running an 5 untrusted target under it is safer behind a process boundary the server can kill. 6 7 Protocol: one JSON object per line in, one per line out. 8 in: {"id": 1, "cmd": "open", "args": {"mode": "launch", "target": "ping -n 2 127.0.0.1"}} 9 out: {"id": 1, "ok": true, "result": {...}} 10 {"id": 1, "ok": false, "error": "..."} 11 """ 12 13 import json 14 import sys 15 16 # Allow `python.exe worker.py` to find the package when run straight from the source tree. 17 if __package__ in (None, ""): 18 import os 19 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 20 21 from dbgeng_mcp._engine import Engine # noqa: E402 22 23 STATUS_NAMES = {0: "no_change", 1: "go", 4: "step_over", 5: "step_into", 24 6: "break", 7: "no_debuggee"} 25 26 27 class Worker: 28 def __init__(self): 29 self.engine: Engine | None = None 30 31 def handle(self, cmd: str, args: dict): 32 return getattr(self, f"cmd_{cmd}")(**args) 33 34 def _require(self) -> Engine: 35 if self.engine is None: 36 raise RuntimeError("No target is open. Call open first.") 37 return self.engine 38 39 def _stop_state(self, status: int) -> dict: 40 """Where the target is after a stop: status name and the current instruction.""" 41 name = STATUS_NAMES.get(status, status) 42 if status == 7: # no_debuggee: the target exited, so there is nothing to disassemble 43 return {"status": name, "location": "target has exited"} 44 where = self._require().execute("u @rip L1").strip().splitlines() 45 return {"status": name, "location": where[-1].strip() if where else ""} 46 47 def cmd_open(self, mode: str, target) -> dict: 48 if self.engine is not None: 49 self.engine.end_session() 50 self.engine = None 51 engine = Engine() 52 if mode == "launch": 53 engine.create_process(str(target)) 54 elif mode == "attach": 55 engine.attach(int(target)) 56 elif mode == "dump": 57 engine.open_dump(str(target)) 58 else: 59 raise ValueError(f"unknown mode {mode!r} (launch, attach, or dump)") 60 engine.wait_for_event() 61 self.engine = engine 62 return self._stop_state(engine.execution_status()) 63 64 def cmd_execute(self, command: str) -> dict: 65 return {"output": self._require().execute(command)} 66 67 def cmd_go(self) -> dict: 68 return self._stop_state(self._require().go()) 69 70 def cmd_step(self, kind: str = "into") -> dict: 71 engine = self._require() 72 status = engine.step_over() if kind == "over" else engine.step_into() 73 return self._stop_state(status) 74 75 def cmd_read_memory(self, address, size: int) -> dict: 76 data = self._require().read_virtual(int(address, 0) if isinstance(address, str) else address, size) 77 return {"address": address, "size": len(data), "hex": data.hex()} 78 79 def cmd_registers(self) -> dict: 80 return {"output": self._require().execute("r")} 81 82 def cmd_close(self) -> dict: 83 if self.engine is not None: 84 self.engine.end_session() 85 self.engine = None 86 return {"closed": True} 87 88 def cmd_ping(self) -> dict: 89 return {"pong": True} 90 91 92 def main(): 93 worker = Worker() 94 for line in sys.stdin: 95 line = line.strip() 96 if not line: 97 continue 98 request = json.loads(line) 99 response = {"id": request.get("id")} 100 try: 101 response["ok"] = True 102 response["result"] = worker.handle(request["cmd"], request.get("args", {})) 103 except Exception as error: 104 response["ok"] = False 105 response["error"] = f"{type(error).__name__}: {error}" 106 sys.stdout.write(json.dumps(response) + "\n") 107 sys.stdout.flush() 108 109 110 if __name__ == "__main__": 111 main()