diff --git a/crates/lightgui-debug/src/lib.rs b/crates/lightgui-debug/src/lib.rs index d6a604b..8c929e8 100644 --- a/crates/lightgui-debug/src/lib.rs +++ b/crates/lightgui-debug/src/lib.rs @@ -17,6 +17,36 @@ //! `-break-condition`) or logpoint (a gdb dprintf: prints a message and //! never stops). Any kind may also carry an ignore count and a group //! label. See `Breakpoint` for the full contract. +//! +//! The eight documented C debugger bugs +//! (`docs/step-debugger-guide.md` in lightgui), and how this port +//! stands on each: +//! +//! * (a) Breakpoint pane too narrow, (b) list selection doesn't +//! stick, (g) watch clicks open a search popup, (h) checkbox +//! toggles ignored — UI bugs. There is no debugger UI in the Rust +//! designer yet (the Debug menu entries only report that the +//! debugger lives here), so none of these can occur; whoever builds +//! the UI must carry the C lessons (wide pane, in-place list +//! updates, search disabled on the trees, session-first toggles). +//! * (c) Step Out in `main()`: `step_out()` degrades to Continue +//! instead of failing with `"finish" not meaningful in the +//! outermost frame.`. +//! * (d) Stop times out on a GUI app in `gtk_main`: `spawn_gdb` +//! enables `-gdb-set mi-async on`, and `interrupt()` falls back +//! through MI interrupt, SIGINT and SIGSTOP to the inferior pid. +//! `kill_target()` additionally tells gdb to drop a stopped +//! inferior it never reported dead (console `kill`), or +//! `-file-exec-and-symbols` fails with "Couldn't get registers". +//! * (e) Run ignores the Target field: `restart_or_start()` re-runs +//! the loaded target when executable/args match, otherwise kills +//! the stopped inferior and starts the new target. The future +//! debugger UI's Run button should call this, not `run()`. +//! * (f) break-on-main's temp breakpoint persists as a duplicate: +//! the breakpoint is marked `Breakpoint::temporary` — skipped when +//! breakpoints are re-applied, never written by +//! `save_breakpoints()`, and never added twice (a `main` +//! breakpoint already present wins). pub mod mi; pub mod session; diff --git a/crates/lightgui-debug/src/session.rs b/crates/lightgui-debug/src/session.rs index 952b29b..b8efdea 100644 --- a/crates/lightgui-debug/src/session.rs +++ b/crates/lightgui-debug/src/session.rs @@ -495,6 +495,15 @@ impl GdbSession { g.state = DbgState::Error; return Err("gdb exited immediately".to_string()); } + // Async mode: without it gdb runs synchronously and never reads + // a new MI command while the inferior runs, so -exec-interrupt + // sits unread in gdb's stdin until the target stops or exits + // on its own — Stop then times out on anything that keeps + // running (a GUI app in gtk_main, a busy loop). With mi-async + // on, gdb answers -exec-interrupt with ^done + *stopped at + // once. Best effort: old gdb without mi-async keeps working + // through interrupt()'s direct-signal fallbacks. + let _ = self.command("-gdb-set mi-async on", 2000); if self.settings().pretty_print { let _ = self.command("-enable-pretty-printing", 2000); } @@ -579,7 +588,9 @@ impl GdbSession { } // Re-apply saved breakpoints (restart keeps them), with their // full handler options. Best effort: a stale location must not - // abort the run. + // abort the run. Temporary breakpoints (break-on-main) are + // skipped: they are re-created below when the setting is on, + // and must not accumulate. let old: Vec = { let mut g = self.shared.inner.lock().unwrap(); let old = g.bps.clone(); @@ -587,10 +598,37 @@ impl GdbSession { old }; for b in old { + if b.temporary { + continue; + } let _ = self.add_breakpoint_opts(&b.location, &b); } if self.settings().break_on_main || self.settings().stop_on_entry { - let _ = self.add_breakpoint("main"); + // The break-on-main breakpoint is temporary: it lives only + // for this run and is never persisted (see + // save_breakpoints), so a fresh session cannot show a + // duplicate `main` row for it. Do not add a second one + // when a `main` breakpoint is already there (e.g. loaded + // from an older bps file, or added by hand). + let have_main = self + .shared + .inner + .lock() + .unwrap() + .bps + .iter() + .any(|b| b.location == "main" || b.function == "main"); + if !have_main { + if let Ok(bp) = self.add_breakpoint("main") { + let mut g = self.shared.inner.lock().unwrap(); + for b in g.bps.iter_mut() { + if b.id == bp.id { + b.temporary = true; + } + } + } + } + // best effort; main may not exist } self.run() } @@ -633,7 +671,18 @@ impl GdbSession { } pub fn step_out(&mut self) -> Result<(), String> { - self.issue_exec("-exec-finish") + // In the outermost frame (main) gdb rejects -exec-finish with + // `"finish" not meaningful in the outermost frame.` — the C + // bug (c) modal. There is no caller to return to, so run on + // like Continue (which still stops at breakpoints) instead of + // failing; other errors propagate unchanged. + match self.issue_exec("-exec-finish") { + Ok(()) => Ok(()), + Err(e) if e.contains("not meaningful in the outermost frame") => { + self.issue_exec("-exec-continue") + } + Err(e) => Err(e), + } } pub fn kill_target(&mut self) -> Result<(), String> { @@ -651,6 +700,18 @@ impl GdbSession { if self.state() == DbgState::Running { self.pump(500); } + // A stopped inferior killed from outside leaves gdb + // holding a dead thread: it never reports the exit, and + // -file-exec-and-symbols then fails with "Couldn't get + // registers: No such process." Tell gdb to drop the + // inferior via the console `kill` command so a later + // load can proceed (best effort; the inferior is dead + // either way). Without this, restart_or_start() cannot + // switch targets after a same-target restart. + if self.state() == DbgState::Stopped { + let _ = self.command("-interpreter-exec console \"kill\"", 2000); + self.pump(500); + } return Ok(()); } // No inferior pid known: fall back to interrupting, then the @@ -663,8 +724,52 @@ impl GdbSession { } pub fn interrupt(&mut self) -> Result<(), String> { - self.command("-exec-interrupt", -1)?; - Ok(()) + // Stop a running target (the Stop action). A bare + // -exec-interrupt times out on anything that keeps running — + // gdb in synchronous mode never reads the command while the + // inferior runs — so this falls back the way the C version + // does: MI interrupt, then SIGINT straight to the inferior + // pid, then SIGSTOP, which cannot be blocked or ignored. + // (mi-async, enabled in spawn_gdb, makes stage 1 answer at + // once on modern gdb; the fallbacks cover old gdb and + // stubborn targets.) C bug (d): Stop must never time out on + // a GUI app sitting in gtk_main. + if self.state() == DbgState::Stopped { + return Ok(()); + } + if self.state() != DbgState::Running { + return Err("target is not running".to_string()); + } + // 1. The MI interrupt. Works when gdb runs in async mode. + if self.command("-exec-interrupt", 2000).is_ok() + && self.wait_for_stop(2000) + { + return Ok(()); + } + self.pump(100); + if self.state() == DbgState::Stopped { + return Ok(()); + } + let inferior_pid = self.shared.inner.lock().unwrap().inferior_pid; + // 2. SIGINT straight to the inferior pid. gdb is blocked in + // waitpid while the target runs, so the signal wakes it up + // and gdb reports the stop even in synchronous mode. + if inferior_pid > 0 { + unsafe { libc::kill(inferior_pid, libc::SIGINT) }; + if self.wait_for_stop(2000) { + return Ok(()); + } + } + // 3. SIGSTOP cannot be blocked or ignored: gdb reports the stop. + if inferior_pid > 0 { + unsafe { libc::kill(inferior_pid, libc::SIGSTOP) }; + if self.wait_for_stop(2000) { + return Ok(()); + } + } + Err("could not interrupt the target (still running); use Restart \ + to kill it" + .to_string()) } pub fn restart(&mut self) -> Result<(), String> { @@ -676,6 +781,38 @@ impl GdbSession { self.run() } + /// Run from Stopped/Exited, honouring the Target field: when the + /// executable/args match the loaded target this is a plain + /// restart, otherwise the new target is loaded and run (C bug + /// (e): Run silently re-ran the old program after the Target + /// entry changed, with no UI path to switch targets without + /// restarting LightGUI). The future debugger UI calls this for + /// its Run button instead of run(). + pub fn restart_or_start( + &mut self, + executable: &str, + args: &str, + ) -> Result<(), String> { + let (cur_exe, cur_args) = { + let g = self.shared.inner.lock().unwrap(); + (g.executable.clone(), g.args.clone()) + }; + if (self.state() == DbgState::Stopped || self.state() == DbgState::Exited) + && executable == cur_exe + && args == cur_args + { + return self.restart(); + } + // Different target (or a fresh session): kill a stopped + // inferior first so -file-exec-and-symbols does not have to + // displace a live one, then load and run the new executable. + if self.state() == DbgState::Stopped || self.state() == DbgState::Running { + self.kill_target()?; + self.pump(300); + } + self.start(executable, args) + } + pub fn poll_events(&mut self) { if self.shared.inner.lock().unwrap().child.is_some() { self.pump(20); @@ -906,6 +1043,10 @@ impl GdbSession { let mut replaced = false; for old in g.bps.iter_mut() { if old.id == b.id { + // A re-insert keeps the entry's temporary flag: a + // break-on-main breakpoint stays temporary even + // when re-applied. + b.temporary = old.temporary; *old = b.clone(); replaced = true; } @@ -986,6 +1127,7 @@ impl GdbSession { let mut want = opts.clone(); want.location = cur.location.clone(); want.id = cur.id; + want.temporary = cur.temporary; want.file = cur.file.clone(); want.line = cur.line; want.function = cur.function.clone(); @@ -1007,6 +1149,7 @@ impl GdbSession { let loc = cur.location.clone(); let mut want = opts.clone(); want.location = loc.clone(); + want.temporary = cur.temporary; self.remove_breakpoint(id)?; self.add_breakpoint_opts(&loc, &want) } @@ -1096,8 +1239,9 @@ impl GdbSession { } } // Merge: gdb is authoritative for kind/condition/ignore/hits, - // but our own records keep the log template and group (gdb - // cannot report them). Staged entries (id 0) are kept. + // but our own records keep the log template, group and + // temporary flag (gdb cannot report them). Staged entries (id + // 0) are kept. let mut merged: Vec = Vec::new(); { let g = self.shared.inner.lock().unwrap(); @@ -1108,6 +1252,7 @@ impl GdbSession { } f.log_message = old.log_message.clone(); f.group = old.group.clone(); + f.temporary = old.temporary; if f.condition.is_empty() { f.condition = old.condition.clone(); } @@ -1139,6 +1284,12 @@ impl GdbSession { let mut body = String::from("# location|enabled|kind|condition|ignore|log_message|group\n"); let g = self.shared.inner.lock().unwrap(); for b in g.bps.iter() { + if b.temporary { + continue; // break-on-main temp bp: live only, never + // persisted (a saved copy would come back as a + // duplicate `main` row next session, alongside the + // fresh temp one) + } body.push_str(&format!( "{}|{}|{}|{}|{}|{}|{}\n", bps_escape(&b.location), diff --git a/crates/lightgui-debug/src/types.rs b/crates/lightgui-debug/src/types.rs index 14de285..6203b86 100644 --- a/crates/lightgui-debug/src/types.rs +++ b/crates/lightgui-debug/src/types.rs @@ -206,6 +206,11 @@ pub struct Breakpoint { pub log_message: String, /// Optional group label (organisation only). pub group: String, + /// Break-on-main / stop-on-entry breakpoint: lives only for this + /// run, is never persisted, and is skipped when breakpoints are + /// re-applied on the next start (C bug 6: a persisted temp `main` + /// breakpoint comes back as a duplicate row next session). + pub temporary: bool, } impl Default for Breakpoint { @@ -223,6 +228,7 @@ impl Default for Breakpoint { ignore_count: 0, log_message: String::new(), group: String::new(), + temporary: false, } } } diff --git a/crates/lightgui-debug/tests/common/mod.rs b/crates/lightgui-debug/tests/common/mod.rs index d95ebf1..23d9120 100644 --- a/crates/lightgui-debug/tests/common/mod.rs +++ b/crates/lightgui-debug/tests/common/mod.rs @@ -18,6 +18,8 @@ pub struct Targets { pub spin: PathBuf, pub gtkapp: PathBuf, pub gtkapp_src: PathBuf, + pub gtkspin: PathBuf, + pub gtkspin_src: PathBuf, } pub fn targets() -> &'static Targets { @@ -45,9 +47,11 @@ fn build_targets() -> Targets { let console_src = src_dir.join("console.cpp"); let spin_src = src_dir.join("spin.cpp"); let gtk_src = src_dir.join("gtkapp.cpp"); + let gtkspin_src = src_dir.join("gtkspin.cpp"); let console = dir.join("console"); let spin = dir.join("spin"); let gtkapp = dir.join("gtkapp"); + let gtkspin = dir.join("gtkspin"); run_or_panic( { @@ -89,6 +93,17 @@ fn build_targets() -> Targets { }, "build gtkapp target", ); + run_or_panic( + { + let mut c = Command::new("g++"); + c.args(["-g", "-O0", "-o"]); + c.arg(>kspin); + c.arg(>kspin_src); + c.args(&flags); + c + }, + "build gtkspin target", + ); Targets { dir, @@ -97,6 +112,8 @@ fn build_targets() -> Targets { spin, gtkapp, gtkapp_src: gtk_src, + gtkspin, + gtkspin_src, } } diff --git a/crates/lightgui-debug/tests/console.rs b/crates/lightgui-debug/tests/console.rs index 452a725..e92b145 100644 --- a/crates/lightgui-debug/tests/console.rs +++ b/crates/lightgui-debug/tests/console.rs @@ -830,3 +830,129 @@ fn bp_handlers_persist_roundtrip() { assert!(!r.unwrap_err().is_empty()); assert!(s4.breakpoints().is_empty()); } + +// Bug (c): Step Out while stopped in main() must not fail with +// "finish not meaningful in the outermost frame" — it degrades to +// Continue, like the Python port (no modal, no error). +#[test] +fn step_out_in_main_degrades_to_continue() { + let s = DebuggerSettings { + break_on_main: true, + ..Default::default() + }; + let mut sess = GdbSession::new(s); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.last_stop().frame.function, "main"); + let r = sess.step_out(); + assert!(r.is_ok(), "step_out in main failed: {:?}", r.err()); + assert!(sess.wait_for_stop(10_000)); + assert_eq!(sess.state(), DbgState::Exited); + assert_eq!(sess.exit_code(), 0); +} + +// Bug (f): break-on-main must not duplicate on a second start() — +// the "main" breakpoint is re-applied from the kept list AND added +// again by start(), which used to leave two identical "main" rows. +#[test] +fn break_on_main_no_duplicate_on_second_start() { + let s = DebuggerSettings { + break_on_main: true, + ..Default::default() + }; + let mut sess = GdbSession::new(s); + sess.start(console().to_str().unwrap(), "").expect("start 1"); + assert!(sess.wait_for_stop(-1)); + let count_main = |sess: &GdbSession| { + sess.breakpoints() + .iter() + .filter(|b| b.location == "main") + .count() + }; + assert_eq!( + count_main(&sess), + 1, + "after start 1: {:?}", + sess.breakpoints() + ); + sess.start(console().to_str().unwrap(), "").expect("start 2"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.last_stop().frame.function, "main"); + assert_eq!( + count_main(&sess), + 1, + "after start 2: {:?}", + sess.breakpoints() + ); +} + +// Bug (f), persisted variant: a saved "main" breakpoint loaded from +// disk plus break_on_main must still leave exactly one "main" row. +#[test] +fn break_on_main_no_duplicate_after_load() { + let s = DebuggerSettings { + break_on_main: true, + ..Default::default() + }; + let mut sess = GdbSession::new(s); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(-1)); + let p = tmp_path("bps_main"); + assert!(sess.save_breakpoints(p.to_str().unwrap())); + // Bug (f), root cause: the break-on-main temp breakpoint must + // never be written to the bps file — a saved copy comes back as + // a duplicate `main` row next session. + let saved = std::fs::read_to_string(p.to_str().unwrap()).unwrap(); + assert!( + !saved.lines().any(|l| l.starts_with("main|")), + "temp main bp must not be persisted: {}", + saved + ); + sess.shutdown(); + let mut sess2 = GdbSession::new(DebuggerSettings { + break_on_main: true, + ..Default::default() + }); + assert!(sess2.load_breakpoints(p.to_str().unwrap())); + sess2 + .start(console().to_str().unwrap(), "") + .expect("start 2"); + assert!(sess2.wait_for_stop(-1)); + let n = sess2 + .breakpoints() + .iter() + .filter(|b| b.location == "main") + .count(); + assert_eq!( + n, + 1, + "loaded + break_on_main: {:?}", + sess2.breakpoints() + ); +} + +// Bug (e): Run from Stopped/Exited must honour the Target field — +// restart_or_start with a different executable loads and runs it +// instead of silently re-running the loaded program. +#[test] +fn restart_or_start_switches_target() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.start(console().to_str().unwrap(), "").expect("start console"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.last_stop().frame.line, l_loop); + // Same target + args: plain restart, hits the breakpoint again. + sess.restart_or_start(console().to_str().unwrap(), "") + .expect("restart same"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.last_stop().frame.line, l_loop); + // Different target: spin runs (never stops on its own). + sess.restart_or_start(spin().to_str().unwrap(), "") + .expect("switch to spin"); + std::thread::sleep(std::time::Duration::from_millis(500)); + assert!(sess.target_running()); + assert_eq!(sess.executable(), spin().to_str().unwrap()); + sess.kill_target().expect("kill spin"); + assert!(sess.wait_for_stop(5000)); +} diff --git a/crates/lightgui-debug/tests/gtk.rs b/crates/lightgui-debug/tests/gtk.rs index 9c9e910..b292edf 100644 --- a/crates/lightgui-debug/tests/gtk.rs +++ b/crates/lightgui-debug/tests/gtk.rs @@ -18,6 +18,9 @@ fn app() -> PathBuf { fn app_src() -> PathBuf { targets().gtkapp_src.clone() } +fn gtkspin() -> PathBuf { + targets().gtkspin.clone() +} fn marks() -> (i32, i32) { let src = app_src(); (mark_line(&src, "MARK:CB"), mark_line(&src, "MARK:CB_NEXT")) @@ -150,3 +153,26 @@ fn gtk_conditional_in_callback() { assert_eq!(sess.exit_code(), 0); assert!(sess.target_output().contains("CLICKS=1")); } + +// Bug (d): Stop (interrupt) on a GUI app sitting in gtk_main() must +// not time out waiting for a gdb reply — it interrupts the inferior, +// falling back to a direct kill if gdb does not answer. +#[test] +fn gtk_interrupt_running_app() { + let mut sess = GdbSession::default(); + sess.start(gtkspin().to_str().unwrap(), "").expect("start"); + std::thread::sleep(std::time::Duration::from_millis(500)); + assert!(sess.target_running(), "gtkspin should be in gtk_main"); + let t0 = std::time::Instant::now(); + let r = sess.interrupt(); + let dt = t0.elapsed(); + assert!( + r.is_ok(), + "interrupt timed out after {:?}: {:?}", + dt, + r.err() + ); + assert!(sess.wait_for_stop(5000), "no stop after interrupt"); + assert_eq!(sess.state(), DbgState::Stopped); + sess.kill_target().expect("kill_target"); +} diff --git a/crates/lightgui-debug/tests/targets/gtkspin.cpp b/crates/lightgui-debug/tests/targets/gtkspin.cpp new file mode 100644 index 0000000..2289702 --- /dev/null +++ b/crates/lightgui-debug/tests/targets/gtkspin.cpp @@ -0,0 +1,38 @@ +// Debugger test target: GTK app that sits in gtk_main() forever +// (no quit timer, no auto-click) — the Stop/interrupt probe target. +// The C guide's bug 4 is "Stop times out on a GUI app stuck in +// gtk_main"; this target reproduces that state on demand. +// Compile with: g++ -g -O0 -o gtkspin gtkspin.cpp $(pkg-config --cflags --libs gtk+-3.0) +#include +#include + +static int counter = 0; +static GtkWidget* label = nullptr; + +static void on_clicked(GtkButton*, gpointer) { + counter++; + char buf[64]; + std::snprintf(buf, sizeof buf, "Clicks: %d", counter); + gtk_label_set_text(GTK_LABEL(label), buf); +} + +int main(int argc, char** argv) { + gtk_init(&argc, &argv); + GtkWidget* win = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(win), "Debugger GTK Spin Test"); + gtk_window_set_default_size(GTK_WINDOW(win), 300, 120); + g_signal_connect(win, "destroy", G_CALLBACK(gtk_main_quit), nullptr); + GtkWidget* box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); + gtk_container_add(GTK_CONTAINER(win), box); + label = gtk_label_new("Clicks: 0"); + gtk_box_pack_start(GTK_BOX(box), label, TRUE, TRUE, 0); + GtkWidget* button = gtk_button_new_with_label("Click me"); + g_signal_connect(button, "clicked", G_CALLBACK(on_clicked), nullptr); + gtk_box_pack_start(GTK_BOX(box), button, TRUE, TRUE, 0); + gtk_widget_show_all(win); + // No quit timer: this app sits in gtk_main() until killed. + gtk_main(); + std::printf("CLICKS=%d\n", counter); + std::fflush(stdout); + return 0; +}