Skip to content

Commit aab48c9

Browse files
authored
[lldb] Detect a Darwin kernel issue and work around it (#81573)
On arm64 machines, when there is a hardware breakpoint or watchpoint set, and lldb has instruction-stepped a thread, and then done a Process::Resume, we will sometimes receive an extra "instruction step completed" mach exception and the pc has not advanced. From a user's perspective, they hit Continue and lldb stops again at the same spot. From the testsuite's perspective, this has been a constant source of testsuite failures for any test using hardware watchpoints and breakpoints, the arm64 CI bots seem especially good at hitting this issue. Jim and I have been slowly looking at this for a few months now, and finally I decided to try to detect this situation in lldb and silently resume the process again when it happens. We were already detecting this "got an insn-step finished mach exception but this thread was not instruction stepping" combination in StopInfoMachException where we take the mach exception and create a StopInfo object for it. We had a lot of logging we used to understand the failure as it was hit on the bots in assert builds. This patch adds a new case to `Thread::GetPrivateStopInfo()` to call the StopInfo's (new) `IsContinueInterrupted()` method. In StopInfoMachException, where we previously had logging for assert builds, I now note it in an ivar, and when `Thread::GetPrivateStopInfo()` asks if this has happened, we check all of the combination of events that this comes up: We have a hardware breakpoint or watchpoint, we were not instruction stepping this thread but got an insn-step mach exception, the pc is the same as the previous stop's pc. And in that case, `Thread::GetPrivateStopInfo()` returns no StopInfo -- indicating that this thread would like to resume execution. The `Thread` object has two StackFrameLists, `m_curr_frames_sp` and `m_prev_frames_sp`. When a thread resumes execution, we move `m_curr_frames_sp` in to `m_prev_frames_sp` and when it stops executing, w euse `m_prev_frames_sp` to seed the new `m_curr_frames_sp` if most of the stack is the same as before. In this same location, I now save the Thread's RegisterContext::GetPC into an ivar, `m_prev_framezero_pc`. StopInfoMachException needs this information to check all of the conditions I outlined above for `IsContinueInterrupted`. This has passed exhaustive testing and we do not have any testsuite failures for hardware watchpoints and breakpoints due to this kernel bug with the patch in place. In focusing on these tests for thousands of runs, I have found two other uncommon race conditions for the TestConcurrent* tests on arm64. TestConcurrentManyBreakpoints.py (which uses no hardware watchpoint/breakpoints) will sometimes only have 99 breakpoints when it expects 100, and any of the concurrent tests using the shared harness (I've seen it in TestConcurrentWatchBreakDelay.py, TestConcurrentTwoBreakpointsOneSignal.py, TestConcurrentSignalDelayWatch.py) can fail when the test harness checks that there is only one thread still running at the end, and it finds two -- one of them under pthread_exit / pthread_terminate. Both of these failures happen on github main without my changes, and with my changes - they are unrelated race conditions in these tests, and I'm sure I'll be looking into them at some point if they hit the CI bots with frequency. On my computer, these are in the 0.3-0.5% of the time class. But the CI bots do have different timing.
1 parent f3b92fa commit aab48c9

File tree

5 files changed

+101
-31
lines changed

5 files changed

+101
-31
lines changed

