[Lldb-commits] [lldb] [lldb-dap] Make lldb-dap attach with waitFor cancellable (PR #233709)
Nathan Fusselman via lldb-commits
lldb-commits at lists.llvm.org
Mon Oct 19 23:31:59 PDT 2026
https://github.com/nathanfusselman updated https://github.com/llvm/llvm-project/pull/233709
>From 8908781fe345b11667964994670acfcfc5f2f47d Mon Sep 17 00:00:00 2001
From: Nathan Fusselman <nfusselman at apple.com>
Date: Fri, 16 Oct 2026 18:03:27 -0700
Subject: [PATCH] [lldb-dap] Make lldb-dap attach with waitFor cancellable
A waitFor attach blocked until the target launched, and neither a DAP
cancel nor a disconnect could end it. Interrupt the wait on cancel,
disconnect and a closed connection, and make Disconnect() wake a
blocked socket read.
rdar://190257377
---
.../posix/ConnectionFileDescriptorPosix.cpp | 1 +
lldb/source/Target/Target.cpp | 25 ++++++++++++---
.../tools/lldb-dap/attach/TestDAP_attach.py | 29 +++++++++++++++++
.../tools/lldb-dap/cancel/TestDAP_cancel.py | 5 +--
lldb/tools/lldb-dap/DAP.cpp | 30 ++++++++++++++----
lldb/tools/lldb-dap/DAP.h | 7 ++++-
.../Host/ConnectionFileDescriptorTest.cpp | 31 ++++++++++++++++++-
7 files changed, 112 insertions(+), 16 deletions(-)
diff --git a/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp b/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp
index e65a67fe1bd15..2099cb528e19f 100644
--- a/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp
+++ b/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp
@@ -77,6 +77,7 @@ ConnectionFileDescriptor::ConnectionFileDescriptor(
: m_shutting_down(false) {
m_uri = socket_up->GetRemoteConnectionURI();
m_io_sp = std::move(socket_up);
+ OpenCommandPipe();
}
ConnectionFileDescriptor::~ConnectionFileDescriptor() {
diff --git a/lldb/source/Target/Target.cpp b/lldb/source/Target/Target.cpp
index 1b4e2a207a476..eb03726ec06e8 100644
--- a/lldb/source/Target/Target.cpp
+++ b/lldb/source/Target/Target.cpp
@@ -3881,9 +3881,24 @@ Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
process_sp->RestoreProcessEvents();
} else {
// We are stopping all the way out to the user, so update selected frames.
- state = process_sp->WaitForProcessToStop(
- std::nullopt, nullptr, false, attach_info.GetHijackListener(), stream,
- true, SelectMostRelevantFrame);
+ // Wait in slices so a debugger interrupt can end an attach that is
+ // still waiting for a process to launch.
+ constexpr std::chrono::milliseconds interrupt_poll_interval(100);
+ bool interrupted = false;
+ bool process_interrupted = false;
+ do {
+ EventSP event_sp;
+ state = process_sp->WaitForProcessToStop(
+ interrupt_poll_interval, &event_sp, false,
+ attach_info.GetHijackListener(), stream, true,
+ SelectMostRelevantFrame);
+ if (state == eStateInvalid) {
+ process_interrupted = event_sp && event_sp->GetType() ==
+ Process::eBroadcastBitInterrupt;
+ interrupted =
+ !process_interrupted && GetDebugger().InterruptRequested();
+ }
+ } while (state == eStateInvalid && !process_interrupted && !interrupted);
process_sp->RestoreProcessEvents();
// Run the stop hooks here. Since we were hijacking the events, they
@@ -3892,7 +3907,9 @@ Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
if (state != eStateStopped) {
const char *exit_desc = process_sp->GetExitDescription();
- if (exit_desc)
+ if (interrupted)
+ error = Status::FromErrorString("attach was interrupted");
+ else if (exit_desc)
error = Status::FromErrorStringWithFormat("%s", exit_desc);
else
error = Status::FromErrorString(
diff --git a/lldb/test/API/tools/lldb-dap/attach/TestDAP_attach.py b/lldb/test/API/tools/lldb-dap/attach/TestDAP_attach.py
index 6f7190828b95c..58950648e2588 100644
--- a/lldb/test/API/tools/lldb-dap/attach/TestDAP_attach.py
+++ b/lldb/test/API/tools/lldb-dap/attach/TestDAP_attach.py
@@ -11,6 +11,7 @@
from lldbsuite.test.tools.lldb_dap import DAPTestCaseBase
from lldbsuite.test.tools.lldb_dap.types import (
AttachArgs,
+ CancelArgs,
ProcessEvent,
ProgressStartEvent,
)
@@ -119,6 +120,34 @@ def do_attach_waitFor(self, use_basename: bool):
self.assertEqual(process_event.body.systemProcessId, proc.pid)
self.verify_pid(proc)
+ @expectedFailureWindows
+ @skipIfWindowsAndLLDBServer
+ def test_waitFor_cancel(self):
+ """
+ Tests that a cancel request ends an attach that is still waiting for
+ the process to launch.
+ """
+ session = self.create_session(disconnect_automatically=False)
+ program = self.build_for_attach()
+
+ init_response = session.initialize_sequence(session.initialize_args)
+ pending = session.send_request(AttachArgs(program=program, waitFor=True))
+ session.wait_for_event(
+ ProgressStartEvent,
+ until=lambda e: "Waiting to attach" in e.body.title,
+ after=init_response,
+ timeout_msg="Waiting for attach progress event.",
+ )
+
+ session.send_request(CancelArgs(requestId=pending.seq)).result()
+ # `initialized` is only sent once the attach request stopped waiting.
+ session.ensure_initialized()
+
+ session.disconnect()
+ response = pending.error("expects attach response.")
+ assert response.body is not None and response.body.error is not None
+ self.assertEqual(response.body.error.format, "attach was interrupted")
+
def test_attach_with_missing_session_debugger(self):
"""
Test that attaching with only one of debuggerId/targetId specified
diff --git a/lldb/test/API/tools/lldb-dap/cancel/TestDAP_cancel.py b/lldb/test/API/tools/lldb-dap/cancel/TestDAP_cancel.py
index 7dbc5c095f545..f0a0105b90343 100644
--- a/lldb/test/API/tools/lldb-dap/cancel/TestDAP_cancel.py
+++ b/lldb/test/API/tools/lldb-dap/cancel/TestDAP_cancel.py
@@ -110,13 +110,10 @@ def test_request_after_disconnect(self):
session.verify_stopped_on_entry(after=process_event)
# Block the request handling thread, so both requests are queued.
- blocking_handle = self.async_blocking_request(session, count=1)
+ self.async_blocking_request(session, count=1)
disconnect_handle = session.send_request(DisconnectArgs(terminateDebuggee=True))
threads_handle = session.send_request(ThreadsArgs())
- blocking_resp = blocking_handle.result()
- self.assertEqual(blocking_resp.success, True)
-
threads_resp = threads_handle.error()
self.assertEqual(threads_resp.request_seq, threads_handle.seq)
self.assertEqual(threads_resp.message, "cancelled")
diff --git a/lldb/tools/lldb-dap/DAP.cpp b/lldb/tools/lldb-dap/DAP.cpp
index 5a816ec4ccbb9..947b3208efae6 100644
--- a/lldb/tools/lldb-dap/DAP.cpp
+++ b/lldb/tools/lldb-dap/DAP.cpp
@@ -698,6 +698,7 @@ bool DAP::HandleObject(const Message &M) {
{
std::lock_guard<std::mutex> guard(m_active_request_mutex);
m_active_request = req;
+ m_active_request_interrupted = false;
// Clear the interrupt request prior to invoking a handler.
if (debugger.InterruptRequested())
@@ -707,6 +708,7 @@ bool DAP::HandleObject(const Message &M) {
llvm::scope_exit cleanup([&]() {
std::scoped_lock<std::mutex> active_request_lock(m_active_request_mutex);
m_active_request = nullptr;
+ m_active_request_interrupted = false;
});
auto handler_pos = request_handlers.find(req->command);
@@ -787,6 +789,7 @@ void DAP::SendTerminatedEvent() {
llvm::Error DAP::Disconnect() { return Disconnect(!is_attach); }
llvm::Error DAP::Disconnect(bool terminateDebuggee) {
+ InterruptActiveRequest();
// Serializes with the request handlers, and with a call from
// `DAPSessionManager::DisconnectAllSessions()` on another thread.
lldb::SBMutex api_mutex = GetAPIMutex();
@@ -857,7 +860,25 @@ void DAP::Received(const protocol::Event &event) {
// no-op, no supported events from the client to the server as of DAP v1.68.
}
+void DAP::InterruptActiveRequest(std::optional<protocol::Id> seq) {
+ std::lock_guard<std::mutex> guard(m_active_request_mutex);
+ if (!m_active_request || m_active_request_interrupted)
+ return;
+ if (seq && *seq != m_active_request->seq)
+ return;
+
+ DAP_LOG(log, "interrupting inflight request (command={0} seq={1})",
+ m_active_request->command, m_active_request->seq);
+ m_active_request_interrupted = true;
+ debugger.RequestInterrupt();
+}
+
void DAP::Received(const protocol::Request &request) {
+ // A disconnect must not wait behind a request that can block indefinitely,
+ // such as a waitFor attach.
+ if (request.command == "disconnect")
+ InterruptActiveRequest();
+
const std::optional<CancelArguments> cancel_args =
getArgumentsIfRequest<CancelArguments>(request, "cancel");
if (cancel_args) {
@@ -869,12 +890,7 @@ void DAP::Received(const protocol::Request &request) {
// If a cancel is requested for the active request, make a best
// effort attempt to interrupt.
- std::lock_guard<std::mutex> guard(m_active_request_mutex);
- if (m_active_request && cancel_args->requestId == m_active_request->seq) {
- DAP_LOG(log, "interrupting inflight request (command={0} seq={1})",
- m_active_request->command, m_active_request->seq);
- debugger.RequestInterrupt();
- }
+ InterruptActiveRequest(cancel_args->requestId);
}
std::lock_guard<std::mutex> guard(m_queue_mutex);
@@ -893,11 +909,13 @@ void DAP::Received(const protocol::Response &response) {
void DAP::OnError(llvm::Error error) {
DAP_LOG_ERROR(log, std::move(error), "transport error: {0}");
+ InterruptActiveRequest();
TerminateLoop(/*failed=*/true);
}
void DAP::OnClosed() {
DAP_LOG(log, "transport closed");
+ InterruptActiveRequest();
TerminateLoop();
}
diff --git a/lldb/tools/lldb-dap/DAP.h b/lldb/tools/lldb-dap/DAP.h
index f084929a5850b..75d3a81e0edcb 100644
--- a/lldb/tools/lldb-dap/DAP.h
+++ b/lldb/tools/lldb-dap/DAP.h
@@ -472,6 +472,10 @@ struct DAP final : public DAPTransport::MessageHandler {
void TransportHandler();
void TerminateLoop(bool failed = false);
+ /// Interrupts the debugger for the request being handled, at most once per
+ /// request. With `seq`, only if that is the request being handled.
+ void InterruptActiveRequest(std::optional<protocol::Id> seq = std::nullopt);
+
/// What `Loop()` does with the queued messages. It only moves forward.
enum class QueueState {
Running,
@@ -529,7 +533,8 @@ struct DAP final : public DAPTransport::MessageHandler {
llvm::SmallSet<int64_t, 4> m_cancelled_requests;
std::mutex m_active_request_mutex;
- const protocol::Request *m_active_request;
+ const protocol::Request *m_active_request = nullptr;
+ bool m_active_request_interrupted = false;
llvm::StringMap<SourceBreakpointMap> m_source_breakpoints;
llvm::DenseMap<src_ref_t, SourceBreakpointMap> m_source_assembly_breakpoints;
diff --git a/lldb/unittests/Host/ConnectionFileDescriptorTest.cpp b/lldb/unittests/Host/ConnectionFileDescriptorTest.cpp
index 171481acca01b..4d437c11a3b48 100644
--- a/lldb/unittests/Host/ConnectionFileDescriptorTest.cpp
+++ b/lldb/unittests/Host/ConnectionFileDescriptorTest.cpp
@@ -7,11 +7,13 @@
//===----------------------------------------------------------------------===//
#include "TestingSupport/Host/SocketTestUtilities.h"
-#include "gtest/gtest.h"
#include "TestingSupport/SubsystemRAII.h"
#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
#include "lldb/Utility/UriParser.h"
+#include "gtest/gtest.h"
+#include <thread>
+using namespace lldb;
using namespace lldb_private;
class ConnectionFileDescriptorTest : public testing::Test {
@@ -42,3 +44,30 @@ TEST_F(ConnectionFileDescriptorTest, TCPGetURIv6) {
return;
TestGetURI("::1");
}
+
+TEST_F(ConnectionFileDescriptorTest, DisconnectWakesBlockedRead) {
+ auto pair = llvm::cantFail(Socket::CreatePair());
+ ConnectionFileDescriptor connection(std::move(pair.first));
+
+ char byte;
+ Status error;
+ ConnectionStatus status = eConnectionStatusSuccess;
+ std::thread reader([&] {
+ Status read_error;
+ // Only failing to take the connection lock reports a timeout.
+ do
+ connection.Read(&byte, 1, std::nullopt, status, &read_error);
+ while (status == eConnectionStatusTimedOut);
+ });
+
+ // The lock is only unavailable while the reader is blocked holding it.
+ ConnectionStatus probe_status;
+ char probe_byte;
+ while (!llvm::StringRef(error.AsCString()).contains("connection lock"))
+ connection.Read(&probe_byte, 1, std::chrono::microseconds(0), probe_status,
+ &error);
+
+ connection.Disconnect(nullptr);
+ reader.join();
+ EXPECT_EQ(eConnectionStatusEndOfFile, status);
+}
More information about the lldb-commits
mailing list