- debugger.py step_over: pdb stops once more at the --Return-- event inside the finishing function, so one extra `next` lands in the caller (GDB `next` behaviour). A --Return-- stop at a breakpoint line is no longer misreported as a breakpoint hit. - debugger_ui.py: sync hit counts from pdb on every stop so the breakpoint pane's Hits column shows the real count. - tests: step over the last line of a function lands in the caller (new test_step_over_last_line_lands_in_caller). Full suite: 240 tests pass.
994 lines
38 KiB
Python
994 lines
38 KiB
Python
"""Step debugger — pdb session backend (no GTK dependency).
|
|
|
|
Drives ``python3 -m pdb`` on a generated Python script in a
|
|
subprocess, mirroring the C GDB/MI session architecture
|
|
(src/debugger.h / GdbSession): staged breakpoints, step
|
|
into/over/out, continue, kill, restart, locals / watches / stack
|
|
frames, target output capture. The UI (debugger_ui.py) polls this
|
|
session; all pdb traffic stays here.
|
|
|
|
Protocol notes (verified against CPython 3.14 pdb, see the probe in
|
|
the Phase 5 report):
|
|
|
|
* pdb stops at the first line on start and prints ``> file(1)func()``
|
|
plus the source line, then the ``(Pdb) `` prompt. Every command's
|
|
reply ends at the next prompt, so the session reads until the
|
|
prompt (or process exit) with a timeout.
|
|
* A breakpoint hit prints the same ``> file(line)func()`` marker;
|
|
the stop reason is inferred: the current line matches a known
|
|
breakpoint -> ``breakpoint-hit``; otherwise after a step command
|
|
-> ``end-stepping-range``; the first stop -> ``entry``.
|
|
* When the program finishes, pdb does NOT exit: it prints ``The
|
|
program finished and will be restarted`` and waits at the first
|
|
line again. That message is the exit event (state Exited); the
|
|
pdb process itself is ended by sending ``quit`` or by killing it.
|
|
* ``break`` (no args) lists breakpoints as ``N breakpoint keep
|
|
yes|no at file:line`` with an optional ``breakpoint already hit
|
|
N time(s)`` continuation line. ``clear N`` deletes silently;
|
|
``disable``/``enable`` print confirmation.
|
|
|
|
The eight documented C debugger bugs, and how this session avoids
|
|
each of them (the UI half is in debugger_ui.py):
|
|
|
|
1. Breakpoint pane too narrow — the UI gives the pane a 420px
|
|
minimum and a 320px location column (see debugger_ui.py).
|
|
2. List selection doesn't stick — the UI updates store rows in
|
|
place by breakpoint id and re-selects the same id (no rebuild).
|
|
3. Step Out in main() modal — there is no modal here: ``step_out``
|
|
sends pdb ``return``; at module level (a single frame) it
|
|
degrades to ``continue`` instead of blocking.
|
|
4. Stop times out on a GUI app — ``stop()`` never waits on the pdb
|
|
prompt: a stopped session gets ``quit``; anything else gets
|
|
SIGTERM then SIGKILL to the whole process group, and the child
|
|
is always reaped.
|
|
5. Run from Stopped/Exited ignores Target — ``run()``/``restart()``
|
|
always restart with the *current* stored target and re-apply
|
|
every breakpoint; there is no stale-target path.
|
|
6. break-on-main temp breakpoint persisted — there are no temp
|
|
breakpoints at all: ``stop_on_entry`` uses pdb's natural first
|
|
stop (no breakpoint is created), and ``break_on_main`` is a
|
|
normal persistent breakpoint on the ``def main():`` line.
|
|
7. Watch clicks open a search popup — the UI disables TreeView
|
|
search on the watch/locals trees and uses no SearchEntry.
|
|
8. Enabled-checkbox toggles ignored — the UI applies the toggle to
|
|
the session first, then updates the store row directly.
|
|
"""
|
|
|
|
import ast
|
|
import os
|
|
import re
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
|
|
PDB_PROMPT = "(Pdb) "
|
|
DEFAULT_TIMEOUT = 10.0
|
|
|
|
# States. Mirrors DbgState (C) minus Starting/Error, which pdb does
|
|
# not distinguish: a failed start reports False + last_error and
|
|
# stays Idle.
|
|
STATE_IDLE = "idle"
|
|
STATE_RUNNING = "running"
|
|
STATE_STOPPED = "stopped"
|
|
STATE_EXITED = "exited"
|
|
|
|
# Dunder names are never shown as locals (they drown the pane in
|
|
# __builtins__ etc. — the probe showed a multi-KB __builtins__ repr).
|
|
_LOCALS_QUERY = ("p [(k, type(v).__name__, repr(v)) for k, v in "
|
|
"list(locals().items()) if not k.startswith('__')]")
|
|
|
|
_FRAME_RE = re.compile(r"^>?\s*(\S+)\((\d+)\)(.*)$")
|
|
_BP_SET_RE = re.compile(r"Breakpoint (\d+) at (.+):(\d+)")
|
|
_BP_ROW_RE = re.compile(
|
|
r"^(\d+)\s+breakpoint\s+\w+\s+(yes|no)\s+at\s+(.+):(\d+)\s*$")
|
|
_BP_HITS_RE = re.compile(r"breakpoint already hit (\d+) time")
|
|
_LOCATION_RE = re.compile(r"^(.*?):(\d+)$")
|
|
_FINISHED_RE = re.compile(r"The program finished")
|
|
|
|
|
|
class DebuggerSettings:
|
|
"""Session settings (C DebuggerSettings, pdb subset)."""
|
|
|
|
def __init__(self, stop_on_entry=True, break_on_main=False,
|
|
default_args="", cmd_timeout_ms=5000,
|
|
stop_timeout_ms=10000):
|
|
self.stop_on_entry = stop_on_entry
|
|
# Persistent breakpoint on the ``def main():`` line (not a
|
|
# temp breakpoint — see the module docstring, bug 6).
|
|
self.break_on_main = break_on_main
|
|
self.default_args = default_args
|
|
self.cmd_timeout_ms = cmd_timeout_ms
|
|
self.stop_timeout_ms = stop_timeout_ms
|
|
|
|
|
|
class Breakpoint:
|
|
"""One breakpoint: pdb number (0 = staged, not yet inserted),
|
|
``file:line`` location, enabled flag, hit count, and the
|
|
optional condition / ignore count (pdb ``break loc, cond`` /
|
|
``ignore N count``)."""
|
|
|
|
def __init__(self, location, bp_id=0, enabled=True, hits=0,
|
|
condition="", ignore_count=0):
|
|
self.id = bp_id
|
|
self.location = location
|
|
self.file = ""
|
|
self.line = 0
|
|
self.enabled = enabled
|
|
self.hits = hits
|
|
self.condition = condition
|
|
self.ignore_count = ignore_count
|
|
parsed = parse_breakpoint_location(location)
|
|
if parsed is not None:
|
|
self.file, self.line, _func = parsed
|
|
|
|
def __repr__(self):
|
|
return ("Breakpoint(id=%r, location=%r, enabled=%r, hits=%r)"
|
|
% (self.id, self.location, self.enabled, self.hits))
|
|
|
|
|
|
class Variable:
|
|
"""One local / watch value: name, type name, repr value."""
|
|
|
|
def __init__(self, name, type_name, value):
|
|
self.name = name
|
|
self.type_name = type_name
|
|
self.value = value
|
|
|
|
def __repr__(self):
|
|
return "Variable(%r, %r, %r)" % (self.name, self.type_name,
|
|
self.value)
|
|
|
|
|
|
class StackFrame:
|
|
"""One frame from ``where``: level, function, file, line."""
|
|
|
|
def __init__(self, level, function, file, line):
|
|
self.level = level
|
|
self.function = function
|
|
self.file = file
|
|
self.line = line
|
|
|
|
def __repr__(self):
|
|
return ("StackFrame(%r, %r, %r, %r)"
|
|
% (self.level, self.function, self.file, self.line))
|
|
|
|
|
|
class StopInfo:
|
|
"""What the last stop was: reason (``breakpoint-hit`` /
|
|
``end-stepping-range`` / ``entry`` / ``exited-normally`` /
|
|
``exited``), the breakpoint id when applicable, the current
|
|
frame, and the exit code once the program has finished."""
|
|
|
|
def __init__(self, reason="", breakpoint_id=0, frame=None,
|
|
exit_code=-1, exited=False):
|
|
self.reason = reason
|
|
self.breakpoint_id = breakpoint_id
|
|
self.frame = frame or StackFrame(0, "", "", 0)
|
|
self.exit_code = exit_code
|
|
self.exited = exited
|
|
|
|
def __repr__(self):
|
|
return ("StopInfo(%r, bp=%r, frame=%r, exit=%r)"
|
|
% (self.reason, self.breakpoint_id, self.frame,
|
|
self.exit_code))
|
|
|
|
|
|
def parse_breakpoint_location(text):
|
|
"""Parse ``file:line`` (or a bare function name) into
|
|
(file, line, function). Returns None when the text is not a
|
|
plausible location. Mirrors C parse_breakpoint_location."""
|
|
text = (text or "").strip()
|
|
if not text:
|
|
return None
|
|
match = _LOCATION_RE.match(text)
|
|
if match:
|
|
try:
|
|
line = int(match.group(2))
|
|
except ValueError:
|
|
return None
|
|
if line <= 0:
|
|
return None
|
|
return (match.group(1), line, "")
|
|
if re.match(r"^[A-Za-z_][A-Za-z0-9_.]*$", text):
|
|
return ("", 0, text)
|
|
return None
|
|
|
|
|
|
def repo_root():
|
|
"""Directory holding the ``lightgui`` package (this file's
|
|
parent's parent) — put on PYTHONPATH for the debuggee so a
|
|
generated script can ``import lightgui``."""
|
|
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
|
|
def _run_env(extra=None):
|
|
env = dict(os.environ)
|
|
root = repo_root()
|
|
parts = [p for p in env.get("PYTHONPATH", "").split(os.pathsep)
|
|
if p]
|
|
if root not in parts:
|
|
parts.insert(0, root)
|
|
env["PYTHONPATH"] = os.pathsep.join(parts)
|
|
if extra:
|
|
env.update(extra)
|
|
return env
|
|
|
|
|
|
def _parse_frame_line(line):
|
|
"""Parse one pdb ``> file(line)func()`` / ``where`` line into a
|
|
StackFrame (level 0), or None."""
|
|
match = _FRAME_RE.match(line.strip())
|
|
if not match:
|
|
return None
|
|
try:
|
|
line_no = int(match.group(2))
|
|
except ValueError:
|
|
return None
|
|
func = match.group(3)
|
|
# A --Return-- marker carries the return value:
|
|
# ``helper()->11`` -> ``helper``.
|
|
if "()->" in func:
|
|
func = func.split("()->", 1)[0]
|
|
elif func.endswith("()"):
|
|
func = func[:-2]
|
|
return StackFrame(0, func, match.group(1), line_no)
|
|
|
|
|
|
class PdbSession:
|
|
"""A pdb subprocess driving one target script.
|
|
|
|
Only one session runs at a time per instance. All public
|
|
methods that talk to pdb return bool and set ``last_error`` on
|
|
failure; ``state`` is one of idle/running/stopped/exited.
|
|
"""
|
|
|
|
def __init__(self, settings=None, python=sys.executable):
|
|
self.settings = settings or DebuggerSettings()
|
|
self.python = python
|
|
self.state = STATE_IDLE
|
|
self.script_path = None
|
|
self.args = ""
|
|
self.last_error = ""
|
|
self.last_stop = StopInfo()
|
|
self._stop_seq = 0
|
|
self._last_exec_response = ""
|
|
self._breakpoints = [] # Breakpoint, live (id>0) or staged
|
|
self._watch_exprs = []
|
|
self._watches = []
|
|
self._locals = []
|
|
self._frames = []
|
|
self._proc = None
|
|
self._reader = None
|
|
self._reader_stop = threading.Event()
|
|
self._prompt_event = threading.Event()
|
|
self._exited_event = threading.Event()
|
|
self._lock = threading.Lock()
|
|
self._raw = [] # all output text, in order
|
|
self._resp = [] # output since the last command
|
|
self._resp_start = 0 # index into _raw of current reply
|
|
|
|
# --- introspection ----------------------------------------------------
|
|
|
|
def stop_seq(self):
|
|
"""Monotonic stop counter (C stop_seq): incremented on every
|
|
fresh stop, so a UI poll can tell a new stop from a stale
|
|
Stopped state."""
|
|
return self._stop_seq
|
|
|
|
def breakpoints(self):
|
|
return list(self._breakpoints)
|
|
|
|
def watches(self):
|
|
return list(self._watches)
|
|
|
|
def locals(self):
|
|
return list(self._locals)
|
|
|
|
def frames(self):
|
|
return list(self._frames)
|
|
|
|
def target_output(self):
|
|
"""All debuggee + pdb output so far."""
|
|
with self._lock:
|
|
return "".join(self._raw)
|
|
|
|
def clear_output(self):
|
|
with self._lock:
|
|
self._raw = []
|
|
self._resp = []
|
|
self._resp_start = 0
|
|
|
|
def is_alive(self):
|
|
return self._proc is not None and self._proc.poll() is None
|
|
|
|
def target_running(self):
|
|
return self.state == STATE_RUNNING
|
|
|
|
# --- lifecycle ----------------------------------------------------------
|
|
|
|
def start(self, script_path, args=None):
|
|
"""Start pdb on *script_path* (re-applying every breakpoint
|
|
kept from a previous run). Returns True on the initial stop
|
|
(or, with stop_on_entry False, after the auto-continue).
|
|
A live session is shut down first, so start() is also the
|
|
clean restart path (bug 5: Run from Stopped/Exited always
|
|
uses the current target)."""
|
|
if not script_path or not os.path.isfile(script_path):
|
|
self.last_error = "no such script: %s" % script_path
|
|
return False
|
|
self.shutdown()
|
|
self.script_path = os.path.abspath(script_path)
|
|
self.args = args if args is not None else self.settings.default_args
|
|
argv = [self.python, "-u", "-m", "pdb", self.script_path]
|
|
if self.args:
|
|
argv.extend(self.args.split())
|
|
try:
|
|
self._proc = subprocess.Popen(
|
|
argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT, text=False,
|
|
start_new_session=True, env=_run_env())
|
|
except OSError as exc:
|
|
self.last_error = "cannot start pdb: %s" % exc
|
|
return False
|
|
self._prompt_event.clear()
|
|
self._exited_event.clear()
|
|
self._reader_stop.clear()
|
|
with self._lock:
|
|
self._raw = []
|
|
self._resp = []
|
|
self._resp_start = 0
|
|
self._reader = threading.Thread(target=self._reader_loop,
|
|
daemon=True)
|
|
self._reader.start()
|
|
self.state = STATE_RUNNING
|
|
if not self._wait_prompt(self.settings.stop_timeout_ms / 1000.0):
|
|
self.last_error = "pdb did not reach its first prompt"
|
|
self.state = STATE_IDLE
|
|
self.shutdown()
|
|
return False
|
|
self.state = STATE_STOPPED
|
|
self._note_stop("entry", self._last_response())
|
|
# Re-apply kept breakpoints, then the break-on-main one.
|
|
for bp in list(self._breakpoints):
|
|
self._insert_live(bp)
|
|
if self.settings.break_on_main:
|
|
main_line = _find_main_def_line(self.script_path)
|
|
if main_line:
|
|
self.add_breakpoint("%s:%d" % (self.script_path,
|
|
main_line))
|
|
if not self.settings.stop_on_entry:
|
|
# Short wait: a GUI target runs on past the entry stop
|
|
# and the UI poll picks up its later stops.
|
|
return self.cont(timeout_s=0.5)
|
|
self.refresh_on_stop()
|
|
return True
|
|
|
|
def run(self):
|
|
"""(Re)run from the start with the current target — the C
|
|
toolbar Run behaviour: from Idle it starts the target; from
|
|
Stopped/Exited it restarts it cleanly (bug 5)."""
|
|
if self.script_path is None:
|
|
self.last_error = "no target — nothing to run"
|
|
return False
|
|
return self.start(self.script_path, self.args)
|
|
|
|
def restart(self):
|
|
"""Kill (if running) and run the target again."""
|
|
return self.run()
|
|
|
|
def shutdown(self):
|
|
"""End the pdb process and reap it. Safe to call repeatedly;
|
|
never blocks on the pdb prompt (bug 4)."""
|
|
self.stop()
|
|
if self._reader is not None:
|
|
self._reader_stop.set()
|
|
self._reader.join(timeout=2.0)
|
|
self._reader = None
|
|
self.state = STATE_IDLE
|
|
|
|
def stop(self):
|
|
"""Terminate the debuggee. A session stopped at a prompt gets
|
|
a clean ``quit``; anything else (running GUI app, hung
|
|
target) gets SIGTERM to the whole process group, then
|
|
SIGKILL, then a reap — so Stop can never hang (bug 4)."""
|
|
proc = self._proc
|
|
if proc is None:
|
|
self.state = STATE_EXITED if self.script_path else STATE_IDLE
|
|
return True
|
|
if proc.poll() is not None:
|
|
self._reap()
|
|
return True
|
|
# Clean quit when pdb is sitting at a prompt.
|
|
if self._prompt_event.is_set():
|
|
try:
|
|
proc.stdin.write(b"quit\n")
|
|
proc.stdin.flush()
|
|
except (BrokenPipeError, OSError):
|
|
pass
|
|
try:
|
|
proc.wait(timeout=2.0)
|
|
except subprocess.TimeoutExpired:
|
|
pass
|
|
if proc.poll() is None:
|
|
try:
|
|
os.killpg(proc.pid, signal.SIGTERM)
|
|
except (ProcessLookupError, PermissionError, OSError):
|
|
try:
|
|
proc.terminate()
|
|
except OSError:
|
|
pass
|
|
try:
|
|
proc.wait(timeout=2.0)
|
|
except subprocess.TimeoutExpired:
|
|
try:
|
|
os.killpg(proc.pid, signal.SIGKILL)
|
|
except (ProcessLookupError, PermissionError, OSError):
|
|
try:
|
|
proc.kill()
|
|
except OSError:
|
|
pass
|
|
try:
|
|
proc.wait(timeout=2.0)
|
|
except subprocess.TimeoutExpired:
|
|
pass
|
|
self._reap()
|
|
return True
|
|
|
|
def _reap(self):
|
|
"""Mark the session exited once the child is gone."""
|
|
proc = self._proc
|
|
if proc is not None and proc.poll() is None:
|
|
try:
|
|
proc.wait(timeout=1.0)
|
|
except subprocess.TimeoutExpired:
|
|
pass
|
|
self._proc = None
|
|
self._exited_event.set()
|
|
self.state = STATE_EXITED
|
|
|
|
# --- reader -------------------------------------------------------------
|
|
|
|
def _reader_loop(self):
|
|
"""Read pdb output byte-wise until the ``(Pdb) `` prompt (it
|
|
has no trailing newline, so readline() would block) or EOF.
|
|
Appends to the raw log and to the current command's reply;
|
|
sets the prompt event on each prompt, the exited event on
|
|
EOF."""
|
|
fd = self._proc.stdout.fileno()
|
|
buf = b""
|
|
while not self._reader_stop.is_set():
|
|
try:
|
|
chunk = os.read(fd, 4096)
|
|
except OSError:
|
|
break
|
|
if not chunk:
|
|
break
|
|
buf += chunk
|
|
text = buf.decode("utf-8", "replace")
|
|
buf = b""
|
|
with self._lock:
|
|
self._raw.append(text)
|
|
self._resp.append(text)
|
|
if text.endswith(PDB_PROMPT) or PDB_PROMPT in text:
|
|
# Prompt is always at the end of a chunk boundary
|
|
# once pdb is idle; require the tail match so target
|
|
# output merely mentioning "(Pdb)" does not count.
|
|
with self._lock:
|
|
tail = "".join(self._raw)[-len(PDB_PROMPT):]
|
|
if tail == PDB_PROMPT:
|
|
self._prompt_event.set()
|
|
self._exited_event.set()
|
|
if self._proc is not None and self._proc.poll() is not None:
|
|
self.state = STATE_EXITED
|
|
|
|
def _last_response(self):
|
|
"""Text of the current command's reply (since the last
|
|
command was sent), prompt stripped."""
|
|
with self._lock:
|
|
text = "".join(self._resp)
|
|
if text.endswith(PDB_PROMPT):
|
|
text = text[:-len(PDB_PROMPT)]
|
|
return text
|
|
|
|
def _send(self, command):
|
|
"""Send one pdb command; clears the prompt event and the
|
|
reply buffer first. Returns False when there is no live
|
|
process."""
|
|
if self._proc is None or self._proc.poll() is not None:
|
|
return False
|
|
self._prompt_event.clear()
|
|
with self._lock:
|
|
self._resp = []
|
|
try:
|
|
self._proc.stdin.write((command + "\n").encode("utf-8"))
|
|
self._proc.stdin.flush()
|
|
except (BrokenPipeError, OSError):
|
|
return False
|
|
return True
|
|
|
|
def _wait_prompt(self, timeout_s):
|
|
"""Wait for the next prompt or for the process to exit.
|
|
Returns True when pdb is idle at a prompt (or the program
|
|
finished and pdb is waiting at the first line again)."""
|
|
deadline = time.time() + max(timeout_s, 0.1)
|
|
while time.time() < deadline:
|
|
if self._prompt_event.wait(timeout=0.1):
|
|
return True
|
|
if self._exited_event.is_set() \
|
|
and self._proc is not None \
|
|
and self._proc.poll() is not None:
|
|
return True
|
|
if self._proc is not None and self._proc.poll() is not None:
|
|
return True
|
|
return self._prompt_event.is_set()
|
|
|
|
def _note_stop(self, reason, response):
|
|
"""Record a stop from a command's *response*: current frame,
|
|
breakpoint hit, finished-program detection. Increments the
|
|
stop sequence."""
|
|
frame = None
|
|
for line in reversed(response.splitlines()):
|
|
parsed = _parse_frame_line(line)
|
|
if parsed is not None:
|
|
frame = parsed
|
|
break
|
|
bp_id = 0
|
|
if frame is not None and "--Return--" not in response:
|
|
# A --Return-- stop is reported at the returning
|
|
# function's last line, which may itself be a
|
|
# breakpoint line — that is a step stop, not a hit.
|
|
for bp in self._breakpoints:
|
|
if bp.id and bp.file == frame.file \
|
|
and bp.line == frame.line and bp.enabled:
|
|
bp_id = bp.id
|
|
reason = "breakpoint-hit"
|
|
break
|
|
exited = False
|
|
exit_code = -1
|
|
if _FINISHED_RE.search(response):
|
|
exited = True
|
|
reason = "exited-normally"
|
|
if "Traceback (most recent call last)" not in response:
|
|
exit_code = 0
|
|
self._stop_seq += 1
|
|
self.last_stop = StopInfo(reason, bp_id, frame, exit_code,
|
|
exited)
|
|
self.state = STATE_EXITED if exited else STATE_STOPPED
|
|
if frame is not None:
|
|
self._frames = [frame]
|
|
|
|
# --- execution control ----------------------------------------------------
|
|
|
|
def _exec(self, command, timeout_s=None):
|
|
"""Send an execution command (continue/step/...) and wait
|
|
for the next stop. Returns False + last_error when pdb does
|
|
not stop in time; the session is then left Running and the
|
|
caller may still stop() it."""
|
|
if self.state not in (STATE_STOPPED, STATE_EXITED):
|
|
self.last_error = "cannot %s while %s" % (command,
|
|
self.state)
|
|
return False
|
|
if self.state == STATE_EXITED:
|
|
# Continuing a finished program restarts it from line 1
|
|
# (pdb behaviour); a clean restart is run()/restart().
|
|
self.last_error = ("program has exited — use Run to "
|
|
"start it again")
|
|
return False
|
|
if timeout_s is None:
|
|
timeout_s = self.settings.stop_timeout_ms / 1000.0
|
|
self.state = STATE_RUNNING
|
|
if not self._send(command):
|
|
self.last_error = "pdb process is gone"
|
|
self.state = STATE_EXITED
|
|
return False
|
|
if not self._wait_prompt(timeout_s):
|
|
# Still running (e.g. sitting in Gtk.main()) — not an
|
|
# error; the UI poll picks up the stop when it lands.
|
|
self.last_error = ""
|
|
self._last_exec_response = ""
|
|
return True
|
|
response = self._last_response()
|
|
self._last_exec_response = response
|
|
reason = "end-stepping-range" if command != "continue" \
|
|
else "breakpoint-hit"
|
|
self._note_stop(reason, response)
|
|
if self.state == STATE_STOPPED:
|
|
self.refresh_on_stop()
|
|
return True
|
|
|
|
def cont(self, timeout_s=None):
|
|
"""Continue until the next breakpoint, or exit. *timeout_s*
|
|
bounds how long the caller waits for the stop; a running
|
|
target (e.g. a GUI app in Gtk.main()) returns promptly with
|
|
state Running and the UI poll picks up the stop when it
|
|
lands."""
|
|
return self._exec("continue", timeout_s)
|
|
|
|
def step_into(self, timeout_s=None):
|
|
"""Step into the called function (pdb ``step``)."""
|
|
return self._exec("step", timeout_s)
|
|
|
|
def step_over(self, timeout_s=None):
|
|
"""Step over the current line (pdb ``next``). Stepping over
|
|
the last line of a function stops at pdb's ``--Return--``
|
|
event inside that function; one more step lands in the
|
|
caller, like GDB's ``next``."""
|
|
if not self._exec("next", timeout_s):
|
|
return False
|
|
if "--Return--" in self._last_exec_response:
|
|
return self._exec("next", timeout_s)
|
|
return True
|
|
|
|
def step_out(self, timeout_s=None):
|
|
"""Step out of the current function (pdb ``return``). At
|
|
module level there is no caller, so this degrades to
|
|
``continue`` instead of blocking (bug 3: no modal). pdb
|
|
stops once more at the ``--Return--`` event inside the same
|
|
function, so one extra ``next`` lands in the caller — the
|
|
GDB ``finish`` behaviour."""
|
|
# ``where`` lists bdb.py frames too, so the frame count
|
|
# cannot decide this: the current frame's function can. At
|
|
# module level there is no caller, so Step Out degrades to
|
|
# Continue (which still stops at breakpoints) instead of
|
|
# blocking (bug 3: no modal).
|
|
if self.last_stop.frame \
|
|
and self.last_stop.frame.function in ("<module>", ""):
|
|
return self._exec("continue", timeout_s)
|
|
if not self._exec("return", timeout_s):
|
|
return False
|
|
if "--Return--" in self._last_exec_response:
|
|
return self._exec("next", timeout_s)
|
|
return True
|
|
|
|
def wait_for_stop(self, timeout_ms=-1):
|
|
"""Wait until the target stops (breakpoint/step/exit) or
|
|
*timeout_ms* elapses. True when a stop arrived."""
|
|
if timeout_ms < 0:
|
|
timeout_ms = self.settings.stop_timeout_ms
|
|
before = self._stop_seq
|
|
ok = self._wait_prompt(timeout_ms / 1000.0)
|
|
if ok and self._stop_seq == before \
|
|
and self._prompt_event.is_set():
|
|
self._note_stop("end-stepping-range",
|
|
self._last_response())
|
|
self.refresh_on_stop()
|
|
return ok and self._stop_seq > before
|
|
|
|
def poll_events(self):
|
|
"""Non-blocking drain for the UI poll tick: if a fresh stop
|
|
landed since the last poll, record it and refresh panes.
|
|
Returns True when a new stop was picked up."""
|
|
if not self._prompt_event.is_set():
|
|
return False
|
|
if self.state != STATE_RUNNING:
|
|
return False
|
|
self._note_stop("end-stepping-range", self._last_response())
|
|
if self.state == STATE_STOPPED:
|
|
self.refresh_on_stop()
|
|
return True
|
|
|
|
# --- breakpoints ----------------------------------------------------------
|
|
|
|
def _insert_live(self, bp):
|
|
"""Insert a staged/kept breakpoint into the live pdb. On
|
|
success the Breakpoint gains its pdb id; on failure it stays
|
|
staged (id 0) and last_error is set."""
|
|
if self._proc is None or self.state != STATE_STOPPED:
|
|
return False
|
|
cmd = "break %s" % bp.location
|
|
if bp.condition:
|
|
cmd += ", %s" % bp.condition
|
|
if not self._send(cmd):
|
|
return False
|
|
if not self._wait_prompt(
|
|
self.settings.cmd_timeout_ms / 1000.0):
|
|
self.last_error = "pdb did not answer break"
|
|
return False
|
|
response = self._last_response()
|
|
match = _BP_SET_RE.search(response)
|
|
if not match:
|
|
self.last_error = response.strip().splitlines()[-1] \
|
|
if response.strip() else "breakpoint rejected"
|
|
return False
|
|
bp.id = int(match.group(1))
|
|
bp.file = match.group(2)
|
|
bp.line = int(match.group(3))
|
|
if bp.ignore_count:
|
|
self._send("ignore %d %d" % (bp.id, bp.ignore_count))
|
|
self._wait_prompt(self.settings.cmd_timeout_ms / 1000.0)
|
|
if not bp.enabled:
|
|
self._send("disable %d" % bp.id)
|
|
self._wait_prompt(self.settings.cmd_timeout_ms / 1000.0)
|
|
return True
|
|
|
|
def add_breakpoint(self, location, condition="", ignore_count=0,
|
|
enabled=True):
|
|
"""Add a breakpoint at ``file:line``. Before start (or when
|
|
the session is not stopped) it is staged for the next Run;
|
|
live, it is inserted into pdb at once. Returns the
|
|
Breakpoint, or None + last_error when the location does not
|
|
parse or pdb rejects it."""
|
|
parsed = parse_breakpoint_location(location)
|
|
if parsed is None:
|
|
self.last_error = "bad breakpoint location: %r" % location
|
|
return None
|
|
existing = self.find_breakpoint(location)
|
|
if existing is not None:
|
|
self.last_error = "breakpoint already set at %s" % location
|
|
return existing
|
|
bp = Breakpoint(location, enabled=enabled,
|
|
condition=condition, ignore_count=ignore_count)
|
|
bp.file, bp.line, _func = parsed
|
|
if self.state == STATE_STOPPED and self.is_alive():
|
|
if not self._insert_live(bp):
|
|
return None
|
|
self._breakpoints.append(bp)
|
|
return bp
|
|
|
|
def find_breakpoint(self, location):
|
|
"""Breakpoint at *location* (``file:line``), or None. The
|
|
file part is compared by basename + absolute path, so a
|
|
breakpoint set as ``script.py:6`` matches the resolved
|
|
``/abs/path/script.py:6``."""
|
|
parsed = parse_breakpoint_location(location)
|
|
if parsed is None:
|
|
return None
|
|
want_file, want_line, _func = parsed
|
|
for bp in self._breakpoints:
|
|
if bp.line != want_line:
|
|
continue
|
|
if bp.file == want_file or (
|
|
want_file and os.path.basename(bp.file)
|
|
== os.path.basename(want_file)):
|
|
return bp
|
|
return None
|
|
|
|
def remove_breakpoint(self, bp_id):
|
|
"""Remove breakpoint *bp_id* (live or staged). Returns False
|
|
when the id is unknown."""
|
|
bp = next((b for b in self._breakpoints if b.id == bp_id),
|
|
None)
|
|
if bp is None:
|
|
# Staged breakpoints have id 0; match by object identity
|
|
# is handled by remove_staged_breakpoint().
|
|
self.last_error = "no breakpoint %r" % bp_id
|
|
return False
|
|
if bp.id and self.state == STATE_STOPPED and self.is_alive():
|
|
if not self._send("clear %d" % bp.id):
|
|
return False
|
|
self._wait_prompt(self.settings.cmd_timeout_ms / 1000.0)
|
|
self._breakpoints.remove(bp)
|
|
return True
|
|
|
|
def remove_staged_breakpoint(self, location):
|
|
"""Erase a staged (not yet inserted, id 0) breakpoint by
|
|
location. False when not staged."""
|
|
bp = self.find_breakpoint(location)
|
|
if bp is None or bp.id != 0:
|
|
return False
|
|
self._breakpoints.remove(bp)
|
|
return True
|
|
|
|
def toggle_breakpoint(self, file, line):
|
|
"""Toggle a breakpoint at (*file*, *line*). Returns True when
|
|
a breakpoint is now set there (C debugger_toggle_breakpoint).
|
|
With a live session the change applies at once; otherwise it
|
|
is staged for the next Run."""
|
|
location = "%s:%d" % (file, line)
|
|
bp = self.find_breakpoint(location)
|
|
if bp is not None:
|
|
if bp.id == 0:
|
|
self.remove_staged_breakpoint(location)
|
|
else:
|
|
self.remove_breakpoint(bp.id)
|
|
return False
|
|
return self.add_breakpoint(location) is not None
|
|
|
|
def has_breakpoint(self, file, line):
|
|
return self.find_breakpoint("%s:%d" % (file, line)) is not None
|
|
|
|
def breakpoint_lines(self, file):
|
|
"""1-based lines in *file* that currently have breakpoints."""
|
|
lines = []
|
|
for bp in self._breakpoints:
|
|
if bp.file == file or (file and os.path.basename(bp.file)
|
|
== os.path.basename(file)):
|
|
lines.append(bp.line)
|
|
return sorted(lines)
|
|
|
|
def enable_breakpoint(self, bp_id, enable):
|
|
"""Enable/disable breakpoint *bp_id*. Live: pdb
|
|
enable/disable; staged: the flag is stored and applied on
|
|
insert. Returns False when the id is unknown."""
|
|
bp = next((b for b in self._breakpoints if b.id == bp_id),
|
|
None)
|
|
if bp is None:
|
|
if bp_id == 0:
|
|
return False
|
|
self.last_error = "no breakpoint %r" % bp_id
|
|
return False
|
|
if bp.id and self.state == STATE_STOPPED and self.is_alive():
|
|
if not self._send("enable %d" % bp.id if enable
|
|
else "disable %d" % bp.id):
|
|
return False
|
|
if not self._wait_prompt(
|
|
self.settings.cmd_timeout_ms / 1000.0):
|
|
self.last_error = "pdb did not answer enable/disable"
|
|
return False
|
|
bp.enabled = bool(enable)
|
|
return True
|
|
|
|
def refresh_breakpoints(self):
|
|
"""Re-list breakpoints from pdb (live only) and sync ids,
|
|
enabled flags and hit counts. Staged entries are untouched."""
|
|
if self.state != STATE_STOPPED or not self.is_alive():
|
|
return False
|
|
if not self._send("break"):
|
|
return False
|
|
if not self._wait_prompt(
|
|
self.settings.cmd_timeout_ms / 1000.0):
|
|
return False
|
|
response = self._last_response()
|
|
listed = {}
|
|
last_id = None
|
|
for line in response.splitlines():
|
|
row = _BP_ROW_RE.match(line.strip())
|
|
if row:
|
|
last_id = int(row.group(1))
|
|
listed[last_id] = {
|
|
"enabled": row.group(2) == "yes",
|
|
"file": row.group(3),
|
|
"line": int(row.group(4)),
|
|
"hits": 0,
|
|
}
|
|
continue
|
|
hits = _BP_HITS_RE.search(line)
|
|
if hits and last_id in listed:
|
|
listed[last_id]["hits"] = int(hits.group(1))
|
|
for bp in self._breakpoints:
|
|
if bp.id and bp.id in listed:
|
|
info = listed[bp.id]
|
|
bp.enabled = info["enabled"]
|
|
bp.hits = info["hits"]
|
|
bp.file = info["file"]
|
|
bp.line = info["line"]
|
|
return True
|
|
|
|
# --- inspection (valid while stopped) ---------------------------------------
|
|
|
|
def _eval(self, command, timeout_s=None):
|
|
"""Send a query command (``p ...`` / ``where``) while
|
|
stopped and return its reply text, or None."""
|
|
if self.state != STATE_STOPPED or not self.is_alive():
|
|
return None
|
|
if timeout_s is None:
|
|
timeout_s = self.settings.cmd_timeout_ms / 1000.0
|
|
if not self._send(command):
|
|
return None
|
|
if not self._wait_prompt(timeout_s):
|
|
return None
|
|
return self._last_response()
|
|
|
|
def evaluate(self, expr):
|
|
"""Evaluate *expr* in the current frame. Returns
|
|
(value_repr, error): on failure value is None and error
|
|
holds pdb's ``*** ...`` message."""
|
|
expr = (expr or "").strip()
|
|
if not expr:
|
|
return None, "empty expression"
|
|
response = self._eval("p %s" % expr)
|
|
if response is None:
|
|
return None, "not stopped at a breakpoint"
|
|
lines = [ln for ln in response.splitlines() if ln.strip()]
|
|
for line in lines:
|
|
if line.startswith("***"):
|
|
return None, line[3:].strip()
|
|
if not lines:
|
|
return None, "no result"
|
|
return lines[0], ""
|
|
|
|
def list_locals(self):
|
|
"""Locals of the current frame as [Variable]. Dunder names
|
|
are excluded by the query itself; on any parse failure the
|
|
raw reply is returned as a single variable."""
|
|
response = self._eval(_LOCALS_QUERY)
|
|
if response is None:
|
|
return []
|
|
text = response.strip()
|
|
try:
|
|
items = ast.literal_eval(text)
|
|
except (ValueError, SyntaxError):
|
|
items = None
|
|
if not isinstance(items, list):
|
|
return [Variable("<locals>", "", text)] if text else []
|
|
out = []
|
|
for item in items:
|
|
if isinstance(item, (list, tuple)) and len(item) == 3:
|
|
out.append(Variable(str(item[0]), str(item[1]),
|
|
str(item[2])))
|
|
return out
|
|
|
|
def list_frames(self):
|
|
"""Stack frames from ``where`` (all frames, innermost last
|
|
in pdb's listing — reversed here so level 0 is innermost)."""
|
|
response = self._eval("where")
|
|
if response is None:
|
|
return []
|
|
frames = []
|
|
for line in response.splitlines():
|
|
parsed = _parse_frame_line(line)
|
|
if parsed is not None:
|
|
frames.append(parsed)
|
|
frames.reverse()
|
|
for i, frame in enumerate(frames):
|
|
frame.level = i
|
|
return frames
|
|
|
|
def add_watch(self, expr):
|
|
"""Add a watch expression (kept in-session, refreshed by
|
|
refresh_watches). False when empty or already watched."""
|
|
expr = (expr or "").strip()
|
|
if not expr or expr in self._watch_exprs:
|
|
return False
|
|
self._watch_exprs.append(expr)
|
|
self.refresh_watches()
|
|
return True
|
|
|
|
def remove_watch(self, expr):
|
|
if expr in self._watch_exprs:
|
|
self._watch_exprs.remove(expr)
|
|
self._watches = [w for w in self._watches
|
|
if w.name != expr]
|
|
return True
|
|
return False
|
|
|
|
def watch_exprs(self):
|
|
return list(self._watch_exprs)
|
|
|
|
def refresh_watches(self):
|
|
if self.state != STATE_STOPPED:
|
|
return False
|
|
out = []
|
|
for expr in self._watch_exprs:
|
|
value, err = self.evaluate(expr)
|
|
out.append(Variable(expr, "",
|
|
value if err == "" else
|
|
"*** %s" % err))
|
|
self._watches = out
|
|
return True
|
|
|
|
def refresh_on_stop(self):
|
|
"""Refresh locals + frames + watches after a stop (best
|
|
effort; a failure leaves the previous values in place)."""
|
|
if self.state != STATE_STOPPED:
|
|
return
|
|
try:
|
|
self._locals = self.list_locals()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
frames = self.list_frames()
|
|
if frames:
|
|
self._frames = frames
|
|
except Exception:
|
|
pass
|
|
try:
|
|
self.refresh_watches()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _find_main_def_line(script_path):
|
|
"""Line number of ``def main(...):`` in *script_path*, or None
|
|
(used by the break_on_main setting)."""
|
|
try:
|
|
with open(script_path, "r", encoding="utf-8") as handle:
|
|
for number, line in enumerate(handle, start=1):
|
|
if re.match(r"def\s+main\s*\(", line):
|
|
return number
|
|
except OSError:
|
|
return None
|
|
return None
|