lldb/include/lldb/Target/StopInfo.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,11 @@ class StopInfo : public std::enable_shared_from_this<StopInfo> {
7979

8080
virtual bool IsValidForOperatingSystemThread(Thread &thread) { return true; }
8181

82+
/// A Continue operation can result in a false stop event
83+
/// before any execution has happened. We need to detect this
84+
/// and silently continue again one more time.
85+
virtual bool WasContinueInterrupted(Thread &thread) { return false; }
86+
8287
// Sometimes the thread plan logic will know that it wants a given stop to
8388
// stop or not, regardless of what the ordinary logic for that StopInfo would
8489
// dictate. The main example of this is the ThreadPlanCallFunction, which

lldb/include/lldb/Target/Thread.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
#include <memory>
1313
#include <mutex>
14+
#include <optional>
1415
#include <string>
1516
#include <vector>
1617

@@ -1226,6 +1227,16 @@ class Thread : public std::enable_shared_from_this<Thread>,
12261227

12271228
lldb::ValueObjectSP GetSiginfoValue();
12281229

1230+
/// Request the pc value the thread had when previously stopped.
1231+
///
1232+
/// When the thread performs execution, it copies the current RegisterContext
1233+
/// GetPC() value. This method returns that value, if it is available.
1234+
///
1235+
/// \return
1236+
/// The PC value before execution was resumed. May not be available;
1237+
/// an empty std::optional is returned in that case.
1238+
std::optional<lldb::addr_t> GetPreviousFrameZeroPC();
1239+
12291240
protected:
12301241
friend class ThreadPlan;
12311242
friend class ThreadList;
@@ -1306,6 +1317,9 @@ class Thread : public std::enable_shared_from_this<Thread>,
13061317
///populated after a thread stops.
13071318
lldb::StackFrameListSP m_prev_frames_sp; ///< The previous stack frames from
13081319
///the last time this thread stopped.
1320+
std::optional<lldb::addr_t>
1321+
m_prev_framezero_pc; ///< Frame 0's PC the last
1322+
/// time this thread was stopped.
13091323
int m_resume_signal; ///< The signal that should be used when continuing this
13101324
///thread.
13111325
lldb::StateType m_resume_state; ///< This state is used to force a thread to

lldb/source/Plugins/Process/Utility/StopInfoMachException.cpp

Lines changed: 57 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
#include "lldb/Target/Thread.h"
2727
#include "lldb/Target/ThreadPlan.h"
2828
#include "lldb/Target/UnixSignals.h"
29+
#include "lldb/Utility/LLDBLog.h"
30+
#include "lldb/Utility/Log.h"
2931
#include "lldb/Utility/StreamString.h"
3032
#include <optional>
3133

@@ -596,6 +598,7 @@ StopInfoSP StopInfoMachException::CreateStopReasonWithMachException(
596598
if (exc_type == 0)
597599
return StopInfoSP();
598600

601+
bool not_stepping_but_got_singlestep_exception = false;
599602
uint32_t pc_decrement = 0;
600603
ExecutionContext exe_ctx(thread.shared_from_this());
601604
Target *target = exe_ctx.GetTargetPtr();
@@ -720,30 +723,8 @@ StopInfoSP StopInfoMachException::CreateStopReasonWithMachException(
720723
// is set
721724
is_actual_breakpoint = true;
722725
is_trace_if_actual_breakpoint_missing = true;
723-
#ifndef NDEBUG
724-
if (thread.GetTemporaryResumeState() != eStateStepping) {
725-
StreamString s;
726-
s.Printf("CreateStopReasonWithMachException got EXC_BREAKPOINT [1,0] "
727-
"indicating trace event, but thread is not tracing, it has "
728-
"ResumeState %d",
729-
thread.GetTemporaryResumeState());
730-
if (RegisterContextSP regctx = thread.GetRegisterContext()) {
731-
if (const RegisterInfo *ri = regctx->GetRegisterInfoByName("esr")) {
732-
uint32_t esr =
733-
(uint32_t)regctx->ReadRegisterAsUnsigned(ri, UINT32_MAX);
734-
if (esr != UINT32_MAX) {
735-
s.Printf(" esr value: 0x%" PRIx32, esr);
736-
}
737-
}
738-
}
739-
thread.GetProcess()->DumpPluginHistory(s);
740-
llvm::report_fatal_error(s.GetData());
741-
lldbassert(
742-
false &&
743-
"CreateStopReasonWithMachException got EXC_BREAKPOINT [1,0] "
744-
"indicating trace event, but thread was not doing a step.");
745-
}
746-
#endif
726+
if (thread.GetTemporaryResumeState() != eStateStepping)
727+
not_stepping_but_got_singlestep_exception = true;
747728
}
748729
if (exc_code == 0x102) // EXC_ARM_DA_DEBUG
749730
{
@@ -825,6 +806,56 @@ StopInfoSP StopInfoMachException::CreateStopReasonWithMachException(
825806
break;
826807
}
827808

828-
return StopInfoSP(new StopInfoMachException(thread, exc_type, exc_data_count,
829-
exc_code, exc_sub_code));
809+
return std::make_shared<StopInfoMachException>(
810+
thread, exc_type, exc_data_count, exc_code, exc_sub_code,
811+
not_stepping_but_got_singlestep_exception);
812+
}
813+
814+
// Detect an unusual situation on Darwin where:
815+
//
816+
// 0. We did an instruction-step before this.
817+
// 1. We have a hardware breakpoint or watchpoint set.
818+
// 2. We resumed the process, but not with an instruction-step.
819+
// 3. The thread gets an "instruction-step completed" mach exception.
820+
// 4. The pc has not advanced - it is the same as before.
821+
//
822+
// This method returns true for that combination of events.
823+
bool StopInfoMachException::WasContinueInterrupted(Thread &thread) {
824+
Log *log = GetLog(LLDBLog::Step);
825+
826+
// We got an instruction-step completed mach exception but we were not
827+
// doing an instruction step on this thread.
828+
if (!m_not_stepping_but_got_singlestep_exception)
829+
return false;
830+
831+
RegisterContextSP reg_ctx_sp(thread.GetRegisterContext());
832+
std::optional<addr_t> prev_pc = thread.GetPreviousFrameZeroPC();
833+
if (!reg_ctx_sp || !prev_pc)
834+
return false;
835+
836+
// The previous pc value and current pc value are the same.
837+
if (*prev_pc != reg_ctx_sp->GetPC())
838+
return false;
839+
840+
// We have a watchpoint -- this is the kernel bug.
841+
ProcessSP process_sp = thread.GetProcess();
842+
if (process_sp->GetWatchpointResourceList().GetSize()) {
843+
LLDB_LOGF(log,
844+
"Thread stopped with insn-step completed mach exception but "
845+
"thread was not stepping; there is a hardware watchpoint set.");
846+
return true;
847+
}
848+
849+
// We have a hardware breakpoint -- this is the kernel bug.
850+
auto &bp_site_list = process_sp->GetBreakpointSiteList();
851+
for (auto &site : bp_site_list.Sites()) {
852+
if (site->IsHardware() && site->IsEnabled()) {
853+
LLDB_LOGF(log,
854+
"Thread stopped with insn-step completed mach exception but "
855+
"thread was not stepping; there is a hardware breakpoint set.");
856+
return true;
857+
}
858+
}
859+
860+
return false;
830861
}

lldb/source/Plugins/Process/Utility/StopInfoMachException.h

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,12 @@ class StopInfoMachException : public StopInfo {
3131
// Constructors and Destructors
3232
StopInfoMachException(Thread &thread, uint32_t exc_type,
3333
uint32_t exc_data_count, uint64_t exc_code,
34-
uint64_t exc_subcode)
34+
uint64_t exc_subcode,
35+
bool not_stepping_but_got_singlestep_exception)
3536
: StopInfo(thread, exc_type), m_exc_data_count(exc_data_count),
36-
m_exc_code(exc_code), m_exc_subcode(exc_subcode) {}
37+
m_exc_code(exc_code), m_exc_subcode(exc_subcode),
38+
m_not_stepping_but_got_singlestep_exception(
39+
not_stepping_but_got_singlestep_exception) {}
3740

3841
~StopInfoMachException() override = default;
3942

@@ -58,10 +61,14 @@ class StopInfoMachException : public StopInfo {
5861
uint64_t exc_code, uint64_t exc_sub_code, uint64_t exc_sub_sub_code,
5962
bool pc_already_adjusted = true, bool adjust_pc_if_needed = false);
6063

64+
bool WasContinueInterrupted(Thread &thread) override;
65+
6166
protected:
6267
uint32_t m_exc_data_count;
6368
uint64_t m_exc_code;
6469
uint64_t m_exc_subcode;
70+
71+
bool m_not_stepping_but_got_singlestep_exception;
6572
};
6673

6774
} // namespace lldb_private

