[Lldb-commits] [lldb] [lldb] Keep a stop private until it has been handled (PR #234789)
Med Ismail Bennani via lldb-commits
lldb-commits at lists.llvm.org
Fri Oct 23 12:52:29 PDT 2026
https://github.com/medismailben updated https://github.com/llvm/llvm-project/pull/234789
>From f4b89c88eaf151f5d4096f0284cfbfd01c551f14 Mon Sep 17 00:00:00 2001
From: Med Ismail Bennani <ismail at bennani.ma>
Date: Fri, 23 Oct 2026 12:52:13 -0700
Subject: [PATCH] [lldb] Keep a stop private until it has been handled
ProcessEventData::DoOnRemoval makes a stop public, by setting the
public state to stopped and releasing the public run lock, before it
handles the stop by running its StopInfo actions and stop hooks. While
those run, any other thread sees a stopped process: it can take the
run lock, run expressions, or resume the process underneath them. In
an IDE, this is what happens when the user keeps clicking Continue
while LLDB is still handling the previous stop.
Hold the stop back until it has been handled. The thread handling it
pushes a new Policy::View::HandlingStop and gets a public state and
run lock of its own, which read stopped, so it can still run
expressions. Every other thread keeps seeing the process running, and
the main run lock stays held. Once the stop is handled, it is made
public, unless handling it restarted the process.
Halt now refuses while another thread handles a stop, since the
process is already stopped and interrupting it would interrupt the
expressions run while handling it. Destroy and Detach treat such a
process as stopped instead of trying to halt it.
Assisted-by: Claude
Signed-off-by: Med Ismail Bennani <ismail at bennani.ma>
---
lldb/include/lldb/Target/Process.h | 94 +++++-
lldb/include/lldb/Utility/Policy.h | 19 +-
.../source/Interpreter/CommandInterpreter.cpp | 5 +-
lldb/source/Target/Process.cpp | 168 ++++++++--
lldb/source/Utility/Policy.cpp | 23 +-
.../api/multithreaded/stop_reporting/Makefile | 8 +
.../TestMultithreadedStopReporting.py | 21 ++
.../stop_reporting/stop_reporting.cpp | 13 +
.../stop_reporting_callbacks.py | 41 +++
.../stop_reporting/test_stop_reporting.cpp | 302 ++++++++++++++++++
lldb/unittests/Utility/PolicyTest.cpp | 29 ++
11 files changed, 683 insertions(+), 40 deletions(-)
create mode 100644 lldb/test/API/api/multithreaded/stop_reporting/Makefile
create mode 100644 lldb/test/API/api/multithreaded/stop_reporting/TestMultithreadedStopReporting.py
create mode 100644 lldb/test/API/api/multithreaded/stop_reporting/stop_reporting.cpp
create mode 100644 lldb/test/API/api/multithreaded/stop_reporting/stop_reporting_callbacks.py
create mode 100644 lldb/test/API/api/multithreaded/stop_reporting/test_stop_reporting.cpp
diff --git a/lldb/include/lldb/Target/Process.h b/lldb/include/lldb/Target/Process.h
index 226c58034dd655..2044a1bb34c9c0 100644
--- a/lldb/include/lldb/Target/Process.h
+++ b/lldb/include/lldb/Target/Process.h
@@ -19,6 +19,7 @@
#include <mutex>
#include <optional>
#include <string>
+#include <thread>
#include <unordered_set>
#include <vector>
@@ -497,6 +498,10 @@ class Process : public std::enable_shared_from_this<Process>,
private:
bool ForwardEventToPendingListeners(Event *event_ptr) override;
+ /// Run the stop's StopInfo actions and stop hooks, and resume the process
+ /// if they ask for it.
+ void PerformStopActions(Process &process, Event *event_ptr);
+
void SetUpdateStateOnRemoval() { m_update_state++; }
void SetRestarted(bool new_value) { m_restarted = new_value; }
@@ -1294,6 +1299,14 @@ class Process : public std::enable_shared_from_this<Process>,
/// \see lldb::StateType
lldb::StateType GetState();
+ /// Return true if another thread is still handling a stop that hasn't been
+ /// made public yet, by running its StopInfo actions and stop hooks.
+ ///
+ /// The process is stopped, but until the stop is handled its public state
+ /// reads running to every thread but that one, so that nothing can resume
+ /// or inspect the process underneath it.
+ bool IsHandlingStopOnOtherThread() const;
+
lldb::ExpressionResults
RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp,
const EvaluateExpressionOptions &requested_options,
@@ -3423,29 +3436,71 @@ void PruneThreadPlans();
return m_current_private_state_thread_sp->SetPrivateRunLockToRunning();
return false;
}
- bool SetPublicRunLockToStopped() {
- assert(m_current_private_state_thread_sp);
- if (m_current_private_state_thread_sp)
- return m_current_private_state_thread_sp->SetPublicRunLockToStopped();
- return false;
- }
- bool SetPublicRunLockToRunning() {
- assert(m_current_private_state_thread_sp);
- if (m_current_private_state_thread_sp)
- return m_current_private_state_thread_sp->SetPublicRunLockToRunning();
- return false;
- }
+ bool SetPublicRunLockToStopped();
+ bool SetPublicRunLockToRunning();
+
+ /// The public state and public run lock seen by the thread handling a stop,
+ /// until the stop is made public. Every other thread keeps seeing the
+ /// public state from before the stop, which reads running. See
+ /// ProcessEventData::DoOnRemoval.
+ ///
+ /// Only the handling thread reads or writes the state and the flags, so
+ /// they need no lock of their own.
+ struct StopHandlingContext {
+ explicit StopHandlingContext(std::thread::id owner) : m_owner(owner) {}
+
+ const std::thread::id m_owner;
+ lldb::StateType m_public_state = lldb::eStateStopped;
+ ProcessRunLock m_public_run_lock;
+ /// Whether handling the stop resumed the process through this context.
+ bool m_resumed = false;
+ /// Whether this context's run lock was last set to running.
+ bool m_run_lock_running = false;
+ };
+ using StopHandlingContextSP = std::shared_ptr<StopHandlingContext>;
+
+ /// Holds a stop back from every other thread while the current thread
+ /// handles it, by giving this thread a context of its own and the policy
+ /// that selects it. Scopes nest: when one ends, the
+ /// context it replaced comes back.
+ class StopHandlingScope {
+ public:
+ explicit StopHandlingScope(Process &process);
+ ~StopHandlingScope();
+
+ /// Whether handling the stop resumed the process and it stopped again
+ /// before the handling was done, as it does after a synchronous
+ /// continue.
+ bool StoppedAgainAfterResume() const {
+ return m_context_sp->m_resumed && !m_context_sp->m_run_lock_running;
+ }
+
+ /// The state the handling thread last saw, which is the one to make
+ /// public once the stop is handled.
+ lldb::StateType GetPublicState() const {
+ return m_context_sp->m_public_state;
+ }
+
+ private:
+ Process &m_process;
+ StopHandlingContextSP m_context_sp;
+ StopHandlingContextSP m_enclosing_context_sp;
+ std::optional<PolicyStack::Guard> m_policy_guard;
+
+ StopHandlingScope(const StopHandlingScope &) = delete;
+ const StopHandlingScope &operator=(const StopHandlingScope &) = delete;
+ };
+
+ /// Return the context of the stop the current thread is handling, or null
+ /// if it isn't handling one for this process.
+ StopHandlingContextSP GetStopHandlingContextForCurrentThread() const;
std::recursive_mutex &GetPrivateStateMutex() {
assert(m_current_private_state_thread_sp);
return m_current_private_state_thread_sp->GetPrivateStateMutex();
}
- lldb::StateType GetPublicState() const {
- if (!m_current_private_state_thread_sp)
- return lldb::eStateUnloaded;
- return m_current_private_state_thread_sp->GetPublicState();
- }
+ lldb::StateType GetPublicState() const;
lldb::StateType GetPrivateState() const {
if (!m_current_private_state_thread_sp)
@@ -3483,6 +3538,11 @@ void PruneThreadPlans();
/// always be a private state thread in this slot.
std::shared_ptr<PrivateStateThread> m_current_private_state_thread_sp;
+ /// The context of the stop being handled, if any. Written by the handling
+ /// thread and read by every thread, under m_stop_handling_mutex.
+ StopHandlingContextSP m_stop_handling_context_sp;
+ mutable std::mutex m_stop_handling_mutex;
+
ProcessModID m_mod_id; ///< Tracks the state of the process over stops and
///other alterations.
uint32_t m_process_unique_id; ///< Each lldb_private::Process class that is
diff --git a/lldb/include/lldb/Utility/Policy.h b/lldb/include/lldb/Utility/Policy.h
index b3f2e1ba04e9ce..174c65928de493 100644
--- a/lldb/include/lldb/Utility/Policy.h
+++ b/lldb/include/lldb/Utility/Policy.h
@@ -31,10 +31,17 @@ class Stream;
/// than checking thread identity at every callsite, the private state thread
/// pushes Policy::CreatePrivateState() and the rest follows from the policy.
struct Policy {
- /// What view of the process this thread sees.
+ /// What view of the process this thread sees: which state and run lock it
+ /// reads, and which of the target's API mutexes it takes.
enum class View {
- Public, ///< Provider-augmented frames, public state, public run lock.
- Private, ///< Parent (unwinder) frames, private state, private run lock.
+ /// The public state, public run lock and API mutex that clients use.
+ Public,
+ /// The private state, private run lock and private API mutex that the
+ /// private state thread works from.
+ Private,
+ /// The state and run lock of a stop this thread is handling, before the
+ /// rest of the debugger sees it. Takes the same API mutex as Public.
+ HandlingStop,
};
/// What operations this thread is allowed to perform.
@@ -77,6 +84,7 @@ struct Policy {
PrivateStatePurpose purpose = PrivateStatePurpose::Default);
static Policy CreatePublicStateRunningExpression();
static Policy CreateScriptedExtensionCall();
+ static Policy CreateHandlingStop();
/// @}
void Dump(Stream &s) const;
@@ -147,6 +155,11 @@ class PolicyStack {
return Guard();
}
+ [[nodiscard]] Guard PushHandlingStop() {
+ Push(Policy::CreateHandlingStop());
+ return Guard();
+ }
+
private:
void Push(Policy policy) { m_stack.push_back(std::move(policy)); }
diff --git a/lldb/source/Interpreter/CommandInterpreter.cpp b/lldb/source/Interpreter/CommandInterpreter.cpp
index 6d361470039fda..a4c0f0b80c7fdc 100644
--- a/lldb/source/Interpreter/CommandInterpreter.cpp
+++ b/lldb/source/Interpreter/CommandInterpreter.cpp
@@ -3543,7 +3543,10 @@ bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
if (process) {
StateType state = process->GetState();
- if (StateIsRunningState(state)) {
+ // While another thread is still handling a stop, the process looks
+ // running from here but is actually stopped, so there is nothing to halt.
+ // Let the interrupt go to whatever is handling the stop instead.
+ if (StateIsRunningState(state) && !process->IsHandlingStopOnOtherThread()) {
process->Halt();
return true; // Don't do any updating when we are running
}
diff --git a/lldb/source/Target/Process.cpp b/lldb/source/Target/Process.cpp
index c1343fa196f6e8..aa9bab28408d9d 100644
--- a/lldb/source/Target/Process.cpp
+++ b/lldb/source/Target/Process.cpp
@@ -1335,6 +1335,86 @@ StateType Process::GetState() {
return GetPublicState();
}
+StateType Process::GetPublicState() const {
+ if (!m_current_private_state_thread_sp)
+ return eStateUnloaded;
+ if (StopHandlingContextSP context_sp =
+ GetStopHandlingContextForCurrentThread())
+ return context_sp->m_public_state;
+ return m_current_private_state_thread_sp->GetPublicState();
+}
+
+bool Process::SetPublicRunLockToStopped() {
+ if (StopHandlingContextSP context_sp =
+ GetStopHandlingContextForCurrentThread()) {
+ context_sp->m_run_lock_running = false;
+ return context_sp->m_public_run_lock.SetStopped();
+ }
+ assert(m_current_private_state_thread_sp);
+ if (m_current_private_state_thread_sp)
+ return m_current_private_state_thread_sp->SetPublicRunLockToStopped();
+ return false;
+}
+
+bool Process::SetPublicRunLockToRunning() {
+ if (StopHandlingContextSP context_sp =
+ GetStopHandlingContextForCurrentThread()) {
+ const bool was_stopped = context_sp->m_public_run_lock.SetRunning();
+ context_sp->m_run_lock_running = true;
+ context_sp->m_resumed |= was_stopped;
+ return was_stopped;
+ }
+ assert(m_current_private_state_thread_sp);
+ if (m_current_private_state_thread_sp)
+ return m_current_private_state_thread_sp->SetPublicRunLockToRunning();
+ return false;
+}
+
+Process::StopHandlingContextSP
+Process::GetStopHandlingContextForCurrentThread() const {
+ if (PolicyStack::Get().Current().view != Policy::View::HandlingStop)
+ return nullptr;
+ std::lock_guard<std::mutex> guard(m_stop_handling_mutex);
+ // A thread handling a stop for one process sees any other process the way
+ // every other thread does.
+ if (m_stop_handling_context_sp &&
+ m_stop_handling_context_sp->m_owner == std::this_thread::get_id())
+ return m_stop_handling_context_sp;
+ return nullptr;
+}
+
+bool Process::IsHandlingStopOnOtherThread() const {
+ std::lock_guard<std::mutex> guard(m_stop_handling_mutex);
+ return m_stop_handling_context_sp &&
+ m_stop_handling_context_sp->m_owner != std::this_thread::get_id();
+}
+
+Process::StopHandlingScope::StopHandlingScope(Process &process)
+ : m_process(process), m_context_sp(std::make_shared<StopHandlingContext>(
+ std::this_thread::get_id())) {
+ {
+ std::lock_guard<std::mutex> guard(m_process.m_stop_handling_mutex);
+ m_enclosing_context_sp =
+ std::exchange(m_process.m_stop_handling_context_sp, m_context_sp);
+ }
+ // Push the policy only once the context it selects is in place.
+ m_policy_guard.emplace(PolicyStack::Get().PushHandlingStop());
+}
+
+Process::StopHandlingScope::~StopHandlingScope() {
+ m_policy_guard.reset();
+ std::lock_guard<std::mutex> guard(m_process.m_stop_handling_mutex);
+ // Another thread may have replaced the context if it consumed a stop of
+ // this process at the same time, in which case that thread restores it.
+ if (m_process.m_stop_handling_context_sp != m_context_sp)
+ return;
+ // Only a scope this thread opened earlier is known to be still open.
+ if (m_enclosing_context_sp &&
+ m_enclosing_context_sp->m_owner != m_context_sp->m_owner)
+ m_enclosing_context_sp.reset();
+ m_process.m_stop_handling_context_sp = std::move(m_enclosing_context_sp);
+}
+
void Process::SetPublicState(StateType new_state, bool restarted) {
const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
if (new_state_is_stopped) {
@@ -1351,7 +1431,11 @@ void Process::SetPublicState(StateType new_state, bool restarted) {
LLDB_LOGF(log, "(plugin = %s, state = %s, restarted = %i)",
GetPluginName().data(), StateAsCString(new_state), restarted);
const StateType old_state = GetPublicState();
- m_current_private_state_thread_sp->SetPublicState(new_state);
+ if (StopHandlingContextSP context_sp =
+ GetStopHandlingContextForCurrentThread())
+ context_sp->m_public_state = new_state;
+ else
+ m_current_private_state_thread_sp->SetPublicState(new_state);
// On the transition from Run to Stopped, we unlock the writer end of the run
// lock. The lock gets locked in Resume, which is the public API to tell the
@@ -3632,6 +3716,12 @@ Status Process::PrivateResume() {
}
Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
+ // The process is already stopped. Interrupting it now would interrupt the
+ // expressions run while handling the stop.
+ if (IsHandlingStopOnOtherThread())
+ return Status::FromErrorString(
+ "process is stopped, but another thread is still handling the stop");
+
if (!StateIsRunningState(GetPublicState()))
return Status::FromErrorString("Process is not running.");
@@ -3738,8 +3828,12 @@ Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
// Check both the public & private states here. If we're hung evaluating an
// expression, for instance, then the public state will be stopped, but we
- // still need to interrupt.
- if (GetPublicState() == eStateRunning || GetPrivateState() == eStateRunning) {
+ // still need to interrupt. While another thread handles a stop, the public
+ // state reads running although the process is stopped, so only the private
+ // state can tell.
+ const bool public_running =
+ GetPublicState() == eStateRunning && !IsHandlingStopOnOtherThread();
+ if (public_running || GetPrivateState() == eStateRunning) {
Log *log = GetLog(LLDBLog::Process);
LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
@@ -3874,12 +3968,13 @@ Status Process::DestroyImpl(bool force_kill) {
error = StopForDestroyOrDetach(exit_event_sp);
}
- if (GetPublicState() == eStateStopped) {
+ if (GetPublicState() == eStateStopped || IsHandlingStopOnOtherThread()) {
// Ditch all thread plans, and remove all our breakpoints: in case we
// have to restart the target to kill it, we don't want it hitting a
// breakpoint... Only do this if we've stopped, however, since if we
// didn't manage to halt it above, then we're not going to have much luck
- // doing this now.
+ // doing this now. The process is also stopped while another thread is
+ // still handling a stop, even though it looks running from here.
m_thread_list.DiscardThreadPlans();
DisableAllBreakpointSites();
if (auto error = FlushDelayedBreakpoints())
@@ -4705,8 +4800,27 @@ void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
return;
m_update_state++;
- process_sp->SetPublicState(
- m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
+ // Halt events don't run the StopInfo actions, even if the halt stopped with
+ // some reason other than a plain interrupt (e.g. we had already stopped for
+ // a breakpoint when the halt request came through), as they may end up
+ // restarting the process. Neither do events that aren't stops, or stops
+ // that have already been restarted.
+ const bool performs_stop_actions =
+ m_state == eStateStopped && !m_restarted && !m_interrupted;
+
+ // A stop handled here is only made public once its actions and stop hooks
+ // are done. Until then this thread sees the process stopped and every
+ // other thread still sees it running, so nothing can resume or inspect the
+ // process underneath them. Stops that an expression consumes run no
+ // actions, and the private state thread has its own view.
+ const Policy policy = PolicyStack::Get().Current();
+ const bool holds_stop = performs_stop_actions &&
+ policy.view != Policy::View::Private &&
+ policy.capabilities.can_run_breakpoint_actions;
+
+ if (!holds_stop)
+ process_sp->SetPublicState(
+ m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
if (m_state == eStateStopped && !m_restarted) {
// Let process subclasses know we are about to do a public stop and do
@@ -4715,18 +4829,31 @@ void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
process_sp->WillPublicStop();
}
- // If this is a halt event, even if the halt stopped with some reason other
- // than a plain interrupt (e.g. we had already stopped for a breakpoint when
- // the halt request came through) don't do the StopInfo actions, as they may
- // end up restarting the process.
- if (m_interrupted)
+ if (!performs_stop_actions)
return;
- // If we're not stopped or have restarted, then skip the StopInfo actions:
- if (m_state != eStateStopped || m_restarted) {
+ if (!holds_stop) {
+ PerformStopActions(*process_sp, event_ptr);
return;
}
+ bool make_public;
+ StateType final_state;
+ {
+ StopHandlingScope scope(*process_sp);
+ PerformStopActions(*process_sp, event_ptr);
+ // If handling the stop restarted the process, it stays running to
+ // everyone else. The exception is a synchronous continue: the process
+ // stopped again, and that stop never reached anyone else either.
+ make_public = !m_restarted || scope.StoppedAgainAfterResume();
+ final_state = scope.GetPublicState();
+ }
+ if (make_public)
+ process_sp->SetPublicState(final_state, /*restarted=*/false);
+}
+
+void Process::ProcessEventData::PerformStopActions(Process &process,
+ Event *event_ptr) {
bool does_anybody_have_an_opinion = false;
bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
@@ -4739,10 +4866,10 @@ void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
SetRestarted(true);
// Use the private resume method here, since we aren't changing the run
// lock state.
- process_sp->PrivateResume();
+ process.PrivateResume();
} else {
- bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
- !process_sp->StateChangedIsHijackedForSynchronousResume();
+ bool hijacked = process.IsHijackedForEvent(eBroadcastBitStateChanged) &&
+ !process.StateChangedIsHijackedForSynchronousResume();
if (!hijacked) {
// If we didn't restart, run the Stop Hooks here.
@@ -4750,7 +4877,7 @@ void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
// public (or SyncResume) broadcasters. StopHooks are just for
// real public stops. They might also restart the target,
// so watch for that.
- if (process_sp->GetTarget().RunStopHooks())
+ if (process.GetTarget().RunStopHooks())
SetRestarted(true);
}
}
@@ -6256,6 +6383,11 @@ void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton
}
ProcessRunLock &Process::GetRunLock() {
+ // The scope that installed the context keeps it alive for as long as this
+ // thread can be handed it.
+ if (StopHandlingContextSP context_sp =
+ GetStopHandlingContextForCurrentThread())
+ return context_sp->m_public_run_lock;
return m_current_private_state_thread_sp->GetRunLock();
}
diff --git a/lldb/source/Utility/Policy.cpp b/lldb/source/Utility/Policy.cpp
index bd17bf90bd59e1..3e130003053782 100644
--- a/lldb/source/Utility/Policy.cpp
+++ b/lldb/source/Utility/Policy.cpp
@@ -76,6 +76,27 @@ Policy Policy::CreateScriptedExtensionCall() {
return p;
}
+// The rest of the debugger keeps seeing the process running until the stop
+// is handled, so that nothing can resume or inspect the process underneath
+// the thread handling it. That thread sees the stop.
+Policy Policy::CreateHandlingStop() {
+ Policy p = PolicyStack::Get().Current();
+ p.view = View::HandlingStop;
+ return p;
+}
+
+static llvm::StringRef GetViewName(Policy::View view) {
+ switch (view) {
+ case Policy::View::Public:
+ return "public";
+ case Policy::View::Private:
+ return "private";
+ case Policy::View::HandlingStop:
+ return "handling-stop";
+ }
+ llvm_unreachable("unhandled policy view");
+}
+
PolicyStack::Guard::~Guard() {
if (!m_active)
return;
@@ -112,7 +133,7 @@ PolicyStack::Guard &PolicyStack::Guard::operator=(Guard &&other) {
}
void Policy::Dump(Stream &s) const {
- s << "policy: view=" << (view == View::Public ? "public" : "private");
+ s << "policy: view=" << GetViewName(view);
s << ", capabilities={";
s << "eval_expr=" << capabilities.can_evaluate_expressions;
s << " run_all=" << capabilities.can_run_all_threads;
diff --git a/lldb/test/API/api/multithreaded/stop_reporting/Makefile b/lldb/test/API/api/multithreaded/stop_reporting/Makefile
new file mode 100644
index 00000000000000..beaa00d907bf59
--- /dev/null
+++ b/lldb/test/API/api/multithreaded/stop_reporting/Makefile
@@ -0,0 +1,8 @@
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp
+
+# Sources shared between the multithreaded tests live in the parent directory.
+override VPATH += $(SRCDIR)/..
+override CFLAGS_EXTRAS += -I$(SRCDIR)/..
+
+include Makefile.rules
diff --git a/lldb/test/API/api/multithreaded/stop_reporting/TestMultithreadedStopReporting.py b/lldb/test/API/api/multithreaded/stop_reporting/TestMultithreadedStopReporting.py
new file mode 100644
index 00000000000000..c34aa7836e9509
--- /dev/null
+++ b/lldb/test/API/api/multithreaded/stop_reporting/TestMultithreadedStopReporting.py
@@ -0,0 +1,21 @@
+"""Test that a stop stays private to the thread handling it."""
+
+from lldbsuite.test.decorators import *
+from lldbsuite.test.lldbtest import *
+
+
+ at requireThreadSupport
+ at skipIfNoSBHeaders
+ at skipIfRemote
+ at skipIfHostIncompatibleWithTarget
+class MultithreadedStopReportingTestCase(TestBase):
+ SHARED_BUILD_TESTCASE = False
+ NO_DEBUG_INFO_TESTCASE = True
+
+ @skipIfWindows # https://github.com/llvm/llvm-project/issues/225860
+ # Occasional SIGABRT, see https://github.com/llvm/llvm-project/issues/225860.
+ @skipIf(oslist=["linux"], archs=["aarch64"])
+ def test(self):
+ self.buildAndRunDriver(
+ "driver.cpp test_stop_reporting.cpp", "stop_reporting.cpp"
+ )
diff --git a/lldb/test/API/api/multithreaded/stop_reporting/stop_reporting.cpp b/lldb/test/API/api/multithreaded/stop_reporting/stop_reporting.cpp
new file mode 100644
index 00000000000000..e09f2675d03db8
--- /dev/null
+++ b/lldb/test/API/api/multithreaded/stop_reporting/stop_reporting.cpp
@@ -0,0 +1,13 @@
+int bkpt_function(int input) {
+ return input * 10; // Set a breakpoint here:
+}
+
+int call_me_function(int input) { return input * 20; }
+
+int main() {
+ int counter = 0; // Set a breakpoint in main
+ counter += call_me_function(5);
+ counter += bkpt_function(10);
+ counter += bkpt_function(15);
+ return counter;
+}
diff --git a/lldb/test/API/api/multithreaded/stop_reporting/stop_reporting_callbacks.py b/lldb/test/API/api/multithreaded/stop_reporting/stop_reporting_callbacks.py
new file mode 100644
index 00000000000000..038d04a0f8cf72
--- /dev/null
+++ b/lldb/test/API/api/multithreaded/stop_reporting/stop_reporting_callbacks.py
@@ -0,0 +1,41 @@
+import lldb
+import time
+
+signal_var = False
+failed_calls = 0
+
+# Long enough for the driver's other thread to finish its checks, short enough
+# that a broken test fails instead of hanging.
+DEADLINE_SECONDS = 60
+
+
+def slow_breakpoint_callback(frame, bp_loc, extra_args, unused):
+ global signal_var, failed_calls
+ # Keep calling a function in the target until the driver's other thread
+ # says to stop, so that thread has time to check what it sees meanwhile.
+ signal_var = True
+ options = lldb.SBExpressionOptions()
+ options.SetStopOthers(True)
+ options.SetTryAllThreads(False)
+
+ deadline = time.monotonic() + DEADLINE_SECONDS
+ while signal_var and time.monotonic() < deadline:
+ time.sleep(0.01)
+ valobj = frame.EvaluateExpression("call_me_function(1)", options)
+ if not valobj.error.success:
+ failed_calls += 1
+
+
+def handle_signal_var(debugger, command, result, unused):
+ global signal_var
+ if len(command) == 0:
+ result.Print("True" if signal_var else "False")
+ result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
+ else:
+ signal_var = False
+ result.SetStatus(lldb.eReturnStatusSuccessFinishNoResult)
+
+
+def handle_failed_calls(debugger, command, result, unused):
+ result.Print(str(failed_calls))
+ result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
diff --git a/lldb/test/API/api/multithreaded/stop_reporting/test_stop_reporting.cpp b/lldb/test/API/api/multithreaded/stop_reporting/test_stop_reporting.cpp
new file mode 100644
index 00000000000000..b71066b2e0d099
--- /dev/null
+++ b/lldb/test/API/api/multithreaded/stop_reporting/test_stop_reporting.cpp
@@ -0,0 +1,302 @@
+// LLDB C++ API Test: verify that while a stop is being handled, it stays
+// private to the thread handling it. That thread sees the process stopped and
+// can run expressions, but every other thread sees it running and can neither
+// inspect, resume nor halt it.
+
+#include <chrono>
+#include <cstdlib>
+#include <cstring>
+#include <errno.h>
+#ifdef _WIN32
+#include <fcntl.h>
+#include <io.h>
+#endif
+#include <mutex>
+#include <stdio.h>
+#include <string>
+#include <thread>
+#include <unistd.h>
+#include <vector>
+
+#include "lldb/API/SBBreakpoint.h"
+#include "lldb/API/SBBroadcaster.h"
+#include "lldb/API/SBCommandInterpreter.h"
+#include "lldb/API/SBCommandReturnObject.h"
+#include "lldb/API/SBDebugger.h"
+#include "lldb/API/SBError.h"
+#include "lldb/API/SBEvent.h"
+#include "lldb/API/SBFileSpec.h"
+#include "lldb/API/SBListener.h"
+#include "lldb/API/SBProcess.h"
+#include "lldb/API/SBStream.h"
+#include "lldb/API/SBStructuredData.h"
+#include "lldb/API/SBTarget.h"
+#include "lldb/API/SBThread.h"
+
+#include "common.h"
+
+#if !defined(PATH_MAX)
+#define PATH_MAX 4096
+#endif
+
+using namespace lldb;
+
+// Wait for the next state-changed event, skipping the inferior's stdout and
+// stderr events, which also carry the process state.
+bool wait_for_state_event(SBListener &listener, SBEvent &event) {
+ while (listener.WaitForEvent(10, event))
+ if (event.GetType() & SBProcess::eBroadcastBitStateChanged)
+ return true;
+ return false;
+}
+
+bool continue_to_breakpoint(SBDebugger dbg, SBProcess process, SBThread thread,
+ lldb::break_id_t bkpt_id, std::string &reason) {
+ // And wait for it to start running and stop again:
+ SBEvent event;
+ SBListener proc_listener = dbg.GetListener();
+ process.Continue();
+
+ if (!wait_for_state_event(proc_listener, event)) {
+ reason = "Didn't get an event after Continue";
+ return false;
+ }
+
+ if (SBProcess::GetStateFromEvent(event) != lldb::eStateRunning) {
+ reason = "Didn't get a running event after Continue";
+ return false;
+ }
+
+ if (!wait_for_state_event(proc_listener, event)) {
+ reason = "Didn't get an event after run event";
+ return false;
+ }
+
+ if (SBProcess::GetStateFromEvent(event) != lldb::eStateStopped) {
+ reason = "Didn't get a stop event after run event";
+ return false;
+ }
+
+ if (!thread.IsValid()) {
+ reason = "Traced thread is not valid.";
+ return false;
+ }
+
+ if (thread.GetStopReason() != lldb::eStopReasonBreakpoint) {
+ reason = "Tracked thread didn't stop for a breakpoint reason.";
+ return false;
+ }
+
+ if (thread.GetStopReasonDataAtIndex(0) != bkpt_id) {
+ reason = "Tracked thread didn't stop at the right breakpoint";
+ return false;
+ }
+ return true;
+}
+
+bool get_command_output(SBCommandInterpreter &interp, const char *command,
+ std::string &output) {
+ SBCommandReturnObject result;
+ interp.HandleCommand(command, result);
+ if (!result.Succeeded())
+ return false;
+ const char *result_output = result.GetOutput();
+ output = result_output ? result_output : "";
+ return true;
+}
+
+void test(SBDebugger &dbg, std::vector<std::string> args) {
+ // Between a stop event being received and the completion of its
+ // PerformAction, the public state of the process stays "running". The
+ // PerformAction can call back into the command line or Python, so IT has to
+ // see the process stopped. But no other thread can, or it could resume the
+ // process and destroy objects that the PerformAction is still using.
+ //
+ // To test this, the stop runs a breakpoint callback that stalls, calling a
+ // function in the target until it is told to stop. Meanwhile another thread
+ // repeatedly does things that require the process to be stopped, and checks
+ // that they all fail.
+
+ dbg.SetAsync(true);
+
+ const char *exe_name = args.at(0).c_str();
+ SBTarget target = dbg.CreateTarget(exe_name);
+ if (!target.IsValid())
+ throw Exception("invalid target");
+ SBFileSpec main_spec("stop_reporting.cpp");
+
+ SBBreakpoint start_bkpt = target.BreakpointCreateBySourceRegex(
+ "Set a breakpoint in main", main_spec);
+ if (!start_bkpt.IsValid() || start_bkpt.GetNumLocations() == 0)
+ throw Exception("invalid breakpoint");
+
+ SBCommandInterpreter interp = dbg.GetCommandInterpreter();
+ SBCommandReturnObject result;
+
+ // The test sets LLDB_TEST_SOURCE_DIR to the directory containing this
+ // test's support files.
+ const char *source_dir = getenv("LLDB_TEST_SOURCE_DIR");
+ if (!source_dir)
+ throw Exception("LLDB_TEST_SOURCE_DIR is not set");
+ SBFileSpec script_spec(source_dir);
+ script_spec.AppendPathComponent("stop_reporting_callbacks.py");
+ char path[PATH_MAX];
+ script_spec.GetPath(path, PATH_MAX);
+
+ std::string import_command("command script import ");
+ import_command.append(path);
+ interp.HandleCommand(import_command.c_str(), result);
+ if (!result.Succeeded())
+ throw Exception(std::string("Couldn't import ") + path);
+
+ SBProcess process = target.LaunchSimple(nullptr, nullptr, nullptr);
+
+ if (!process.IsValid())
+ throw Exception(std::string("Couldn't launch process."));
+
+ if (process.GetState() != lldb::eStateStopped)
+ throw Exception(std::string("Process not stopped after LaunchSimple."));
+
+ SBThread main_thread = process.GetSelectedThread();
+
+ // Continue from the stop point to our initial breakpoint:
+ std::string error_str;
+ if (!continue_to_breakpoint(dbg, process, main_thread, start_bkpt.GetID(),
+ error_str))
+ throw Exception(error_str);
+
+ // Now add our test breakpoint, and then add a callback to it:
+ SBBreakpoint breakpoint =
+ target.BreakpointCreateBySourceRegex("Set a breakpoint here", main_spec);
+ if (!breakpoint.IsValid() || breakpoint.GetNumLocations() == 0)
+ throw Exception("invalid breakpoint in bkpt_function");
+ SBError error;
+ SBStructuredData extra_args;
+ error = breakpoint.SetScriptCallbackFunction(
+ "stop_reporting_callbacks.slow_breakpoint_callback", extra_args);
+ if (error.Fail())
+ throw Exception(std::string("Failed adding breakpoint command"));
+
+ // The commands we use to get info in and out of the callback:
+ interp.HandleCommand("command script add -f "
+ "stop_reporting_callbacks.handle_signal_var "
+ "handle_signal_var",
+ result);
+ if (!result.Succeeded())
+ throw Exception(std::string("Couldn't add handle_signal_var command."));
+ interp.HandleCommand("command script add -f "
+ "stop_reporting_callbacks.handle_failed_calls "
+ "handle_failed_calls",
+ result);
+ if (!result.Succeeded())
+ throw Exception(std::string("Couldn't add handle_failed_calls command."));
+
+ // Spawn the thread that waits, using `handle_signal_var`, for the callback
+ // to start running, and then checks that the process looks running to it.
+ // Finally it flips the variable so the callback can return.
+ std::string err_str = "Test thread didn't finish";
+ int num_tries = 10;
+ std::thread test_running_thread([&interp, &process, &err_str, &num_tries]() {
+ // Whatever happens, let the callback return. Otherwise the main thread
+ // never gets its stop event back and the test hangs instead of failing.
+ struct ReleaseCallback {
+ SBCommandInterpreter &interp;
+ ~ReleaseCallback() {
+ SBCommandReturnObject result;
+ interp.HandleCommand("handle_signal_var False", result);
+ }
+ } release_callback{interp};
+
+ auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60);
+ while (true) {
+ std::string output;
+ if (!get_command_output(interp, "handle_signal_var", output)) {
+ err_str = "Error calling handle_signal_var";
+ return;
+ }
+ if (output == "True")
+ break;
+ if (output != "False") {
+ err_str = "Unexpected result from handle_signal_var";
+ return;
+ }
+ if (std::chrono::steady_clock::now() > deadline) {
+ err_str = "The breakpoint callback never ran";
+ return;
+ }
+ usleep(10);
+ }
+
+ // The callback is now running, so everything below must fail.
+ if (process.GetState() != lldb::eStateRunning) {
+ err_str = "Process didn't look running while the callback ran";
+ return;
+ }
+
+ for (; num_tries > 0; num_tries--) {
+ SBCommandReturnObject expr_result;
+ interp.HandleCommand("expr call_me_function(1)", expr_result);
+ if (expr_result.Succeeded()) {
+ err_str = "Expression succeeded while the callback ran";
+ return;
+ }
+ usleep(10);
+ }
+
+ if (process.Continue().Success()) {
+ err_str = "Continue succeeded while the callback ran";
+ return;
+ }
+
+ if (process.Stop().Success()) {
+ err_str = "Stop succeeded while the callback ran";
+ return;
+ }
+
+ err_str.clear();
+ });
+
+ // Okay, our test thread is running, so continue the process:
+ bool stopped = continue_to_breakpoint(dbg, process, main_thread,
+ breakpoint.GetID(), error_str);
+
+ test_running_thread.join();
+ if (!err_str.empty())
+ throw Exception(err_str);
+ if (!stopped)
+ throw Exception(error_str);
+
+ // We should have gotten 10 tries at the expression, without being
+ // interrupted.
+ if (num_tries != 0)
+ throw Exception(std::string("Didn't get to run 10 times"));
+
+ // And the callback's own expressions must all have worked.
+ std::string failed_calls;
+ if (!get_command_output(interp, "handle_failed_calls", failed_calls))
+ throw Exception(std::string("Error calling handle_failed_calls"));
+ if (failed_calls != "0")
+ throw Exception("The callback's expressions failed " + failed_calls +
+ " times");
+
+ // Now run to exit - make sure we didn't stall the process.
+ breakpoint.SetEnabled(false);
+ SBEvent event;
+ SBListener proc_listener = dbg.GetListener();
+ process.Continue();
+
+ if (!wait_for_state_event(proc_listener, event))
+ throw Exception(std::string("Didn't get an event after Continue"));
+
+ if (SBProcess::GetStateFromEvent(event) != lldb::eStateRunning)
+ throw Exception(std::string("Didn't get an running event after Continue"));
+
+ if (!wait_for_state_event(proc_listener, event))
+ throw Exception(std::string("Didn't get an event after running"));
+
+ StateType final_state = SBProcess::GetStateFromEvent(event);
+ if (final_state != lldb::eStateExited)
+ throw Exception(std::string("Didn't get an exited event after running, "
+ "got: ") +
+ SBDebugger::StateAsCString(final_state));
+}
diff --git a/lldb/unittests/Utility/PolicyTest.cpp b/lldb/unittests/Utility/PolicyTest.cpp
index cc514b879f5fd9..22492c6f1e08cb 100644
--- a/lldb/unittests/Utility/PolicyTest.cpp
+++ b/lldb/unittests/Utility/PolicyTest.cpp
@@ -94,6 +94,25 @@ TEST(PolicyTest, ScriptedExtensionCallWithdrawalIsInherited) {
EXPECT_FALSE(nested.capabilities.can_try_all_threads);
}
+TEST(PolicyTest, HandlingStop) {
+ Policy p = Policy::CreateHandlingStop();
+ EXPECT_EQ(p.view, Policy::View::HandlingStop);
+ // A stop's actions run in this scope, and they may run expressions.
+ EXPECT_TRUE(p.capabilities.can_evaluate_expressions);
+ EXPECT_TRUE(p.capabilities.can_run_breakpoint_actions);
+ EXPECT_TRUE(p.capabilities.can_load_frame_providers);
+}
+
+TEST(PolicyTest, HandlingStopViewIsInherited) {
+ // An expression run while handling a stop keeps seeing the stop.
+ PolicyStack::Guard outer = PolicyStack::Get().PushHandlingStop();
+ PolicyStack::Guard inner =
+ PolicyStack::Get().PushPublicStateRunningExpression();
+ EXPECT_EQ(PolicyStack::Get().Current().view, Policy::View::HandlingStop);
+ EXPECT_FALSE(
+ PolicyStack::Get().Current().capabilities.can_run_breakpoint_actions);
+}
+
TEST(PolicyTest, StackDefaultIsPublicState) {
Policy current = PolicyStack::Get().Current();
EXPECT_EQ(current.view, Policy::View::Public);
@@ -183,6 +202,16 @@ TEST(PolicyTest, DumpPrivateState) {
"bypass_api_mutex=false}");
}
+TEST(PolicyTest, DumpHandlingStop) {
+ StreamString s;
+ Policy::CreateHandlingStop().Dump(s);
+ EXPECT_EQ(s.GetString(),
+ "policy: view=handling-stop, capabilities={"
+ "eval_expr=true run_all=true try_all=true "
+ "bp_actions=true frame_providers=true frame_recognizers=true "
+ "bypass_api_mutex=false}");
+}
+
TEST(PolicyTest, DumpStack) {
PolicyStack::Guard guard = PolicyStack::Get().PushPrivateState();
More information about the lldb-commits
mailing list