[lldb] Avoid repeated interrupts for multi-site breakpoint updates #246807
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-lldb
Author: Igor Kudrin (igorkudrin)
<details>
<summary>Changes</summary>
Creating, enabling, or disabling a breakpoint with multiple sites while a remote inferior is running can interrupt and resume the inferior once per site.
Hold the remote transport lock across the operation so LLDB can send the individual breakpoint packets during a single interruption.
Before the patch:
(lldb) platform select remote-linux
(lldb) platform connect connect://127.0.0.1:1234
(lldb) file sample
(lldb) run
(lldb) br add name test
Breakpoint 1: 100 locations.
(lldb) stat dump
"totalBreakpointResolveTime": 9.633445,
After the patch:
(lldb) stat dump
"totalBreakpointResolveTime": 0.12673299999999998,
Assisted-by: Codex
---
Full diff: https://github.com/llvm/llvm-project/pull/246807.diff
6 Files Affected:
````````````diff --git a/lldb/include/lldb/Target/Process.h b/lldb/include/lldb/Target/Process.h
index 3652d7400bb32f..75868b7f163301 100644
--- a/lldb/include/lldb/Target/Process.h
+++ b/lldb/include/lldb/Target/Process.h
@@ -2306,6 +2306,15 @@ class Process : public std::enable_shared_from_this<Process>,
UpdateBreakpointSites(const BreakpointSiteToActionMap &site_to_action);
public:
+ using BreakpointUpdateGuard = std::shared_ptr<void>;
+
+ /// Interrupt the inferior and return a guard that lets it resume when the
+ /// last reference is released. Use it to send multiple breakpoint update
+ /// requests during one interruption. Release the last reference on the thread
+ // that acquired the guard.
+ /// Returns an empty guard if batching is unnecessary or unsupported.
+ virtual BreakpointUpdateGuard HoldForBreakpointUpdates() { return {}; }
+
/// Performs `action` on `site`. If `forbid_delay` is true, the action is
/// performed immediately, otherwise the method will delay the breakpoint if
/// it is correct to do so.
diff --git a/lldb/source/Breakpoint/Breakpoint.cpp b/lldb/source/Breakpoint/Breakpoint.cpp
index 3e24eb7484679d..ea35d2cc879a47 100644
--- a/lldb/source/Breakpoint/Breakpoint.cpp
+++ b/lldb/source/Breakpoint/Breakpoint.cpp
@@ -369,6 +369,10 @@ void Breakpoint::SetEnabled(bool enable) {
return;
m_options.SetEnabled(enable);
+ ProcessSP process = m_target.GetProcessSP();
+ Process::BreakpointUpdateGuard guard =
+ process && m_locations.GetSize() > 1 ? process->HoldForBreakpointUpdates()
+ : nullptr;
if (enable)
m_locations.ResolveAllBreakpointSites();
else
@@ -517,6 +521,14 @@ const BreakpointOptions &Breakpoint::GetOptions() const { return m_options; }
void Breakpoint::ResolveBreakpoint() {
if (m_resolver_sp) {
ElapsedTime elapsed(m_resolve_time);
+ ProcessSP process = m_target.GetProcessSP();
+ const bool may_resolve_multiple_locations =
+ m_resolver_sp->GetResolverTy() !=
+ BreakpointResolver::ResolverTy::AddressResolver;
+ Process::BreakpointUpdateGuard guard =
+ process && may_resolve_multiple_locations
+ ? process->HoldForBreakpointUpdates()
+ : nullptr;
m_resolver_sp->ResolveBreakpoint(*m_filter_sp);
}
}
diff --git a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
index 98a474e172d88c..a63fce79b528bb 100644
--- a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
+++ b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
@@ -3705,6 +3705,24 @@ llvm::Error ProcessGDBRemote::DoDisableBreakpointSite(BreakpointSite &bp_site) {
return llvm::Error::success();
}
+Process::BreakpointUpdateGuard ProcessGDBRemote::HoldForBreakpointUpdates() {
+ if (!StateIsRunningState(GetPrivateState()))
+ return {};
+
+ struct Guard {
+ Guard(ProcessGDBRemote &remote)
+ : process(remote.shared_from_this()),
+ lock(remote.m_gdb_comm, remote.GetInterruptTimeout()) {}
+
+ // The lock references the process's transport. Keep it alive until the
+ // lock is destroyed.
+ ProcessSP process;
+ GDBRemoteClientBase::Lock lock;
+ };
+
+ return std::make_shared<Guard>(*this);
+}
+
Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
assert(bp_site != nullptr);
diff --git a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h
index 74a87ed2443820..67cef163f6e467 100644
--- a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h
+++ b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h
@@ -176,6 +176,8 @@ class ProcessGDBRemote : public Process,
size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) override;
// Process Breakpoints
+ BreakpointUpdateGuard HoldForBreakpointUpdates() override;
+
Status EnableBreakpointSite(BreakpointSite *bp_site) override;
llvm::Error UpdateBreakpointSites(
diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestBreakpointUpdateInterrupt.py b/lldb/test/API/functionalities/gdb_remote_client/TestBreakpointUpdateInterrupt.py
new file mode 100644
index 00000000000000..50b38a74c4f18b
--- /dev/null
+++ b/lldb/test/API/functionalities/gdb_remote_client/TestBreakpointUpdateInterrupt.py
@@ -0,0 +1,80 @@
+import threading
+
+import lldb
+from lldbsuite.test import lldbutil
+from lldbsuite.test.gdbclientutils import MockGDBServerResponder
+from lldbsuite.test.lldbgdbclient import GDBRemoteTestBase
+
+
+class TestBreakpointUpdateInterrupt(GDBRemoteTestBase):
+ class Responder(MockGDBServerResponder):
+ def __init__(self):
+ super().__init__()
+ self.resumes = threading.Semaphore(0)
+ self.packets = []
+
+ def qfThreadInfo(self):
+ return "m1"
+
+ def qC(self):
+ return "QC1"
+
+ def haltReason(self):
+ return "T05thread:1;"
+
+ def cont(self):
+ self.packets.append("continue")
+ self.resumes.release()
+ return self.RESPONSE_NONE
+
+ def interrupt(self):
+ self.packets.append("interrupt")
+ return "T02thread:1;"
+
+ def setBreakpoint(self, packet):
+ self.packets.append(packet)
+ return "OK"
+
+ def clearBreakpoint(self, packet):
+ self.packets.append(packet)
+ return "OK"
+
+ def check_operation(self, process, operation, action):
+ responder = self.server.responder
+ responder.packets.clear()
+ result = operation()
+ self.assertTrue(responder.resumes.acquire(timeout=5))
+ packets = responder.packets
+ self.assertEqual(packets[0], "interrupt")
+ self.assertEqual(packets[-1], "continue")
+ self.assertCountEqual(
+ packets[1:-1], [f"{action}0,1000,1", f"{action}0,1001,1"]
+ )
+ self.assertState(process.GetState(), lldb.eStateRunning)
+ return result
+
+ def test_multisite_breakpoint(self):
+ """Check that packets for multiple sites share one inferior interruption."""
+
+ responder = self.Responder()
+ self.server.responder = responder
+ self.runCmd("platform select remote-linux")
+ target = self.createTarget("multisite-breakpoint.yaml")
+ process = self.connect(target)
+ listener = self.dbg.GetListener()
+ lldbutil.expect_state_changes(self, listener, process, [lldb.eStateStopped])
+ self.assertSuccess(target.SetModuleLoadAddress(target.GetModuleAtIndex(0), 0))
+ self.dbg.SetAsync(True)
+ self.assertSuccess(process.Continue())
+ self.assertTrue(responder.resumes.acquire(timeout=5))
+ self.assertEqual(responder.packets, ["continue"])
+ lldbutil.expect_state_changes(self, listener, process, [lldb.eStateRunning])
+
+ breakpoint = self.check_operation(
+ process, lambda: target.BreakpointCreateByRegex("^site_"), "Z"
+ )
+ self.assertEqual(breakpoint.GetNumResolvedLocations(), 2)
+ self.check_operation(process, lambda: breakpoint.SetEnabled(False), "z")
+ self.assertEqual(breakpoint.GetNumResolvedLocations(), 0)
+ self.check_operation(process, lambda: breakpoint.SetEnabled(True), "Z")
+ self.assertEqual(breakpoint.GetNumResolvedLocations(), 2)
diff --git a/lldb/test/API/functionalities/gdb_remote_client/multisite-breakpoint.yaml b/lldb/test/API/functionalities/gdb_remote_client/multisite-breakpoint.yaml
new file mode 100644
index 00000000000000..ca74a75ac48251
--- /dev/null
+++ b/lldb/test/API/functionalities/gdb_remote_client/multisite-breakpoint.yaml
@@ -0,0 +1,25 @@
+--- !ELF
+FileHeader:
+ Class: ELFCLASS64
+ Data: ELFDATA2LSB
+ Type: ET_EXEC
+ Machine: EM_X86_64
+Sections:
+ - Name: .text
+ Type: SHT_PROGBITS
+ Flags: [ SHF_ALLOC, SHF_EXECINSTR ]
+ Address: 0x1000
+ Content: "c3c3"
+Symbols:
+ - Name: site_first
+ Type: STT_FUNC
+ Section: .text
+ Binding: STB_GLOBAL
+ Value: 0x1000
+ Size: 1
+ - Name: site_second
+ Type: STT_FUNC
+ Section: .text
+ Binding: STB_GLOBAL
+ Value: 0x1001
+ Size: 1
</details>
<!--LLVM CODE FORMAT COMMENT: {darker}-->
:white_check_mark: With the latest revision this PR passed the Python code formatter.
This functionality isn't breakpoint specific is it? This is just a "do a bunch of operations with the target stopped, then resume". Even if the first use is breakpoints, it's confusing to name it as though it were specific to them.
The idea looks fine. Just fix the function naming and this should be good.
I would hope that when talking to a stub that supports the multi-breakpoint packet, we send that instead. But the overhead of setting up the Guard to keep it stopped during the operation would be negligible in that case, so it's still worth doing this for stubs that don't support that packet (we invented it and it's fairly new...)
Renamed to InferiorInterruptGuard and InterruptInferior().
The idea looks fine. Just fix the function naming and this should be good.
Thanks for the review!
I would hope that when talking to a stub that supports the multi-breakpoint packet, we send that instead.
For running processes, unfortunately, no: Process::ExecuteBreakpointSiteAction() updates each site immediately rather than collecting actions for a delayed update.
But the overhead of setting up the Guard to keep it stopped during the operation would be negligible in that case, so it's still worth doing this for stubs that don't support that packet (we invented it and it's fairly new...)
Exactly; supporting old servers was one of the motivations to fix it in this way.
> I would hope that when talking to a stub that supports the multi-breakpoint packet, we send that instead.
> For running processes, unfortunately, no: Process::ExecuteBreakpointSiteAction() updates each site immediately rather than collecting actions for a delayed update.
It would be nice to look at the callers of that function again and determine whether it makes sense to have a ExecuteBreakpointSiteAction that takes a vector. (not for this PR)
LGTM
jimingham
igorkudrin
Creating, enabling, or disabling a breakpoint with multiple sites while a remote inferior is running interrupts and resumes the inferior once per site.
Hold the remote transport lock across the operation so LLDB can send the individual breakpoint packets during a single interruption.
Before the patch:
After the patch:
Assisted-by: Codex