lldb/source/Target/Thread.cpp

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ Thread::Thread(Process &process, lldb::tid_t tid, bool use_invalid_index_id)
221221
: process.GetNextThreadIndexID(tid)),
222222
m_reg_context_sp(), m_state(eStateUnloaded), m_state_mutex(),
223223
m_frame_mutex(), m_curr_frames_sp(), m_prev_frames_sp(),
224-
m_resume_signal(LLDB_INVALID_SIGNAL_NUMBER),
224+
m_prev_framezero_pc(), m_resume_signal(LLDB_INVALID_SIGNAL_NUMBER),
225225
m_resume_state(eStateRunning), m_temporary_resume_state(eStateRunning),
226226
m_unwinder_up(), m_destroy_called(false),
227227
m_override_should_notify(eLazyBoolCalculate),
@@ -250,6 +250,7 @@ void Thread::DestroyThread() {
250250
std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
251251
m_curr_frames_sp.reset();
252252
m_prev_frames_sp.reset();
253+
m_prev_framezero_pc.reset();
253254
}
254255

255256
void Thread::BroadcastSelectedFrameChange(StackID &new_frame_id) {
@@ -422,6 +423,12 @@ lldb::StopInfoSP Thread::GetPrivateStopInfo(bool calculate) {
422423
}
423424
}
424425
}
426+
427+
// If we were resuming the process and it was interrupted,
428+
// return no stop reason. This thread would like to resume.
429+
if (m_stop_info_sp && m_stop_info_sp->WasContinueInterrupted(*this))
430+
return {};
431+
425432
return m_stop_info_sp;
426433
}
427434

@@ -1408,16 +1415,22 @@ StackFrameListSP Thread::GetStackFrameList() {
14081415
return m_curr_frames_sp;
14091416
}
14101417

1418+
std::optional<addr_t> Thread::GetPreviousFrameZeroPC() {
1419+
return m_prev_framezero_pc;
1420+
}
1421+
14111422
void Thread::ClearStackFrames() {
14121423
std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
14131424

14141425
GetUnwinder().Clear();
1426+
m_prev_framezero_pc.reset();
1427+
if (RegisterContextSP reg_ctx_sp = GetRegisterContext())
1428+
m_prev_framezero_pc = reg_ctx_sp->GetPC();
14151429

14161430
// Only store away the old "reference" StackFrameList if we got all its
14171431
// frames:
14181432
// FIXME: At some point we can try to splice in the frames we have fetched
1419-
// into
1420-
// the new frame as we make it, but let's not try that now.
1433+
// into the new frame as we make it, but let's not try that now.
14211434
if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched())
14221435
m_prev_frames_sp.swap(m_curr_frames_sp);
14231436
m_curr_frames_sp.reset();

0 commit comments

Comments
 (0)