← Back to Pull requests

[lldb] Keep a stop private until it has been handled #234789

Open
medismailben opened this pull request with 802 lines diff across 11 files
View on GitHub
medismailben medismailben commented on Oct 22, 2026 22:57 UTC
Author

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 left the process running. So after an auto-continue, the main run lock now stays held while the process runs, where before it was released and never taken again.

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, and an interrupt in the command interpreter goes to the script interpreter, as it does when the process is stopped.

Expressions the private state thread runs for a stop before it broadcasts it, such as breakpoint conditions, aren't covered yet: see the FIXME in RunThreadPlan.

Co-authored-by: Jim Ingham <jingham@apple.com>
Assisted-by: Claude

Diff: 802 lines (+762 / -40) across 11 files Reviewer: jimingham Review duration: 59933m
All Vouch review confidence checks passed
Residual risk 0.08 = Change Risk (0.65) × (1 − Review Confidence (0.88)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.65 · 802 lines diff across 11 files
0.65
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.90 · 5 substantive comment(s)
0.90
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
87%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Real PR Conversation Timeline
12 items
github-actions[bot] github-actions[bot] commented on Oct 22, 2026 23:00 UTC
Bot

<!--LLVM CODE FORMAT COMMENT: {clang-format}-->

:white_check_mark: With the latest revision this PR passed the C/C++ code formatter.

medismailben medismailben commented on Oct 23, 2026 22:49 UTC
Author

This is a tentative fix and the implementation is deliberately quite verbose as this is a complex problem to understand in the first place and solve.

jimingham jimingham commented on code on Oct 29, 2026 21:11 UTC
Code Review
lldb/include/lldb/Target/Process.h:1
@@ -3423,29 +3437,94 @@ 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 of a stop that a thread is handling
+  /// in ProcessEventData::DoOnRemoval, before the stop is made public. On the
+  /// handling thread, GetState(), GetPublicState(), SetPublicState(),
+  /// GetRunLock() and SetPublicRunLockToRunning/Stopped() use these instead
+  /// of the PrivateStateThread's public state and public run lock. For every
+  /// other thread, those keep their values from before the stop (eStateRunning
+  /// and a run lock set to running) until DoOnRemoval makes the stop public.
+  ///
+  /// After construction only the handling thread reads or writes the members,
+  /// 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;
+    /// Set once SetPublicRunLockToRunning() succeeds on this context, that is
+    /// once Resume() or ResumeSynchronous() resumed the process while the stop
+    /// was being handled.
+    bool m_resumed = false;
+    /// Whether m_public_run_lock was last set to running. ResumeSynchronous()
+    /// sets it back to stopped when the stop it waits for arrives.
+    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 in ProcessEventData::DoOnRemoval.
+  ///
+  /// Scopes nest on the handling thread. If one of the stop's actions resumes
+  /// the process with ResumeSynchronous(), that call waits for the next stop
+  /// on this same thread, and pulling that stop from its hijack listener runs
+  /// DoOnRemoval again, opening a second scope inside the first. When the
+  /// inner scope ends, its stop is made public into the outer scope's
+  /// context, not the PrivateStateThread's.
+  ///
+  /// DoOnRemoval runs with View::Private on the private state thread and

DoOnRemoval runs several times in the life-cycle of an event. In simplistic terms, it always runs on the thread that pulls the event from the event queue. But that happens a couple of times with different contexts.

The stopped event is originally reported by the gdb-remote-async thread, and pulled from there as a "private event" by a listener on the Private State Thread. DoOnRemoval is first run in that "private" mode where only synchronous callbacks are run.

Then after running the event through the thread plan machinery, if the event will be broadcast publicly, it is made available to the Process Primary Listener, which pulls it off on whatever thread it is using for Event Handling. DoOnRemoval gets run AGAIN when the Primary Process Listener calls WaitForEvent, which is when the asynchronous callbacks are run.

Then DoOnRemoval (now a no-op) gets run again as any other secondary Process Listeners call WaitForEvent.

The complexity with the Private state thread is that sometimes it needs to run expressions while processing a stop, and it can't run itself as private state thread to do that, so it makes a "secondary private state thread" where the current PST plays the role of the async Event Handling Thread, and the secondary PST becomes the one to fetch events from the gdb-remote async thread.

jimingham jimingham commented on code on Oct 29, 2026 21:15 UTC
Code Review
lldb/include/lldb/Target/Process.h:1
@@ -1294,6 +1297,17 @@ class Process : public std::enable_shared_from_this<Process>,
   /// \see lldb::StateType
   lldb::StateType GetState();
 
+  /// Return true if a thread other than the calling one is in

This does not seem like it should be a public method. What would clients of this process do with this information?

jimingham jimingham commented on code on Oct 29, 2026 21:19 UTC
Code Review
lldb/include/lldb/Target/Process.h:1
@@ -3423,29 +3437,94 @@ 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 of a stop that a thread is handling
+  /// in ProcessEventData::DoOnRemoval, before the stop is made public. On the
+  /// handling thread, GetState(), GetPublicState(), SetPublicState(),
+  /// GetRunLock() and SetPublicRunLockToRunning/Stopped() use these instead
+  /// of the PrivateStateThread's public state and public run lock. For every
+  /// other thread, those keep their values from before the stop (eStateRunning
+  /// and a run lock set to running) until DoOnRemoval makes the stop public.
+  ///
+  /// After construction only the handling thread reads or writes the members,
+  /// 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;
+    /// Set once SetPublicRunLockToRunning() succeeds on this context, that is
+    /// once Resume() or ResumeSynchronous() resumed the process while the stop
+    /// was being handled.
+    bool m_resumed = false;
+    /// Whether m_public_run_lock was last set to running. ResumeSynchronous()
+    /// sets it back to stopped when the stop it waits for arrives.
+    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 in ProcessEventData::DoOnRemoval.
+  ///
+  /// Scopes nest on the handling thread. If one of the stop's actions resumes
+  /// the process with ResumeSynchronous(), that call waits for the next stop
+  /// on this same thread, and pulling that stop from its hijack listener runs
+  /// DoOnRemoval again, opening a second scope inside the first. When the
+  /// inner scope ends, its stop is made public into the outer scope's
+  /// context, not the PrivateStateThread's.
+  ///
+  /// DoOnRemoval runs with View::Private on the private state thread and
+  /// creates no scope there, so a stop isn't held back while the private
+  /// state thread runs expressions for it, such as breakpoint conditions. See
+  /// the FIXME in RunThreadPlan.
+  class StopHandlingScope {
+  public:
+    explicit StopHandlingScope(Process &process);
+    ~StopHandlingScope();
+
+    /// True if Resume() or ResumeSynchronous() was called while handling the
+    /// stop and the context's run lock was set back to stopped before the scope
+    /// ended. ResumeSynchronous() does that after consuming the next stop on
+    /// this thread through its hijack listener, so no client got that stop's
+    /// event and it still has to be made public. Resume() does it only when it
+    /// fails, in which case the process never ran.
+    bool StoppedAgainAfterResume() const {
+      return m_context_sp->m_resumed && !m_context_sp->m_run_lock_running;
+    }
+
+    /// The context's public state once the stop is handled, which DoOnRemoval
+    /// then makes public. Usually eStateStopped, or eStateExited if the process
+    /// exited while the stop was being 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;
+    PolicyStack::Guard m_policy_guard;
+
+    StopHandlingScope(const StopHandlingScope &) = delete;
+    const StopHandlingScope &operator=(const StopHandlingScope &) = delete;
+  };
+
+  /// Return m_stop_handling_context_sp if the current thread's policy view is
+  /// HandlingStop and this thread opened that context's StopHandlingScope,
+  /// null otherwise.
+  StopHandlingContextSP GetStopHandlingContextForCurrentThread() const;
+
+  StopHandlingContextSP GetStopHandlingContext() const;

What is this one for?

jimingham jimingham commented on code on Oct 29, 2026 21:24 UTC
Code Review
lldb/include/lldb/Utility/Policy.h:1
@@ -31,10 +31,21 @@ 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.
+  /// Which of the process's states and run locks this thread reads, and which
+  /// of the target's API mutexes it takes. See Process::GetState(),
+  /// Process::GetRunLock() and Target::GetAPIMutexForCurrentPolicy().
   enum class View {
-    Public,  ///< Provider-augmented frames, public state, public run lock.
-    Private, ///< Parent (unwinder) frames, private state, private run lock.
+    /// The public state, the public run lock and the target's public API
+    /// mutex.
+    Public,
+    /// The private state, the private run lock and the target's private API
+    /// mutex. Pushed on the private state thread.
+    Private,
+    /// The state and run lock of the Process::StopHandlingContext for the stop
+    /// this thread is handling in ProcessEventData::DoOnRemoval, which read
+    /// stopped while every other thread still gets eStateRunning. Takes the

Should it take the Target API mutex? If I'm in synchronous mode, a call to "SBProcess::Continue" will still hold the Target API mutex, but the callback is very likely to also call API's that take the Target API mutex as well. The thread handling the async callback DoOnRemoval needs a waiver on the Target API mutex, I think.

jimingham jimingham commented on code on Oct 29, 2026 21:28 UTC
Code Review
lldb/source/Interpreter/CommandInterpreter.cpp:1
@@ -3543,7 +3543,12 @@ bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
 
   if (process) {
     StateType state = process->GetState();
-    if (StateIsRunningState(state)) {
+    // While another thread is handling a stop, GetState() returns eStateRunning
+    // here only because the stop isn't public yet: the process is stopped, and
+    // Halt() would refuse. Fall through to ScriptInterpreter::Interrupt()
+    // below, which is what an interrupt does while the process is stopped, so
+    // Python running as one of the stop's actions is interrupted the same way.
+    if (StateIsRunningState(state) && !process->IsHandlingStopOnOtherThread()) {

This seems the wrong place to do this. Process::Halt should handle ensuring that the process gets done with (or interrupts) the DoOnRemoval handling and then either halts again (if DoOnRemoval restarted the process) or reports the halt state. There are other places that also want to Halt, and none of them should have to know about the details of the DoOnRemoval handling.

jimingham jimingham commented on code on Oct 29, 2026 21:44 UTC
Code Review
lldb/source/Target/Process.cpp:1
@@ -1335,6 +1335,98 @@ 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::GetStopHandlingContext() const {
+  std::lock_guard<std::mutex> guard(m_stop_handling_mutex);
+  return m_stop_handling_context_sp;
+}
+
+Process::StopHandlingContextSP
+Process::GetStopHandlingContextForCurrentThread() const {
+  if (PolicyStack::Get().Current().view != Policy::View::HandlingStop)
+    return nullptr;
+  StopHandlingContextSP context_sp = GetStopHandlingContext();
+  // The policy stack belongs to the host thread, and one host thread can
+  // handle stops of several processes: the debugger's event handler thread
+  // pulls the stop events of every process in the debugger. While it handles
+  // a stop of one process, its view is HandlingStop even when an action calls
+  // into another process. So the view alone isn't enough: return this
+  // process's context only if this thread opened it. Otherwise this process's
+  // public state and run lock come from its PrivateStateThread, as for any
+  // thread that isn't handling its stop.
+  if (context_sp && context_sp->m_owner == std::this_thread::get_id())

If I understand it correctly, I think this comment has the logic flipped:

The standard lldb driver program runs one Event Handling Thread that waits on all the Process Broadcasters. In that mode of using lldb, all the asynchronous DoOnRemoval calls happen on the same thread. So the thread managing events from different processes all have the same m_owner. This check wouldn't help anything, it would always pass. That's not a problem because in that scenario DoOnRemoval is always called ON the event handling thread which blocks that thread from fetching other process events - serializing the StopContext access.

I think this check would matter if I had the opposite use pattern, where there were several independent Event Handling Threads, one per process. Then you might be in the middle of running a DoOnRemoval on the EHT for process A on thread A, and Thread B might try to ask a question of process A. Thread B is not the one that pushed the StopHandling context, so it should see the old (running) state not the currently being handled state.

jimingham jimingham commented on code on Oct 29, 2026 21:54 UTC
Code Review
lldb/source/Target/Process.cpp:1
@@ -1335,6 +1335,98 @@ 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::GetStopHandlingContext() const {
+  std::lock_guard<std::mutex> guard(m_stop_handling_mutex);
+  return m_stop_handling_context_sp;
+}
+
+Process::StopHandlingContextSP
+Process::GetStopHandlingContextForCurrentThread() const {
+  if (PolicyStack::Get().Current().view != Policy::View::HandlingStop)
+    return nullptr;
+  StopHandlingContextSP context_sp = GetStopHandlingContext();
+  // The policy stack belongs to the host thread, and one host thread can
+  // handle stops of several processes: the debugger's event handler thread
+  // pulls the stop events of every process in the debugger. While it handles
+  // a stop of one process, its view is HandlingStop even when an action calls
+  // into another process. So the view alone isn't enough: return this
+  // process's context only if this thread opened it. Otherwise this process's
+  // public state and run lock come from its PrivateStateThread, as for any
+  // thread that isn't handling its stop.
+  if (context_sp && context_sp->m_owner == std::this_thread::get_id())
+    return context_sp;
+  return nullptr;
+}
+
+bool Process::IsHandlingStopOnOtherThread() const {
+  StopHandlingContextSP context_sp = GetStopHandlingContext();
+  return context_sp && 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())),
+      m_policy_guard(PolicyStack::Get().PushHandlingStop()) {
+  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);
+}
+
+Process::StopHandlingScope::~StopHandlingScope() {
+  std::lock_guard<std::mutex> guard(m_process.m_stop_handling_mutex);
+  // The slot only holds another thread's context if two threads pull this

I don't understand when this would happen. When would "two threads pull this process's events from its primary listener"? Do you mean you have two threads each of which is calling "WaitForEvent" on the SAME listener. That seems to me clearly racy and not something we are interested in supporting. If we don't explicitly disallow it currently, we should. You can multiplex by having multiple Listeners for the same Broadcaster, but running concurrent WaitForEvent's on the same Listener seems wrong.

Is there a scenario that motivated this comment?

jimingham jimingham commented on code on Oct 29, 2026 21:59 UTC
Code Review
lldb/source/Target/Process.cpp:1
@@ -3643,6 +3728,13 @@ Status Process::PrivateResume() {
 }
 
 Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
+  // The process is already stopped: the stop isn't public yet only because

Someone said Halt while a stop callback was being run. Since an expression being run might spin forever, Halt needs to be able to interrupt that. I don't think it's right for the Process to just give up here.

BTW, since you return an error here, I don't think you need to check IsHandlingStopOnOtherThread in CommandInterpreter above. Either handle the failure to Halt directly, and/or have Halt actually effect a halt where it's appropriate.

jimingham jimingham commented on code on Oct 29, 2026 22:03 UTC
Code Review
lldb/source/Target/Process.cpp:1
@@ -3885,12 +3981,14 @@ Status Process::DestroyImpl(bool force_kill) {
       error = StopForDestroyOrDetach(exit_event_sp);
     }
 
-    if (GetPublicState() == eStateStopped) {
+    if (GetPublicState() == eStateStopped || IsHandlingStopOnOtherThread()) {

This seems racy. If you don't interrupt or wait till the stop handling on another thread is done, you could have called "DiscardThreadPlans" and then the stop handling callback could push another plan, or set another breakpoint or call break enable after you said DisableAllBreakpoints.

I think you need to work out a way to interrupt the Callback, or to wait on its completion.

Reviewers
Assignees
medismailben medismailben
Labels
risk: low confidence: 87.7% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 64.6% (MEDIUM) · Higher = larger blast radius
64.6%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 87.7% · Lower = rushed or shallow review
87.7%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 8.0% · Safe to merge
8.0%