diff --git a/src/debugger.cpp b/src/debugger.cpp index 1a51c4d..934848c 100644 --- a/src/debugger.cpp +++ b/src/debugger.cpp @@ -439,6 +439,19 @@ bool GdbSession::spawn_gdb(std::string& err) { state_ = DbgState::Error; return false; } + // 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. + { + MiValue r; + std::string e; + command("-gdb-set mi-async on", r, e, 2000); + // Best effort: old gdb without mi-async keeps working through + // interrupt()'s direct-signal fallbacks. + } // Pretty printing is a session-wide gdb setting: apply now so every // later variable value comes back formatted. if (settings_.pretty_print) { @@ -568,6 +581,14 @@ void GdbSession::handle_line(const std::string& line) { inferior_pid_ = std::atoi(f.get_str("pid", "0").c_str()); } else if (line.rfind("=thread-group-exited,", 0) == 0) { inferior_pid_ = -1; + // gdb reports a killed inferior's death ONLY as + // =thread-group-exited (no *stopped exit record), and it + // defers even that until the next command is processed — + // so a SIGKILLed target can otherwise sit in Stopped + // forever. The inferior is gone: the session has exited. + if (state_ == DbgState::Running || + state_ == DbgState::Stopped) + state_ = DbgState::Exited; } return; } @@ -716,18 +737,45 @@ bool GdbSession::start(const std::string& executable, const std::string& args, } // Re-apply saved breakpoints (restart keeps them), with their full // handler options (conditional / logpoint / ignore count / group). + // Temporary breakpoints (break-on-main) are skipped: they are + // re-created below when the setting is on, and must not accumulate. std::vector old = bps_; bps_.clear(); for (auto& b : old) { + if (b.temporary) continue; Breakpoint nb; std::string e; - add_breakpoint_opts(b.location, b, nb, e); // best effort: a stale - // location must not abort the run + if (!add_breakpoint_opts(b.location, b, nb, e)) { + // Best effort: a location this target does not have (or an + // option gdb rejects here) must not abort the run — keep + // the breakpoint staged, so it is still listed and comes + // back when the target switches to one that has it. + Breakpoint staged = b; + staged.id = 0; + staged.hits = 0; + bps_.push_back(staged); + } + // (a stale location must not abort the run) } if (settings_.break_on_main || settings_.stop_on_entry) { - Breakpoint bp; - std::string e; - add_breakpoint("main", bp, e); // best effort; main may not exist + // 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). + bool have_main = false; + for (const auto& b : bps_) + if (b.location == "main" || b.function == "main") + have_main = true; + if (!have_main) { + Breakpoint bp; + std::string e; + if (add_breakpoint("main", bp, e)) { + for (auto& b : bps_) + if (b.id == bp.id) b.temporary = true; + } + // best effort; main may not exist + } } return run(err); } @@ -765,13 +813,60 @@ bool GdbSession::step_into(std::string& err) { return issue_exec("-exec-step", err); } +// True when the current stop is inside a function with a caller to +// return to. The live frame list decides when it is available; the +// frame level from the *stopped record is the fallback. +bool GdbSession::can_step_out() { + if (state_ != DbgState::Stopped) return false; + std::string err; + if (list_frames(frames_, err) && !frames_.empty()) + return frames_.size() > 1; + return last_stop_.frame.level > 0; +} + bool GdbSession::step_out(std::string& err) { + // In the outermost frame (main) gdb rejects -exec-finish with + // `"finish" not meaningful in the outermost frame.` Refuse here, + // with a plain message the UI shows in the status line instead of + // a modal error dialog. + if (!can_step_out()) { + err = "Already in the outermost frame — there is no caller to " + "step out to. Use Continue to run on."; + return false; + } return issue_exec("-exec-finish", err); } bool GdbSession::kill_target(std::string& err) { - // gdb 13 MI has no -exec-kill: SIGKILL the inferior directly (its pid - // comes from =thread-group-started), then let gdb report the exit. + if (state_ == DbgState::Exited || state_ == DbgState::Idle) + return true; // nothing running to kill + // 1. gdb's own `kill`: it reaps the inferior synchronously and + // reports =thread-group-exited at once. A raw SIGKILL does not: + // gdb defers the exit report until the next command that touches + // the inferior, leaving a dead-but-unreaped process behind, and + // the next -file-exec-and-symbols then fails with "Couldn't get + // registers: No such process." (Verified live: console kill on a + // stopped or a running target reports the exit immediately, and + // -file-exec-and-symbols + -exec-run then succeed.) + { + MiValue r; + std::string e; + if (command("-interpreter-exec console \"kill\"", r, e, 5000)) { + // Wait briefly for the exit records (they precede ^done, + // so this is usually instant). + auto deadline = std::chrono::steady_clock::now() + + std::chrono::seconds(2); + while (state_ != DbgState::Exited && + std::chrono::steady_clock::now() < deadline) + pump(100); + if (state_ == DbgState::Exited) return true; + } else if (e.find("not being run") != std::string::npos) { + return true; // inferior already gone + } + // Otherwise fall through to the signal path. + } + // 2. SIGKILL the inferior directly (fallback when gdb could not + // process the console command, e.g. a pre-async gdb). if (inferior_pid_ > 0) { if (::kill(inferior_pid_, SIGKILL) != 0 && errno != ESRCH) { err = "failed to kill target process"; @@ -784,20 +879,45 @@ bool GdbSession::kill_target(std::string& err) { } return true; } - // No inferior pid known (never started / already exited): fall back to - // interrupting, then the console "kill" command. - MiValue r; - if (!command("-exec-interrupt", r, err)) return false; - pump(300); - if (!command("-interpreter-exec console \"kill\"", r, err)) return false; - pump(500); + // No inferior pid known (never started / already exited): nothing + // left to kill. return true; } bool GdbSession::interrupt(std::string& err) { - MiValue r; - if (!command("-exec-interrupt", r, err)) return false; - return true; + if (state_ == DbgState::Stopped) return true; + if (state_ != DbgState::Running) { + err = "target is not running"; + return false; + } + // 1. The MI interrupt. Works when gdb runs in async mode (enabled + // in spawn_gdb); without it gdb never reads the command while the + // inferior runs and this times out — hence the fallbacks below. + { + MiValue r; + std::string e; + if (command("-exec-interrupt", r, e, 2000) && + wait_for_stop(2000)) + return true; + pump(100); + if (state_ == DbgState::Stopped) return true; + } + // 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) { + ::kill(inferior_pid_, SIGINT); + if (wait_for_stop(2000)) return true; + } + // 3. SIGSTOP cannot be blocked or ignored: gdb reports the stop. + if (inferior_pid_ > 0) { + ::kill(inferior_pid_, SIGSTOP); + if (wait_for_stop(2000)) return true; + } + err = "could not interrupt the target (still running); use Restart " + "to kill it"; + last_error_ = err; + return false; } bool GdbSession::restart(std::string& err) { @@ -810,6 +930,26 @@ bool GdbSession::restart(std::string& err) { return run(err); } +// Re-run the loaded target, or load and run a different one when the +// executable/args differ: Run from Stopped/Exited must honour the +// Target field instead of silently re-running the old program. +bool GdbSession::restart_or_start(const std::string& executable, + const std::string& args, std::string& err) { + if ((state_ == DbgState::Stopped || state_ == DbgState::Exited) && + executable == executable_ && args == args_) { + return restart(err); + } + // Different target (or a fresh session): kill the inferior first + // (through gdb itself, so it is reaped synchronously — a raw + // SIGKILL leaves a dead-but-unreaped inferior behind and the next + // -file-exec-and-symbols fails), then load and run the new one. + if (state_ == DbgState::Stopped || state_ == DbgState::Running) { + std::string e; + if (!kill_target(e)) return false; + } + return start(executable, args, err); +} + void GdbSession::poll_events() { if (gdb_pid_ > 0) pump(20); } @@ -1001,9 +1141,14 @@ bool GdbSession::add_breakpoint_opts(const std::string& location, b.ignore_count = want.ignore_count; b.log_message = want.log_message; b.group = want.group; - // Replace any existing entry with the same id. + // Replace any existing entry with the same id (a re-insert keeps + // the entry's temporary flag: a break-on-main breakpoint stays + // temporary even when re-applied). for (auto& old : bps_) - if (old.id == b.id) old = b; + if (old.id == b.id) { + b.temporary = old.temporary; + old = b; + } bool found = false; for (auto& old : bps_) if (old.id == b.id) found = true; @@ -1162,14 +1307,16 @@ bool GdbSession::refresh_breakpoints(std::string& err) { } } // 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, not in gdb yet) are kept. + // our own records keep the log template, group and temporary flag + // (gdb cannot report them). Staged entries (id 0, not in gdb yet) + // are kept. std::vector merged; for (auto& f : fresh) { for (const auto& old : bps_) { if (old.id != f.id) continue; f.log_message = old.log_message; f.group = old.group; + f.temporary = old.temporary; if (f.condition.empty()) f.condition = old.condition; break; } @@ -1242,11 +1389,15 @@ bool GdbSession::save_breakpoints(const std::string& path) const { std::ofstream f(p); if (!f) return false; f << "# location|enabled|kind|condition|ignore|log_message|group\n"; - for (const auto& b : bps_) + for (const auto& b : bps_) { + 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) f << bps_escape(b.location) << "|" << (b.enabled ? "1" : "0") << "|" << bp_kind_name(b.kind) << "|" << bps_escape(b.condition) << "|" << b.ignore_count << "|" << bps_escape(b.log_message) << "|" << bps_escape(b.group) << "\n"; + } return (bool)f; } @@ -1290,6 +1441,15 @@ bool GdbSession::load_breakpoints(const std::string& path) { // breakpoint (also covers hand-edited files). if (b.kind == BpKind::Plain && !b.condition.empty()) b.kind = BpKind::Conditional; + // Legacy files may already contain a persisted break-on-main + // entry (possibly twice: the temp bp plus a user one). Keep the + // first `main` entry, drop later duplicates. + if (b.location == "main") { + bool dup = false; + for (const auto& old : bps_) + if (old.location == "main") dup = true; + if (dup) continue; + } bps_.push_back(b); } return true; diff --git a/src/debugger.h b/src/debugger.h index 0e0c527..ddfd0ff 100644 --- a/src/debugger.h +++ b/src/debugger.h @@ -71,6 +71,11 @@ struct Breakpoint { int ignore_count = 0; // skip the first N hits (-break-after) std::string log_message; // logpoint template, e.g. "i={i} sum={sum}" std::string group; // optional group label (organisation only) + // Temporary breakpoints (the break-on-main / stop-on-entry breakpoint + // inserted by start()) live only for the run: they are never written + // to debugger_bps.conf, so a fresh session cannot show a duplicate + // `main` row for them. + bool temporary = false; }; struct Variable { @@ -152,6 +157,7 @@ public: bool target_running() const { return state_ == DbgState::Running; } DbgState state() const { return state_; } const std::string& executable() const { return executable_; } + const std::string& args() const { return args_; } int exit_code() const { return last_stop_.exit_code; } // Execution control. Each returns false + err if gdb rejects it or @@ -160,10 +166,26 @@ public: bool cont(std::string& err); // continue bool step_over(std::string& err); // -exec-next bool step_into(std::string& err); // -exec-step - bool step_out(std::string& err); // -exec-finish - bool kill_target(std::string& err); // -exec-kill (target keeps gdb) + // -exec-finish. Refused (false + err) in the outermost frame, where + // gdb would answer `"finish" not meaningful in the outermost + // frame.` — see can_step_out(). + bool step_out(std::string& err); + // True when the current stop is inside a function that has a caller + // to return to (more than one stack frame). False in main(). + bool can_step_out(); + bool kill_target(std::string& err); // gdb `kill` (target keeps gdb) bool restart(std::string& err); // kill (if running) + run again - bool interrupt(std::string& err); // SIGINT to the inferior + // Re-run the loaded target, or load and run a different one when + // the executable/args differ from the loaded target (Run from + // Stopped/Exited honours the Target field instead of silently + // re-running the old program). + bool restart_or_start(const std::string& executable, + const std::string& args, std::string& err); + // Interrupt a running target. Tries -exec-interrupt (needs gdb in + // async mode, enabled at spawn), then SIGINT and finally SIGSTOP + // delivered straight to the inferior pid, so Stop works even on a + // GUI app sitting in gtk_main. + bool interrupt(std::string& err); // Wait until the target stops (breakpoint/step/exit) or timeout_ms // elapses. Returns true if a stop event arrived. diff --git a/tests/debugger/dbg_harness.cpp b/tests/debugger/dbg_harness.cpp index 1c0c959..a6e31df 100644 --- a/tests/debugger/dbg_harness.cpp +++ b/tests/debugger/dbg_harness.cpp @@ -6,6 +6,7 @@ // so editing the targets does not silently shift the expectations. #include "../../src/debugger.h" +#include #include #include #include @@ -717,6 +718,145 @@ static void console_tests() { } report("bp_handlers_persist_roundtrip", ok, ""); } + // 37. step out in main() is refused cleanly: no gdb `"finish" not + // meaningful` error, the session stays Stopped, and can_step_out() + // reports false in the outermost frame. + { + DebuggerSettings s; + s.break_on_main = true; + GdbSession sess(s); + std::string err; + bool ok = sess.start(console, "", err) && sess.wait_for_stop(); + ok = ok && sess.state() == DbgState::Stopped && + sess.last_stop().frame.function == "main"; + ok = ok && !sess.can_step_out(); + std::string e2; + bool refused = !sess.step_out(e2); + ok = ok && refused && + e2.find("outermost") != std::string::npos && + sess.state() == DbgState::Stopped; + ok = ok && sess.cont(err) && sess.wait_for_stop(10000); + ok = ok && sess.state() == DbgState::Exited; + report("step_out_in_main_refused", ok, e2); + } + // 38. can_step_out() is true inside a called function, and the + // step out itself still works there. + { + GdbSession sess; + std::string err; + sess.stage_breakpoint(loc(src, L_CALL)); + sess.start(console, "", err); + sess.wait_for_stop(); + bool ok = sess.step_into(err) && sess.wait_for_stop(); + ok = ok && sess.last_stop().frame.function.find("compute") != + std::string::npos; + ok = ok && sess.can_step_out(); + ok = ok && sess.step_out(err) && sess.wait_for_stop(); + ok = ok && sess.last_stop().frame.function == "main"; + report("can_step_out_inside_call", ok, err); + } + // 39. the break-on-main breakpoint is temporary: it is never + // written to the bps file, and a second session shows exactly one + // `main` breakpoint (no duplicate row). Legacy files that already + // hold two `main` lines load back deduplicated. + { + DebuggerSettings s; + s.break_on_main = true; + GdbSession sess(s); + std::string err; + bool ok = sess.start(console, "", err) && sess.wait_for_stop(); + ok = ok && sess.save_breakpoints("/tmp/dbgtest_bps_main"); + std::string content; + { + std::ifstream f("/tmp/dbgtest_bps_main"); + content.assign(std::istreambuf_iterator(f), + std::istreambuf_iterator()); + } + ok = ok && content.find("main|") == std::string::npos; + GdbSession sess2(s); + ok = ok && sess2.load_breakpoints("/tmp/dbgtest_bps_main"); + ok = ok && sess2.breakpoints().empty(); + ok = ok && sess2.start(console, "", err) && sess2.wait_for_stop(); + int nmain = 0; + for (const auto& b : sess2.breakpoints()) + if (b.location == "main" || b.function == "main") ++nmain; + ok = ok && nmain == 1 && sess2.breakpoints().size() == 1; + ok = ok && sess2.cont(err) && sess2.wait_for_stop(10000); + { + std::ofstream f("/tmp/dbgtest_bps_dup"); + f << "main|1|plain||0||\nmain|1|plain||0||\n"; + } + GdbSession sess3; + ok = ok && sess3.load_breakpoints("/tmp/dbgtest_bps_dup"); + ok = ok && sess3.breakpoints().size() == 1; + report("break_on_main_not_persisted", ok, + "file='" + content + "' nmain=" + std::to_string(nmain)); + } + // 40. restart_or_start honours a changed target: from Stopped it + // loads and runs the new executable (and new args), and re-runs the + // loaded one when nothing changed. + { + GdbSession sess; + std::string err; + sess.stage_breakpoint(loc(src, L_LOOP)); + bool ok = sess.start(console, "", err) && sess.wait_for_stop(); + ok = ok && sess.state() == DbgState::Stopped && + sess.last_stop().frame.line == L_LOOP; + // Switch to a different executable. + ok = ok && sess.restart_or_start(spin, "", err); + ::usleep(300000); + ok = ok && sess.target_running() && + sess.executable() == spin; + ok = ok && sess.kill_target(err) && sess.wait_for_stop(5000); + // Same executable, different args: reloaded with the new args + // (stops at the loop bp first, then runs to completion). + ok = ok && sess.restart_or_start(console, "hello", err); + ok = ok && sess.wait_for_stop(); + ok = ok && sess.state() == DbgState::Stopped && + sess.last_stop().frame.line == L_LOOP; + for (int i = 0; i < 3 && ok; ++i) + ok = sess.cont(err) && sess.wait_for_stop(); + ok = ok && sess.state() == DbgState::Exited && + sess.target_output().find("ARG=hello") != std::string::npos; + // Same executable and args: plain restart, stops at the loop + // breakpoint again. + ok = ok && sess.restart_or_start(console, "hello", err); + ok = ok && sess.wait_for_stop(); + ok = ok && sess.state() == DbgState::Stopped && + sess.last_stop().frame.line == L_LOOP; + ok = ok && sess.kill_target(err) && sess.wait_for_stop(5000); + report("restart_or_start_switches_target", ok, + err + " | out: " + sess.target_output()); + } + // 41. interrupt stops a running (spinning) target promptly — the + // old code timed out after 5 s because gdb never read + // -exec-interrupt while the target ran (synchronous mode). + { + GdbSession sess; + std::string err; + bool ok = sess.start(spin, "", err); + ::usleep(500000); + ok = ok && sess.target_running(); + auto t0 = std::chrono::steady_clock::now(); + bool intr = sess.interrupt(err); + double dt = std::chrono::duration( + std::chrono::steady_clock::now() - t0) + .count(); + ok = ok && intr && dt < 3.0; + ok = ok && sess.wait_for_stop(3000); + ok = ok && sess.state() == DbgState::Stopped && + sess.last_stop().reason == "signal-received"; + // Continue, then interrupt again: Stop works repeatedly. + ok = ok && sess.cont(err); + ::usleep(300000); + ok = ok && sess.target_running(); + ok = ok && sess.interrupt(err) && sess.wait_for_stop(3000); + ok = ok && sess.state() == DbgState::Stopped; + ok = ok && sess.kill_target(err) && sess.wait_for_stop(5000); + ok = ok && !sess.target_running(); + report("interrupt_stops_running_target", ok, + "interrupt took " + std::to_string(dt) + "s err=" + err); + } } // ---- GTK tests (run under xvfb-run) --------------------------------------- @@ -819,6 +959,55 @@ static void gtk_tests() { report("gtk_conditional_in_callback", ok, "reason=" + sess.last_stop().reason); } + // 37. Stop interrupts a GUI app sitting in gtk_main: the old code + // timed out after 5 s (gdb in synchronous mode never read + // -exec-interrupt while the target ran). The stop lands inside + // gtk_main's poll, and Stop works again after Continue. + { + std::string spin_app = g_dir + "/gtkspin"; + GdbSession sess; + std::string err; + bool ok = sess.start(spin_app, "", err); + ::usleep(1000000); + ok = ok && sess.target_running(); + // Interrupt until a stop lands inside gtk_main: the first + // interrupt can catch slow GTK startup (theme/css loading) + // instead, so continue and try again (up to 5 times). + bool in_gtk_main = false; + double dt = 0; + for (int attempt = 0; attempt < 5 && !in_gtk_main; ++attempt) { + auto t0 = std::chrono::steady_clock::now(); + bool intr = sess.interrupt(err); + dt = std::chrono::duration( + std::chrono::steady_clock::now() - t0) + .count(); + ok = ok && intr && dt < 3.0; + ok = ok && sess.wait_for_stop(3000); + ok = ok && sess.state() == DbgState::Stopped && + sess.last_stop().reason == "signal-received"; + if (!ok) break; + sess.refresh_on_stop(); + for (const auto& f : sess.frames()) + if (f.function.find("gtk_main") != std::string::npos) + in_gtk_main = true; + if (!in_gtk_main) { + ok = ok && sess.cont(err); + ::usleep(1000000); + ok = ok && sess.target_running(); + } + } + ok = ok && in_gtk_main; + // Stop works again after Continue. + ok = ok && sess.cont(err); + ::usleep(500000); + ok = ok && sess.target_running(); + ok = ok && sess.interrupt(err) && sess.wait_for_stop(3000); + ok = ok && sess.state() == DbgState::Stopped; + ok = ok && sess.kill_target(err) && sess.wait_for_stop(5000); + ok = ok && !sess.target_running(); + report("interrupt_gtkapp_in_gtk_main", ok, + "interrupt took " + std::to_string(dt) + "s err=" + err); + } } int main(int argc, char** argv) { diff --git a/tests/debugger/gtkspin.cpp b/tests/debugger/gtkspin.cpp new file mode 100644 index 0000000..a2f5aef --- /dev/null +++ b/tests/debugger/gtkspin.cpp @@ -0,0 +1,14 @@ +// Debugger test target: GTK app that sits in gtk_main forever (no timers). +// Used to probe Stop/interrupt behaviour on a GUI app. +#include + +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"); + gtk_window_set_default_size(GTK_WINDOW(win), 300, 120); + g_signal_connect(win, "destroy", G_CALLBACK(gtk_main_quit), nullptr); + gtk_widget_show_all(win); + gtk_main(); + return 0; +} diff --git a/tests/debugger_tests.sh b/tests/debugger_tests.sh index a8ad87c..395016d 100755 --- a/tests/debugger_tests.sh +++ b/tests/debugger_tests.sh @@ -60,11 +60,15 @@ say "== building debugger test targets ==" cp "$D/console.cpp" "$WORK/console.cpp" cp "$D/spin.cpp" "$WORK/spin.cpp" cp "$D/gtkapp.cpp" "$WORK/gtkapp.cpp" +cp "$D/gtkspin.cpp" "$WORK/gtkspin.cpp" # Compile from the work-dir paths so DWARF records the same absolute # source paths the harness uses for file:line breakpoints. g++ -g -O0 -o "$WORK/console" "$WORK/console.cpp" || FAIL=1 g++ -g -O0 -o "$WORK/spin" "$WORK/spin.cpp" || FAIL=1 g++ -g -O0 -o "$WORK/gtkapp" "$WORK/gtkapp.cpp" $(pkg-config --cflags --libs gtk+-3.0) || FAIL=1 +# gtkspin: GTK app that sits in gtk_main forever (no quit timer), for the +# Stop/interrupt tests — gtkapp quits on its own after 4 s. +g++ -g -O0 -o "$WORK/gtkspin" "$WORK/gtkspin.cpp" $(pkg-config --cflags --libs gtk+-3.0) || FAIL=1 g++ -O2 -Wall -Wextra -std=c++17 -o "$WORK/dbg_harness" "$D/dbg_harness.cpp" "$ROOT/src/debugger.cpp" || FAIL=1 # lightgui itself (with the debugger window) must build clean (cd "$ROOT" && make >/tmp/dbg_make.log 2>&1) || { say "FAIL lightgui build"; cat /tmp/dbg_make.log; FAIL=1; }