[llvm] 5ab3375 - [lldb-dap] Add multi-session support with shared debugger instances (#163653)
via llvm-commits
llvm-commits at lists.llvm.org
Wed Nov 26 10:32:31 PST 2025
Author: Janet Yang
Date: 2025-11-26T10:32:25-08:00
New Revision: 5ab3375b2cf461ab02704d129a1f4d5ba1a1e275
URL: https://github.com/llvm/llvm-project/commit/5ab3375b2cf461ab02704d129a1f4d5ba1a1e275
DIFF: https://github.com/llvm/llvm-project/commit/5ab3375b2cf461ab02704d129a1f4d5ba1a1e275.diff
LOG: [lldb-dap] Add multi-session support with shared debugger instances (#163653)
## Summary:
This change introduces a `DAPSessionManager` to enable multiple DAP
sessions to share debugger instances when needed, for things like child
process debugging and some scripting hooks that create dynamically new
targets.
Changes include:
- Add `DAPSessionManager` singleton to track and coordinate all active DAP
sessions
- Support attaching to an existing target via its globally unique target
ID (targetId parameter)
- Share debugger instances across sessions when new targets are created
dynamically
- Refactor event thread management to allow sharing event threads
between sessions and move event thread and event thread handlers to `EventHelpers`
- Add `eBroadcastBitNewTargetCreated` event to notify when new targets are
created
- Extract session names from target creation events
- Defer debugger initialization from 'initialize' request to
'launch'/'attach' requests. The only time the debugger is used currently
in between its creation in `InitializeRequestHandler` and the `Launch`
or `Attach` requests is during the `TelemetryDispatcher` destruction
call at the end of the `DAP::HandleObject` call, so this is safe.
This enables scenarios when new targets are created dynamically so that
the debug adapter can automatically start a new debug session for the
spawned target while sharing the debugger instance.
## Tests:
The refactoring maintains backward compatibility. All existing DAP test
cases pass.
Also added a few basic unit tests for DAPSessionManager
```
>> ninja DAPTests
>> ./tools/lldb/unittests/DAP/DAPTests
>>./bin/llvm-lit -v ../llvm-project/lldb/test/API/tools/lldb-dap/
```
Added:
lldb/tools/lldb-dap/DAPSessionManager.cpp
lldb/tools/lldb-dap/DAPSessionManager.h
lldb/unittests/DAP/DAPSessionManagerTest.cpp
Modified:
lldb/include/lldb/API/SBTarget.h
lldb/include/lldb/Target/Target.h
lldb/packages/Python/lldbsuite/test/tools/lldb-dap/dap_server.py
lldb/source/API/SBTarget.cpp
lldb/source/Target/Target.cpp
lldb/test/API/tools/lldb-dap/attach/TestDAP_attach.py
lldb/test/API/tools/lldb-dap/startDebugging/TestDAP_startDebugging.py
lldb/tools/lldb-dap/CMakeLists.txt
lldb/tools/lldb-dap/DAP.cpp
lldb/tools/lldb-dap/DAP.h
lldb/tools/lldb-dap/DAPForward.h
lldb/tools/lldb-dap/EventHelper.cpp
lldb/tools/lldb-dap/EventHelper.h
lldb/tools/lldb-dap/Handler/AttachRequestHandler.cpp
lldb/tools/lldb-dap/Handler/InitializeRequestHandler.cpp
lldb/tools/lldb-dap/Handler/LaunchRequestHandler.cpp
lldb/tools/lldb-dap/Protocol/ProtocolRequests.cpp
lldb/tools/lldb-dap/Protocol/ProtocolRequests.h
lldb/tools/lldb-dap/package.json
lldb/tools/lldb-dap/tool/lldb-dap.cpp
lldb/unittests/DAP/CMakeLists.txt
llvm/utils/gn/secondary/lldb/tools/lldb-dap/BUILD.gn
Removed:
################################################################################
diff --git a/lldb/include/lldb/API/SBTarget.h b/lldb/include/lldb/API/SBTarget.h
index 379a0bb7e9513..d0b91ff4741fa 100644
--- a/lldb/include/lldb/API/SBTarget.h
+++ b/lldb/include/lldb/API/SBTarget.h
@@ -44,6 +44,7 @@ class LLDB_API SBTarget {
eBroadcastBitWatchpointChanged = (1 << 3),
eBroadcastBitSymbolsLoaded = (1 << 4),
eBroadcastBitSymbolsChanged = (1 << 5),
+ eBroadcastBitNewTargetCreated = (1 << 6),
};
// Constructors
@@ -64,6 +65,10 @@ class LLDB_API SBTarget {
static lldb::SBTarget GetTargetFromEvent(const lldb::SBEvent &event);
+ /// For eBroadcastBitNewTargetCreated events, returns the newly created
+ /// target. For other event types, returns an invalid SBTarget.
+ static lldb::SBTarget GetCreatedTargetFromEvent(const lldb::SBEvent &event);
+
static uint32_t GetNumModulesFromEvent(const lldb::SBEvent &event);
static lldb::SBModule GetModuleAtIndexFromEvent(const uint32_t idx,
@@ -365,6 +370,16 @@ class LLDB_API SBTarget {
/// LLDB_INVALID_GLOBALLY_UNIQUE_TARGET_ID if the target is invalid.
lldb::user_id_t GetGloballyUniqueID() const;
+ /// Get the target session name for this target.
+ ///
+ /// The target session name provides a meaningful name for IDEs or tools to
+ /// display to help the user identify the origin and purpose of the target.
+ ///
+ /// \return
+ /// The target session name for this target, or nullptr if the target is
+ /// invalid or has no target session name.
+ const char *GetTargetSessionName() const;
+
SBError SetLabel(const char *label);
/// Architecture opcode byte size width accessor
diff --git a/lldb/include/lldb/Target/Target.h b/lldb/include/lldb/Target/Target.h
index 908094bfd888d..c0fcda7c0d960 100644
--- a/lldb/include/lldb/Target/Target.h
+++ b/lldb/include/lldb/Target/Target.h
@@ -537,6 +537,7 @@ class Target : public std::enable_shared_from_this<Target>,
eBroadcastBitWatchpointChanged = (1 << 3),
eBroadcastBitSymbolsLoaded = (1 << 4),
eBroadcastBitSymbolsChanged = (1 << 5),
+ eBroadcastBitNewTargetCreated = (1 << 6),
};
// These two functions fill out the Broadcaster interface:
@@ -556,6 +557,13 @@ class Target : public std::enable_shared_from_this<Target>,
TargetEventData(const lldb::TargetSP &target_sp,
const ModuleList &module_list);
+ // Constructor for eBroadcastBitNewTargetCreated events. For this event
+ // type:
+ // - target_sp is the parent target (the subject/broadcaster of the event)
+ // - created_target_sp is the newly created target
+ TargetEventData(const lldb::TargetSP &target_sp,
+ const lldb::TargetSP &created_target_sp);
+
~TargetEventData() override;
static llvm::StringRef GetFlavorString();
@@ -570,14 +578,23 @@ class Target : public std::enable_shared_from_this<Target>,
static lldb::TargetSP GetTargetFromEvent(const Event *event_ptr);
+ // For eBroadcastBitNewTargetCreated events, returns the newly created
+ // target. For other event types, returns an invalid target.
+ static lldb::TargetSP GetCreatedTargetFromEvent(const Event *event_ptr);
+
static ModuleList GetModuleListFromEvent(const Event *event_ptr);
const lldb::TargetSP &GetTarget() const { return m_target_sp; }
+ const lldb::TargetSP &GetCreatedTarget() const {
+ return m_created_target_sp;
+ }
+
const ModuleList &GetModuleList() const { return m_module_list; }
private:
lldb::TargetSP m_target_sp;
+ lldb::TargetSP m_created_target_sp;
ModuleList m_module_list;
TargetEventData(const TargetEventData &) = delete;
@@ -622,6 +639,30 @@ class Target : public std::enable_shared_from_this<Target>,
/// requirements.
llvm::Error SetLabel(llvm::StringRef label);
+ /// Get the target session name for this target.
+ ///
+ /// Provides a meaningful name for IDEs or tools to display for dynamically
+ /// created targets. Defaults to "Session {ID}" based on the globally unique
+ /// ID.
+ ///
+ /// \return
+ /// The target session name for this target.
+ llvm::StringRef GetTargetSessionName() { return m_target_session_name; }
+
+ /// Set the target session name for this target.
+ ///
+ /// This should typically be set along with the event
+ /// eBroadcastBitNewTargetCreated. Useful for scripts or triggers that
+ /// automatically create targets and want to provide meaningful names that
+ /// IDEs or other tools can display to help users identify the origin and
+ /// purpose of each target.
+ ///
+ /// \param[in] target_session_name
+ /// The target session name to set for this target.
+ void SetTargetSessionName(llvm::StringRef target_session_name) {
+ m_target_session_name = target_session_name.str();
+ }
+
/// Find a binary on the system and return its Module,
/// or return an existing Module that is already in the Target.
///
@@ -1719,8 +1760,11 @@ class Target : public std::enable_shared_from_this<Target>,
bool m_is_dummy_target;
unsigned m_next_persistent_variable_index = 0;
lldb::user_id_t m_target_unique_id =
- LLDB_INVALID_GLOBALLY_UNIQUE_TARGET_ID; /// The globally unique ID
+ LLDB_INVALID_GLOBALLY_UNIQUE_TARGET_ID; ///< The globally unique ID
/// assigned to this target
+ std::string m_target_session_name; ///< The target session name for this
+ /// target, used to name debugging
+ /// sessions in DAP.
/// An optional \a lldb_private::Trace object containing processor trace
/// information of this target.
lldb::TraceSP m_trace_sp;
diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/dap_server.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/dap_server.py
index 459b7ab89dbef..35a4f8934e961 100644
--- a/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/dap_server.py
+++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/dap_server.py
@@ -785,6 +785,8 @@ def request_attach(
*,
program: Optional[str] = None,
pid: Optional[int] = None,
+ debuggerId: Optional[int] = None,
+ targetId: Optional[int] = None,
waitFor=False,
initCommands: Optional[list[str]] = None,
preRunCommands: Optional[list[str]] = None,
@@ -804,6 +806,10 @@ def request_attach(
args_dict["pid"] = pid
if program is not None:
args_dict["program"] = program
+ if debuggerId is not None:
+ args_dict["debuggerId"] = debuggerId
+ if targetId is not None:
+ args_dict["targetId"] = targetId
if waitFor:
args_dict["waitFor"] = waitFor
args_dict["initCommands"] = self.init_commands
diff --git a/lldb/source/API/SBTarget.cpp b/lldb/source/API/SBTarget.cpp
index 98d10aa07c53f..1879f3957ca32 100644
--- a/lldb/source/API/SBTarget.cpp
+++ b/lldb/source/API/SBTarget.cpp
@@ -128,6 +128,12 @@ SBTarget SBTarget::GetTargetFromEvent(const SBEvent &event) {
return Target::TargetEventData::GetTargetFromEvent(event.get());
}
+SBTarget SBTarget::GetCreatedTargetFromEvent(const SBEvent &event) {
+ LLDB_INSTRUMENT_VA(event);
+
+ return Target::TargetEventData::GetCreatedTargetFromEvent(event.get());
+}
+
uint32_t SBTarget::GetNumModulesFromEvent(const SBEvent &event) {
LLDB_INSTRUMENT_VA(event);
@@ -1641,6 +1647,14 @@ lldb::user_id_t SBTarget::GetGloballyUniqueID() const {
return LLDB_INVALID_GLOBALLY_UNIQUE_TARGET_ID;
}
+const char *SBTarget::GetTargetSessionName() const {
+ LLDB_INSTRUMENT_VA(this);
+
+ if (TargetSP target_sp = GetSP())
+ return ConstString(target_sp->GetTargetSessionName()).AsCString();
+ return nullptr;
+}
+
SBError SBTarget::SetLabel(const char *label) {
LLDB_INSTRUMENT_VA(this, label);
diff --git a/lldb/source/Target/Target.cpp b/lldb/source/Target/Target.cpp
index 5f2e7af54044a..12c653c0eb8cf 100644
--- a/lldb/source/Target/Target.cpp
+++ b/lldb/source/Target/Target.cpp
@@ -185,6 +185,8 @@ Target::Target(Debugger &debugger, const ArchSpec &target_arch,
m_internal_stop_hooks(), m_latest_stop_hook_id(0), m_valid(true),
m_suppress_stop_hooks(false), m_is_dummy_target(is_dummy_target),
m_target_unique_id(g_target_unique_id++),
+ m_target_session_name(
+ llvm::formatv("Session {0}", m_target_unique_id).str()),
m_frame_recognizer_manager_up(
std::make_unique<StackFrameRecognizerManager>()) {
SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
@@ -192,6 +194,7 @@ Target::Target(Debugger &debugger, const ArchSpec &target_arch,
SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
+ SetEventName(eBroadcastBitNewTargetCreated, "new-target-created");
CheckInWithManager();
@@ -5198,6 +5201,11 @@ Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
const ModuleList &module_list)
: EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
+Target::TargetEventData::TargetEventData(
+ const lldb::TargetSP &target_sp, const lldb::TargetSP &created_target_sp)
+ : EventData(), m_target_sp(target_sp),
+ m_created_target_sp(created_target_sp), m_module_list() {}
+
Target::TargetEventData::~TargetEventData() = default;
llvm::StringRef Target::TargetEventData::GetFlavorString() {
@@ -5232,6 +5240,15 @@ TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
return target_sp;
}
+TargetSP
+Target::TargetEventData::GetCreatedTargetFromEvent(const Event *event_ptr) {
+ TargetSP created_target_sp;
+ const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
+ if (event_data)
+ created_target_sp = event_data->m_created_target_sp;
+ return created_target_sp;
+}
+
ModuleList
Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
ModuleList module_list;
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 2db00a5ac3b6f..d6287397a93b0 100644
--- a/lldb/test/API/tools/lldb-dap/attach/TestDAP_attach.py
+++ b/lldb/test/API/tools/lldb-dap/attach/TestDAP_attach.py
@@ -75,3 +75,38 @@ def test_by_name_waitFor(self):
self.spawn_thread.start()
self.attach(program=program, waitFor=True)
self.continue_and_verify_pid()
+
+ def test_attach_with_missing_debuggerId_or_targetId(self):
+ """
+ Test that attaching with only one of debuggerId/targetId specified
+ fails with the expected error message.
+ """
+ self.build_and_create_debug_adapter()
+
+ # Test with only targetId specified (no debuggerId)
+ resp = self.attach(targetId=99999, expectFailure=True)
+ self.assertFalse(resp["success"])
+ self.assertIn(
+ "Both debuggerId and targetId must be specified together",
+ resp["body"]["error"]["format"],
+ )
+
+ def test_attach_with_invalid_debuggerId_and_targetId(self):
+ """
+ Test that attaching with both debuggerId and targetId specified but
+ invalid fails with an appropriate error message.
+ """
+ self.build_and_create_debug_adapter()
+
+ # Attach with both debuggerId=9999 and targetId=99999 (both invalid).
+ # Since debugger ID 9999 likely doesn't exist in the global registry,
+ # we expect a validation error.
+ resp = self.attach(debuggerId=9999, targetId=99999, expectFailure=True)
+ self.assertFalse(resp["success"])
+ error_msg = resp["body"]["error"]["format"]
+ # Either error is acceptable - both indicate the debugger reuse
+ # validation is working correctly
+ self.assertTrue(
+ "Unable to find existing debugger" in error_msg
+ or f"Expected debugger/target not found error, got: {error_msg}"
+ )
diff --git a/lldb/test/API/tools/lldb-dap/startDebugging/TestDAP_startDebugging.py b/lldb/test/API/tools/lldb-dap/startDebugging/TestDAP_startDebugging.py
index b487257b6414d..7e60dd22f1084 100644
--- a/lldb/test/API/tools/lldb-dap/startDebugging/TestDAP_startDebugging.py
+++ b/lldb/test/API/tools/lldb-dap/startDebugging/TestDAP_startDebugging.py
@@ -36,3 +36,54 @@ def test_startDebugging(self):
request = self.dap_server.reverse_requests[0]
self.assertEqual(request["arguments"]["configuration"]["pid"], 321)
self.assertEqual(request["arguments"]["request"], "attach")
+
+ def test_startDebugging_debugger_reuse(self):
+ """
+ Tests that debugger and target IDs can be passed through startDebugging
+ for debugger reuse. This verifies the infrastructure for child DAP
+ sessions to reuse the parent's debugger and attach to an existing target.
+ """
+ program = self.getBuildArtifact("a.out")
+ source = "main.c"
+ self.build_and_launch(program)
+
+ breakpoint_line = line_number(source, "// breakpoint")
+ self.set_source_breakpoints(source, [breakpoint_line])
+ self.continue_to_next_stop()
+
+ # Use mock IDs to test the infrastructure
+ # In a real scenario, these would come from the parent session
+ test_debugger_id = 1
+ test_target_id = 100
+
+ # Send a startDebugging request with debuggerId and targetId
+ # This simulates creating a child DAP session that reuses the debugger
+ self.dap_server.request_evaluate(
+ f'`lldb-dap start-debugging attach \'{{"debuggerId":{test_debugger_id},"targetId":{test_target_id}}}\'',
+ context="repl",
+ )
+
+ self.continue_to_exit()
+
+ # Verify the reverse request was sent with the correct IDs
+ self.assertEqual(
+ len(self.dap_server.reverse_requests),
+ 1,
+ "Should have received one startDebugging reverse request",
+ )
+
+ request = self.dap_server.reverse_requests[0]
+ self.assertEqual(request["command"], "startDebugging")
+ self.assertEqual(request["arguments"]["request"], "attach")
+
+ config = request["arguments"]["configuration"]
+ self.assertEqual(
+ config["debuggerId"],
+ test_debugger_id,
+ "Reverse request should include debugger ID",
+ )
+ self.assertEqual(
+ config["targetId"],
+ test_target_id,
+ "Reverse request should include target ID",
+ )
diff --git a/lldb/tools/lldb-dap/CMakeLists.txt b/lldb/tools/lldb-dap/CMakeLists.txt
index fa940b7b73943..237c3043dbbc7 100644
--- a/lldb/tools/lldb-dap/CMakeLists.txt
+++ b/lldb/tools/lldb-dap/CMakeLists.txt
@@ -10,6 +10,7 @@ add_lldb_library(lldbDAP
DAP.cpp
DAPError.cpp
DAPLog.cpp
+ DAPSessionManager.cpp
EventHelper.cpp
ExceptionBreakpoint.cpp
FifoFiles.cpp
diff --git a/lldb/tools/lldb-dap/DAP.cpp b/lldb/tools/lldb-dap/DAP.cpp
index d4203a2f00983..465d85a07bd34 100644
--- a/lldb/tools/lldb-dap/DAP.cpp
+++ b/lldb/tools/lldb-dap/DAP.cpp
@@ -7,6 +7,7 @@
//===----------------------------------------------------------------------===//
#include "DAP.h"
+#include "CommandPlugins.h"
#include "DAPLog.h"
#include "EventHelper.h"
#include "ExceptionBreakpoint.h"
@@ -242,10 +243,12 @@ llvm::Error DAP::ConfigureIO(std::FILE *overrideOut, std::FILE *overrideErr) {
}
void DAP::StopEventHandlers() {
- if (event_thread.joinable()) {
- broadcaster.BroadcastEventByType(eBroadcastBitStopEventThread);
- event_thread.join();
- }
+ event_thread_sp.reset();
+
+ // Clean up expired event threads from the session manager.
+ DAPSessionManager::GetInstance().ReleaseExpiredEventThreads();
+
+ // Still handle the progress thread normally since it's per-DAP instance.
if (progress_event_thread.joinable()) {
broadcaster.BroadcastEventByType(eBroadcastBitStopProgressThread);
progress_event_thread.join();
@@ -816,7 +819,8 @@ void DAP::SetTarget(const lldb::SBTarget target) {
lldb::SBTarget::eBroadcastBitModulesLoaded |
lldb::SBTarget::eBroadcastBitModulesUnloaded |
lldb::SBTarget::eBroadcastBitSymbolsLoaded |
- lldb::SBTarget::eBroadcastBitSymbolsChanged);
+ lldb::SBTarget::eBroadcastBitSymbolsChanged |
+ lldb::SBTarget::eBroadcastBitNewTargetCreated);
listener.StartListeningForEvents(this->broadcaster,
eBroadcastBitStopEventThread);
}
@@ -1303,13 +1307,99 @@ protocol::Capabilities DAP::GetCustomCapabilities() {
}
void DAP::StartEventThread() {
- event_thread = std::thread(&DAP::EventThread, this);
+ // Get event thread for this debugger (creates it if it doesn't exist).
+ event_thread_sp = DAPSessionManager::GetInstance().GetEventThreadForDebugger(
+ debugger, this);
}
void DAP::StartProgressEventThread() {
progress_event_thread = std::thread(&DAP::ProgressEventThread, this);
}
+void DAP::StartEventThreads() {
+ if (clientFeatures.contains(eClientFeatureProgressReporting))
+ StartProgressEventThread();
+
+ StartEventThread();
+}
+
+llvm::Error DAP::InitializeDebugger(int debugger_id,
+ lldb::user_id_t target_id) {
+ // Find the existing debugger by ID
+ debugger = lldb::SBDebugger::FindDebuggerWithID(debugger_id);
+ if (!debugger.IsValid()) {
+ return llvm::createStringError(
+ "Unable to find existing debugger for debugger ID");
+ }
+
+ // Find the target within the debugger by its globally unique ID
+ lldb::SBTarget target = debugger.FindTargetByGloballyUniqueID(target_id);
+ if (!target.IsValid()) {
+ return llvm::createStringError(
+ "Unable to find existing target for target ID");
+ }
+
+ // Set the target for this DAP session.
+ SetTarget(target);
+ StartEventThreads();
+ return llvm::Error::success();
+}
+
+llvm::Error DAP::InitializeDebugger() {
+ debugger = lldb::SBDebugger::Create(/*argument_name=*/false);
+
+ // Configure input/output/error file descriptors.
+ debugger.SetInputFile(in);
+ target = debugger.GetDummyTarget();
+
+ llvm::Expected<int> out_fd = out.GetWriteFileDescriptor();
+ if (!out_fd)
+ return out_fd.takeError();
+ debugger.SetOutputFile(lldb::SBFile(*out_fd, "w", false));
+
+ llvm::Expected<int> err_fd = err.GetWriteFileDescriptor();
+ if (!err_fd)
+ return err_fd.takeError();
+ debugger.SetErrorFile(lldb::SBFile(*err_fd, "w", false));
+
+ // The sourceInitFile option is not part of the DAP specification. It is an
+ // extension used by the test suite to prevent sourcing `.lldbinit` and
+ // changing its behavior. The CLI flag --no-lldbinit takes precedence over
+ // the DAP parameter.
+ bool should_source_init_files = !no_lldbinit && sourceInitFile;
+ if (should_source_init_files) {
+ debugger.SkipLLDBInitFiles(false);
+ debugger.SkipAppInitFiles(false);
+ lldb::SBCommandReturnObject init;
+ auto interp = debugger.GetCommandInterpreter();
+ interp.SourceInitFileInGlobalDirectory(init);
+ interp.SourceInitFileInHomeDirectory(init);
+ }
+
+ // Run initialization commands.
+ if (llvm::Error err = RunPreInitCommands())
+ return err;
+
+ auto cmd = debugger.GetCommandInterpreter().AddMultiwordCommand(
+ "lldb-dap", "Commands for managing lldb-dap.");
+
+ if (clientFeatures.contains(eClientFeatureStartDebuggingRequest)) {
+ cmd.AddCommand(
+ "start-debugging", new StartDebuggingCommand(*this),
+ "Sends a startDebugging request from the debug adapter to the client "
+ "to start a child debug session of the same type as the caller.");
+ }
+
+ cmd.AddCommand(
+ "repl-mode", new ReplModeCommand(*this),
+ "Get or set the repl behavior of lldb-dap evaluation requests.");
+ cmd.AddCommand("send-event", new SendEventCommand(*this),
+ "Sends an DAP event to the client.");
+
+ StartEventThreads();
+ return llvm::Error::success();
+}
+
void DAP::ProgressEventThread() {
lldb::SBListener listener("lldb-dap.progress.listener");
debugger.GetBroadcaster().AddListener(
@@ -1370,213 +1460,6 @@ void DAP::ProgressEventThread() {
}
}
-// All events from the debugger, target, process, thread and frames are
-// received in this function that runs in its own thread. We are using a
-// "FILE *" to output packets back to VS Code and they have mutexes in them
-// them prevent multiple threads from writing simultaneously so no locking
-// is required.
-void DAP::EventThread() {
- llvm::set_thread_name("lldb.DAP.client." + m_client_name + ".event_handler");
- lldb::SBListener listener = debugger.GetListener();
- broadcaster.AddListener(listener, eBroadcastBitStopEventThread);
- debugger.GetBroadcaster().AddListener(
- listener, lldb::eBroadcastBitError | lldb::eBroadcastBitWarning);
-
- // listen for thread events.
- listener.StartListeningForEventClass(
- debugger, lldb::SBThread::GetBroadcasterClassName(),
- lldb::SBThread::eBroadcastBitStackChanged);
-
- lldb::SBEvent event;
- bool done = false;
- while (!done) {
- if (!listener.WaitForEvent(UINT32_MAX, event))
- continue;
-
- const uint32_t event_mask = event.GetType();
- if (lldb::SBProcess::EventIsProcessEvent(event)) {
- HandleProcessEvent(event, /*&process_exited=*/done);
- } else if (lldb::SBTarget::EventIsTargetEvent(event)) {
- HandleTargetEvent(event);
- } else if (lldb::SBBreakpoint::EventIsBreakpointEvent(event)) {
- HandleBreakpointEvent(event);
- } else if (lldb::SBThread::EventIsThreadEvent(event)) {
- HandleThreadEvent(event);
- } else if (event_mask & lldb::eBroadcastBitError ||
- event_mask & lldb::eBroadcastBitWarning) {
- HandleDiagnosticEvent(event);
- } else if (event.BroadcasterMatchesRef(broadcaster)) {
- if (event_mask & eBroadcastBitStopEventThread) {
- done = true;
- }
- }
- }
-}
-
-void DAP::HandleProcessEvent(const lldb::SBEvent &event, bool &process_exited) {
- lldb::SBProcess process = lldb::SBProcess::GetProcessFromEvent(event);
- const uint32_t event_mask = event.GetType();
- if (event_mask & lldb::SBProcess::eBroadcastBitStateChanged) {
- auto state = lldb::SBProcess::GetStateFromEvent(event);
- switch (state) {
- case lldb::eStateConnected:
- case lldb::eStateDetached:
- case lldb::eStateInvalid:
- case lldb::eStateUnloaded:
- break;
- case lldb::eStateAttaching:
- case lldb::eStateCrashed:
- case lldb::eStateLaunching:
- case lldb::eStateStopped:
- case lldb::eStateSuspended:
- // Only report a stopped event if the process was not
- // automatically restarted.
- if (!lldb::SBProcess::GetRestartedFromEvent(event)) {
- SendStdOutStdErr(*this, process);
- if (llvm::Error err = SendThreadStoppedEvent(*this))
- DAP_LOG_ERROR(log, std::move(err),
- "({1}) reporting thread stopped: {0}", m_client_name);
- }
- break;
- case lldb::eStateRunning:
- case lldb::eStateStepping:
- WillContinue();
- SendContinuedEvent(*this);
- break;
- case lldb::eStateExited:
- lldb::SBStream stream;
- process.GetStatus(stream);
- SendOutput(OutputType::Console, stream.GetData());
-
- // When restarting, we can get an "exited" event for the process we
- // just killed with the old PID, or even with no PID. In that case
- // we don't have to terminate the session.
- if (process.GetProcessID() == LLDB_INVALID_PROCESS_ID ||
- process.GetProcessID() == restarting_process_id) {
- restarting_process_id = LLDB_INVALID_PROCESS_ID;
- } else {
- // Run any exit LLDB commands the user specified in the
- // launch.json
- RunExitCommands();
- SendProcessExitedEvent(*this, process);
- SendTerminatedEvent();
- process_exited = true;
- }
- break;
- }
- } else if ((event_mask & lldb::SBProcess::eBroadcastBitSTDOUT) ||
- (event_mask & lldb::SBProcess::eBroadcastBitSTDERR)) {
- SendStdOutStdErr(*this, process);
- }
-}
-
-void DAP::HandleTargetEvent(const lldb::SBEvent &event) {
- const uint32_t event_mask = event.GetType();
- if (event_mask & lldb::SBTarget::eBroadcastBitModulesLoaded ||
- event_mask & lldb::SBTarget::eBroadcastBitModulesUnloaded ||
- event_mask & lldb::SBTarget::eBroadcastBitSymbolsLoaded ||
- event_mask & lldb::SBTarget::eBroadcastBitSymbolsChanged) {
- const uint32_t num_modules = lldb::SBTarget::GetNumModulesFromEvent(event);
- const bool remove_module =
- event_mask & lldb::SBTarget::eBroadcastBitModulesUnloaded;
-
- // NOTE: Both mutexes must be acquired to prevent deadlock when
- // handling `modules_request`, which also requires both locks.
- lldb::SBMutex api_mutex = GetAPIMutex();
- const std::scoped_lock<lldb::SBMutex, std::mutex> guard(api_mutex,
- modules_mutex);
- for (uint32_t i = 0; i < num_modules; ++i) {
- lldb::SBModule module =
- lldb::SBTarget::GetModuleAtIndexFromEvent(i, event);
-
- std::optional<protocol::Module> p_module =
- CreateModule(target, module, remove_module);
- if (!p_module)
- continue;
-
- const llvm::StringRef module_id = p_module->id;
-
- const bool module_exists = modules.contains(module_id);
- if (remove_module && module_exists) {
- modules.erase(module_id);
- Send(protocol::Event{"module",
- ModuleEventBody{std::move(p_module).value(),
- ModuleEventBody::eReasonRemoved}});
- } else if (module_exists) {
- Send(protocol::Event{"module",
- ModuleEventBody{std::move(p_module).value(),
- ModuleEventBody::eReasonChanged}});
- } else if (!remove_module) {
- modules.insert(module_id);
- Send(protocol::Event{"module",
- ModuleEventBody{std::move(p_module).value(),
- ModuleEventBody::eReasonNew}});
- }
- }
- }
-}
-
-void DAP::HandleBreakpointEvent(const lldb::SBEvent &event) {
- const uint32_t event_mask = event.GetType();
- if (!(event_mask & lldb::SBTarget::eBroadcastBitBreakpointChanged))
- return;
-
- auto event_type = lldb::SBBreakpoint::GetBreakpointEventTypeFromEvent(event);
- auto bp =
- Breakpoint(*this, lldb::SBBreakpoint::GetBreakpointFromEvent(event));
- // If the breakpoint was set through DAP, it will have the
- // BreakpointBase::kDAPBreakpointLabel. Regardless of whether
- // locations were added, removed, or resolved, the breakpoint isn't
- // going away and the reason is always "changed".
- if ((event_type & lldb::eBreakpointEventTypeLocationsAdded ||
- event_type & lldb::eBreakpointEventTypeLocationsRemoved ||
- event_type & lldb::eBreakpointEventTypeLocationsResolved) &&
- bp.MatchesName(BreakpointBase::kDAPBreakpointLabel)) {
- // As the DAP client already knows the path of this breakpoint, we
- // don't need to send it back as part of the "changed" event. This
- // avoids sending paths that should be source mapped. Note that
- // CreateBreakpoint doesn't apply source mapping and certain
- // implementation ignore the source part of this event anyway.
- protocol::Breakpoint protocol_bp = bp.ToProtocolBreakpoint();
-
- // "source" is not needed here, unless we add adapter data to be
- // saved by the client.
- if (protocol_bp.source && !protocol_bp.source->adapterData)
- protocol_bp.source = std::nullopt;
-
- llvm::json::Object body;
- body.try_emplace("breakpoint", protocol_bp);
- body.try_emplace("reason", "changed");
-
- llvm::json::Object bp_event = CreateEventObject("breakpoint");
- bp_event.try_emplace("body", std::move(body));
-
- SendJSON(llvm::json::Value(std::move(bp_event)));
- }
-}
-
-void DAP::HandleThreadEvent(const lldb::SBEvent &event) {
- const uint32_t event_type = event.GetType();
-
- if (event_type & lldb::SBThread::eBroadcastBitStackChanged) {
- const lldb::SBThread evt_thread = lldb::SBThread::GetThreadFromEvent(event);
- SendInvalidatedEvent(*this, {InvalidatedEventBody::eAreaStacks},
- evt_thread.GetThreadID());
- }
-}
-
-void DAP::HandleDiagnosticEvent(const lldb::SBEvent &event) {
- const lldb::SBStructuredData data =
- lldb::SBDebugger::GetDiagnosticFromEvent(event);
- if (!data.IsValid())
- return;
-
- std::string type = GetStringValue(data.GetValueForKey("type"));
- std::string message = GetStringValue(data.GetValueForKey("message"));
- SendOutput(OutputType::Important,
- llvm::formatv("{0}: {1}", type, message).str());
-}
-
std::vector<protocol::Breakpoint> DAP::SetSourceBreakpoints(
const protocol::Source &source,
const std::optional<std::vector<protocol::SourceBreakpoint>> &breakpoints) {
diff --git a/lldb/tools/lldb-dap/DAP.h b/lldb/tools/lldb-dap/DAP.h
index 5d40341329f34..b5f2a57d9dc5f 100644
--- a/lldb/tools/lldb-dap/DAP.h
+++ b/lldb/tools/lldb-dap/DAP.h
@@ -10,6 +10,7 @@
#define LLDB_TOOLS_LLDB_DAP_DAP_H
#include "DAPForward.h"
+#include "DAPSessionManager.h"
#include "ExceptionBreakpoint.h"
#include "FunctionBreakpoint.h"
#include "InstructionBreakpoint.h"
@@ -47,6 +48,7 @@
#include <condition_variable>
#include <cstdint>
#include <deque>
+#include <map>
#include <memory>
#include <mutex>
#include <optional>
@@ -81,6 +83,8 @@ enum class ReplMode { Variable = 0, Command, Auto };
using DAPTransport = lldb_private::transport::JSONTransport<ProtocolDescriptor>;
struct DAP final : public DAPTransport::MessageHandler {
+ friend class DAPSessionManager;
+
/// Path to the lldb-dap binary itself.
static llvm::StringRef debug_adapter_path;
@@ -157,6 +161,11 @@ struct DAP final : public DAPTransport::MessageHandler {
/// Whether to disable sourcing .lldbinit files.
bool no_lldbinit;
+ /// Stores whether the initialize request specified a value for
+ /// lldbExtSourceInitFile. Used by the test suite to prevent sourcing
+ /// `.lldbinit` and changing its behavior.
+ bool sourceInitFile = true;
+
/// The initial thread list upon attaching.
std::vector<protocol::Thread> initial_thread_list;
@@ -408,9 +417,33 @@ struct DAP final : public DAPTransport::MessageHandler {
lldb::SBMutex GetAPIMutex() const { return target.GetAPIMutex(); }
+ /// Get the client name for this DAP session.
+ llvm::StringRef GetClientName() const { return m_client_name; }
+
void StartEventThread();
void StartProgressEventThread();
+ /// DAP debugger initialization functions.
+ /// @{
+
+ /// Perform complete DAP initialization for a new debugger.
+ llvm::Error InitializeDebugger();
+
+ /// Perform complete DAP initialization by reusing an existing debugger and
+ /// target.
+ ///
+ /// \param[in] debugger_id
+ /// The ID of the existing debugger to reuse.
+ ///
+ /// \param[in] target_id
+ /// The globally unique ID of the existing target to reuse.
+ llvm::Error InitializeDebugger(int debugger_id, lldb::user_id_t target_id);
+
+ /// Start event handling threads based on client capabilities.
+ void StartEventThreads();
+
+ /// @}
+
/// Sets the given protocol `breakpoints` in the given `source`, while
/// removing any existing breakpoints in the given source if they are not in
/// `breakpoint`.
@@ -453,15 +486,11 @@ struct DAP final : public DAPTransport::MessageHandler {
/// Event threads.
/// @{
- void EventThread();
- void HandleProcessEvent(const lldb::SBEvent &event, bool &process_exited);
- void HandleTargetEvent(const lldb::SBEvent &event);
- void HandleBreakpointEvent(const lldb::SBEvent &event);
- void HandleThreadEvent(const lldb::SBEvent &event);
- void HandleDiagnosticEvent(const lldb::SBEvent &event);
void ProgressEventThread();
- std::thread event_thread;
+ /// Event thread is a shared pointer in case we have a multiple
+ /// DAP instances sharing the same event thread.
+ std::shared_ptr<ManagedEventThread> event_thread_sp;
std::thread progress_event_thread;
/// @}
diff --git a/lldb/tools/lldb-dap/DAPForward.h b/lldb/tools/lldb-dap/DAPForward.h
index 6620d5fd33642..e7fbbf669e7ec 100644
--- a/lldb/tools/lldb-dap/DAPForward.h
+++ b/lldb/tools/lldb-dap/DAPForward.h
@@ -28,6 +28,7 @@ namespace lldb {
class SBAttachInfo;
class SBBreakpoint;
class SBBreakpointLocation;
+class SBBroadcaster;
class SBCommandInterpreter;
class SBCommandReturnObject;
class SBCommunication;
diff --git a/lldb/tools/lldb-dap/DAPSessionManager.cpp b/lldb/tools/lldb-dap/DAPSessionManager.cpp
new file mode 100644
index 0000000000000..d5440ffd64597
--- /dev/null
+++ b/lldb/tools/lldb-dap/DAPSessionManager.cpp
@@ -0,0 +1,142 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#include "DAPSessionManager.h"
+#include "DAP.h"
+#include "EventHelper.h"
+#include "lldb/API/SBBroadcaster.h"
+#include "lldb/API/SBEvent.h"
+#include "lldb/API/SBTarget.h"
+#include "lldb/Host/MainLoopBase.h"
+#include "llvm/Support/Threading.h"
+#include "llvm/Support/WithColor.h"
+
+#include <chrono>
+#include <mutex>
+
+namespace lldb_dap {
+
+ManagedEventThread::ManagedEventThread(lldb::SBBroadcaster broadcaster,
+ std::thread t)
+ : m_broadcaster(broadcaster), m_event_thread(std::move(t)) {}
+
+ManagedEventThread::~ManagedEventThread() {
+ if (m_event_thread.joinable()) {
+ m_broadcaster.BroadcastEventByType(eBroadcastBitStopEventThread);
+ m_event_thread.join();
+ }
+}
+
+DAPSessionManager &DAPSessionManager::GetInstance() {
+ static std::once_flag initialized;
+ static DAPSessionManager *instance =
+ nullptr; // NOTE: intentional leak to avoid issues with C++ destructor
+ // chain
+
+ std::call_once(initialized, []() { instance = new DAPSessionManager(); });
+
+ return *instance;
+}
+
+void DAPSessionManager::RegisterSession(lldb_private::MainLoop *loop,
+ DAP *dap) {
+ std::lock_guard<std::mutex> lock(m_sessions_mutex);
+ m_active_sessions[loop] = dap;
+}
+
+void DAPSessionManager::UnregisterSession(lldb_private::MainLoop *loop) {
+ std::unique_lock<std::mutex> lock(m_sessions_mutex);
+ m_active_sessions.erase(loop);
+ std::notify_all_at_thread_exit(m_sessions_condition, std::move(lock));
+}
+
+std::vector<DAP *> DAPSessionManager::GetActiveSessions() {
+ std::lock_guard<std::mutex> lock(m_sessions_mutex);
+ std::vector<DAP *> sessions;
+ for (const auto &[loop, dap] : m_active_sessions)
+ if (dap)
+ sessions.emplace_back(dap);
+ return sessions;
+}
+
+void DAPSessionManager::DisconnectAllSessions() {
+ std::lock_guard<std::mutex> lock(m_sessions_mutex);
+ m_client_failed = false;
+ for (auto [loop, dap] : m_active_sessions) {
+ if (dap) {
+ if (llvm::Error error = dap->Disconnect()) {
+ m_client_failed = true;
+ llvm::WithColor::error() << "DAP client disconnected failed: "
+ << llvm::toString(std::move(error)) << "\n";
+ }
+ loop->AddPendingCallback(
+ [](lldb_private::MainLoopBase &loop) { loop.RequestTermination(); });
+ }
+ }
+}
+
+llvm::Error DAPSessionManager::WaitForAllSessionsToDisconnect() {
+ std::unique_lock<std::mutex> lock(m_sessions_mutex);
+ m_sessions_condition.wait(lock, [this] { return m_active_sessions.empty(); });
+
+ // Check if any disconnection failed and return appropriate error.
+ if (m_client_failed)
+ return llvm::make_error<llvm::StringError>(
+ "disconnecting all clients failed", llvm::inconvertibleErrorCode());
+
+ return llvm::Error::success();
+}
+
+std::shared_ptr<ManagedEventThread>
+DAPSessionManager::GetEventThreadForDebugger(lldb::SBDebugger debugger,
+ DAP *requesting_dap) {
+ lldb::user_id_t debugger_id = debugger.GetID();
+ std::lock_guard<std::mutex> lock(m_sessions_mutex);
+
+ // Try to use shared event thread, if it exists.
+ if (auto it = m_debugger_event_threads.find(debugger_id);
+ it != m_debugger_event_threads.end()) {
+ if (std::shared_ptr<ManagedEventThread> thread_sp = it->second.lock())
+ return thread_sp;
+ // Our weak pointer has expired.
+ m_debugger_event_threads.erase(it);
+ }
+
+ // Create a new event thread and store it.
+ auto new_thread_sp = std::make_shared<ManagedEventThread>(
+ requesting_dap->broadcaster,
+ std::thread(EventThread, debugger, requesting_dap->broadcaster,
+ requesting_dap->m_client_name, requesting_dap->log));
+ m_debugger_event_threads[debugger_id] = new_thread_sp;
+ return new_thread_sp;
+}
+
+DAP *DAPSessionManager::FindDAPForTarget(lldb::SBTarget target) {
+ std::lock_guard<std::mutex> lock(m_sessions_mutex);
+
+ for (const auto &[loop, dap] : m_active_sessions)
+ if (dap && dap->target.IsValid() && dap->target == target)
+ return dap;
+
+ return nullptr;
+}
+
+void DAPSessionManager::ReleaseExpiredEventThreads() {
+ std::lock_guard<std::mutex> lock(m_sessions_mutex);
+ for (auto it = m_debugger_event_threads.begin();
+ it != m_debugger_event_threads.end();) {
+ // Check if the weak_ptr has expired (no DAP instances are using it
+ // anymore).
+ if (it->second.expired()) {
+ it = m_debugger_event_threads.erase(it);
+ } else {
+ ++it;
+ }
+ }
+}
+
+} // namespace lldb_dap
diff --git a/lldb/tools/lldb-dap/DAPSessionManager.h b/lldb/tools/lldb-dap/DAPSessionManager.h
new file mode 100644
index 0000000000000..ad76b081ad78b
--- /dev/null
+++ b/lldb/tools/lldb-dap/DAPSessionManager.h
@@ -0,0 +1,119 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This file contains the declarations of the DAPSessionManager and
+/// ManagedEventThread classes, which are used to multiple concurrent DAP
+/// sessions in a single lldb-dap process.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLDB_TOOLS_LLDB_DAP_DAPSESSIONMANAGER_H
+#define LLDB_TOOLS_LLDB_DAP_DAPSESSIONMANAGER_H
+
+#include "lldb/API/SBBroadcaster.h"
+#include "lldb/API/SBDebugger.h"
+#include "lldb/API/SBTarget.h"
+#include "lldb/Host/MainLoop.h"
+#include "lldb/lldb-types.h"
+#include "llvm/Support/Error.h"
+#include <condition_variable>
+#include <map>
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <thread>
+#include <vector>
+
+namespace lldb_dap {
+
+// Forward declarations
+struct DAP;
+
+class ManagedEventThread {
+public:
+ // Constructor declaration
+ ManagedEventThread(lldb::SBBroadcaster broadcaster, std::thread t);
+
+ ~ManagedEventThread();
+
+ ManagedEventThread(const ManagedEventThread &) = delete;
+ ManagedEventThread &operator=(const ManagedEventThread &) = delete;
+
+private:
+ lldb::SBBroadcaster m_broadcaster;
+ std::thread m_event_thread;
+};
+
+/// Global DAP session manager that manages multiple concurrent DAP sessions in
+/// a single lldb-dap process. Handles session lifecycle tracking, coordinates
+/// shared debugger event threads, and facilitates target handoff between
+/// sessions for dynamically created targets.
+class DAPSessionManager {
+public:
+ /// Get the singleton instance of the DAP session manager.
+ static DAPSessionManager &GetInstance();
+
+ /// Register a DAP session.
+ void RegisterSession(lldb_private::MainLoop *loop, DAP *dap);
+
+ /// Unregister a DAP session. Called by sessions when they complete their
+ /// disconnection, which unblocks WaitForAllSessionsToDisconnect().
+ void UnregisterSession(lldb_private::MainLoop *loop);
+
+ /// Get all active DAP sessions.
+ std::vector<DAP *> GetActiveSessions();
+
+ /// Disconnect all registered sessions by calling Disconnect() on
+ /// each and requesting their event loops to terminate. Used during
+ /// shutdown to force all sessions to begin disconnecting.
+ void DisconnectAllSessions();
+
+ /// Block until all sessions disconnect and unregister. Returns an error if
+ /// DisconnectAllSessions() was called and any disconnection failed.
+ llvm::Error WaitForAllSessionsToDisconnect();
+
+ /// Get or create event thread for a specific debugger.
+ std::shared_ptr<ManagedEventThread>
+ GetEventThreadForDebugger(lldb::SBDebugger debugger, DAP *requesting_dap);
+
+ /// Find the DAP instance that owns the given target.
+ DAP *FindDAPForTarget(lldb::SBTarget target);
+
+ /// Static convenience method for FindDAPForTarget.
+ static DAP *FindDAP(lldb::SBTarget target) {
+ return GetInstance().FindDAPForTarget(target);
+ }
+
+ /// Clean up expired event threads from the collection.
+ void ReleaseExpiredEventThreads();
+
+private:
+ DAPSessionManager() = default;
+ ~DAPSessionManager() = default;
+
+ // Non-copyable and non-movable.
+ DAPSessionManager(const DAPSessionManager &) = delete;
+ DAPSessionManager &operator=(const DAPSessionManager &) = delete;
+ DAPSessionManager(DAPSessionManager &&) = delete;
+ DAPSessionManager &operator=(DAPSessionManager &&) = delete;
+
+ bool m_client_failed = false;
+ std::mutex m_sessions_mutex;
+ std::condition_variable m_sessions_condition;
+ std::map<lldb_private::MainLoop *, DAP *> m_active_sessions;
+
+ /// Map from debugger ID to its event thread, used when multiple DAP sessions
+ /// share the same debugger instance.
+ std::map<lldb::user_id_t, std::weak_ptr<ManagedEventThread>>
+ m_debugger_event_threads;
+};
+
+} // namespace lldb_dap
+
+#endif // LLDB_TOOLS_LLDB_DAP_DAPSESSIONMANAGER_H
diff --git a/lldb/tools/lldb-dap/EventHelper.cpp b/lldb/tools/lldb-dap/EventHelper.cpp
index 12d9e21c52ab3..bdb6bb55fe168 100644
--- a/lldb/tools/lldb-dap/EventHelper.cpp
+++ b/lldb/tools/lldb-dap/EventHelper.cpp
@@ -7,16 +7,28 @@
//===----------------------------------------------------------------------===//
#include "EventHelper.h"
+#include "Breakpoint.h"
+#include "BreakpointBase.h"
#include "DAP.h"
#include "DAPError.h"
+#include "DAPLog.h"
+#include "DAPSessionManager.h"
+#include "Handler/ResponseHandler.h"
#include "JSONUtils.h"
#include "LLDBUtils.h"
#include "Protocol/ProtocolEvents.h"
#include "Protocol/ProtocolRequests.h"
#include "Protocol/ProtocolTypes.h"
+#include "ProtocolUtils.h"
+#include "lldb/API/SBEvent.h"
#include "lldb/API/SBFileSpec.h"
+#include "lldb/API/SBListener.h"
#include "lldb/API/SBPlatform.h"
+#include "lldb/API/SBStream.h"
#include "llvm/Support/Error.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/Threading.h"
+#include <mutex>
#include <utility>
#if defined(_WIN32)
@@ -306,4 +318,312 @@ void SendMemoryEvent(DAP &dap, lldb::SBValue variable) {
dap.Send(protocol::Event{"memory", std::move(body)});
}
+// Event handler functions that are called by EventThread.
+// These handlers extract the necessary objects from events and find the
+// appropriate DAP instance to handle them, maintaining compatibility with
+// the original DAP::Handle*Event pattern while supporting multi-session
+// debugging.
+
+void HandleProcessEvent(const lldb::SBEvent &event, bool &process_exited,
+ Log *log) {
+ lldb::SBProcess process = lldb::SBProcess::GetProcessFromEvent(event);
+
+ // Find the DAP instance that owns this process's target.
+ DAP *dap = DAPSessionManager::FindDAP(process.GetTarget());
+ if (!dap) {
+ DAP_LOG(log, "Unable to find DAP instance for process {0}",
+ process.GetProcessID());
+ return;
+ }
+
+ const uint32_t event_mask = event.GetType();
+
+ if (event_mask & lldb::SBProcess::eBroadcastBitStateChanged) {
+ auto state = lldb::SBProcess::GetStateFromEvent(event);
+ switch (state) {
+ case lldb::eStateConnected:
+ case lldb::eStateDetached:
+ case lldb::eStateInvalid:
+ case lldb::eStateUnloaded:
+ break;
+ case lldb::eStateAttaching:
+ case lldb::eStateCrashed:
+ case lldb::eStateLaunching:
+ case lldb::eStateStopped:
+ case lldb::eStateSuspended:
+ // Only report a stopped event if the process was not
+ // automatically restarted.
+ if (!lldb::SBProcess::GetRestartedFromEvent(event)) {
+ SendStdOutStdErr(*dap, process);
+ if (llvm::Error err = SendThreadStoppedEvent(*dap))
+ DAP_LOG_ERROR(dap->log, std::move(err),
+ "({1}) reporting thread stopped: {0}",
+ dap->GetClientName());
+ }
+ break;
+ case lldb::eStateRunning:
+ case lldb::eStateStepping:
+ dap->WillContinue();
+ SendContinuedEvent(*dap);
+ break;
+ case lldb::eStateExited:
+ lldb::SBStream stream;
+ process.GetStatus(stream);
+ dap->SendOutput(OutputType::Console, stream.GetData());
+
+ // When restarting, we can get an "exited" event for the process we
+ // just killed with the old PID, or even with no PID. In that case
+ // we don't have to terminate the session.
+ if (process.GetProcessID() == LLDB_INVALID_PROCESS_ID ||
+ process.GetProcessID() == dap->restarting_process_id) {
+ dap->restarting_process_id = LLDB_INVALID_PROCESS_ID;
+ } else {
+ // Run any exit LLDB commands the user specified in the
+ // launch.json
+ dap->RunExitCommands();
+ SendProcessExitedEvent(*dap, process);
+ dap->SendTerminatedEvent();
+ process_exited = true;
+ }
+ break;
+ }
+ } else if ((event_mask & lldb::SBProcess::eBroadcastBitSTDOUT) ||
+ (event_mask & lldb::SBProcess::eBroadcastBitSTDERR)) {
+ SendStdOutStdErr(*dap, process);
+ }
+}
+
+void HandleTargetEvent(const lldb::SBEvent &event, Log *log) {
+ lldb::SBTarget target = lldb::SBTarget::GetTargetFromEvent(event);
+
+ // Find the DAP instance that owns this target.
+ DAP *dap = DAPSessionManager::FindDAP(target);
+ if (!dap) {
+ DAP_LOG(log, "Unable to find DAP instance for target");
+ return;
+ }
+
+ const uint32_t event_mask = event.GetType();
+ if (event_mask & lldb::SBTarget::eBroadcastBitModulesLoaded ||
+ event_mask & lldb::SBTarget::eBroadcastBitModulesUnloaded ||
+ event_mask & lldb::SBTarget::eBroadcastBitSymbolsLoaded ||
+ event_mask & lldb::SBTarget::eBroadcastBitSymbolsChanged) {
+ const uint32_t num_modules = lldb::SBTarget::GetNumModulesFromEvent(event);
+ const bool remove_module =
+ event_mask & lldb::SBTarget::eBroadcastBitModulesUnloaded;
+
+ // NOTE: Both mutexes must be acquired to prevent deadlock when
+ // handling `modules_request`, which also requires both locks.
+ lldb::SBMutex api_mutex = dap->GetAPIMutex();
+ const std::scoped_lock<lldb::SBMutex, std::mutex> guard(api_mutex,
+ dap->modules_mutex);
+ for (uint32_t i = 0; i < num_modules; ++i) {
+ lldb::SBModule module =
+ lldb::SBTarget::GetModuleAtIndexFromEvent(i, event);
+
+ std::optional<protocol::Module> p_module =
+ CreateModule(dap->target, module, remove_module);
+ if (!p_module)
+ continue;
+
+ llvm::StringRef module_id = p_module->id;
+
+ const bool module_exists = dap->modules.contains(module_id);
+ if (remove_module && module_exists) {
+ dap->modules.erase(module_id);
+ dap->Send(protocol::Event{
+ "module", protocol::ModuleEventBody{
+ std::move(p_module).value(),
+ protocol::ModuleEventBody::eReasonRemoved}});
+ } else if (module_exists) {
+ dap->Send(protocol::Event{
+ "module", protocol::ModuleEventBody{
+ std::move(p_module).value(),
+ protocol::ModuleEventBody::eReasonChanged}});
+ } else if (!remove_module) {
+ dap->modules.insert(module_id);
+ dap->Send(protocol::Event{
+ "module",
+ protocol::ModuleEventBody{std::move(p_module).value(),
+ protocol::ModuleEventBody::eReasonNew}});
+ }
+ }
+ } else if (event_mask & lldb::SBTarget::eBroadcastBitNewTargetCreated) {
+ // For NewTargetCreated events, GetTargetFromEvent returns the parent
+ // target, and GetCreatedTargetFromEvent returns the newly created target.
+ lldb::SBTarget created_target =
+ lldb::SBTarget::GetCreatedTargetFromEvent(event);
+
+ if (!target.IsValid() || !created_target.IsValid()) {
+ DAP_LOG(log, "Received NewTargetCreated event but parent or "
+ "created target is invalid");
+ return;
+ }
+
+ // Send a startDebugging reverse request with the debugger and target
+ // IDs. The new DAP instance will use these IDs to find the existing
+ // debugger and target via FindDebuggerWithID and
+ // FindTargetByGloballyUniqueID.
+ llvm::json::Object configuration;
+ configuration.try_emplace("type", "lldb");
+ configuration.try_emplace("debuggerId",
+ created_target.GetDebugger().GetID());
+ configuration.try_emplace("targetId", created_target.GetGloballyUniqueID());
+ configuration.try_emplace("name", created_target.GetTargetSessionName());
+
+ llvm::json::Object request;
+ request.try_emplace("request", "attach");
+ request.try_emplace("configuration", std::move(configuration));
+
+ dap->SendReverseRequest<LogFailureResponseHandler>("startDebugging",
+ std::move(request));
+ }
+}
+
+void HandleBreakpointEvent(const lldb::SBEvent &event, Log *log) {
+ const uint32_t event_mask = event.GetType();
+ if (!(event_mask & lldb::SBTarget::eBroadcastBitBreakpointChanged))
+ return;
+
+ lldb::SBBreakpoint bp = lldb::SBBreakpoint::GetBreakpointFromEvent(event);
+ if (!bp.IsValid())
+ return;
+
+ // Find the DAP instance that owns this breakpoint's target.
+ DAP *dap = DAPSessionManager::FindDAP(bp.GetTarget());
+ if (!dap) {
+ DAP_LOG(log, "Unable to find DAP instance for breakpoint");
+ return;
+ }
+
+ auto event_type = lldb::SBBreakpoint::GetBreakpointEventTypeFromEvent(event);
+ auto breakpoint = Breakpoint(*dap, bp);
+ // If the breakpoint was set through DAP, it will have the
+ // BreakpointBase::kDAPBreakpointLabel. Regardless of whether
+ // locations were added, removed, or resolved, the breakpoint isn't
+ // going away and the reason is always "changed".
+ if ((event_type & lldb::eBreakpointEventTypeLocationsAdded ||
+ event_type & lldb::eBreakpointEventTypeLocationsRemoved ||
+ event_type & lldb::eBreakpointEventTypeLocationsResolved) &&
+ breakpoint.MatchesName(BreakpointBase::kDAPBreakpointLabel)) {
+ // As the DAP client already knows the path of this breakpoint, we
+ // don't need to send it back as part of the "changed" event. This
+ // avoids sending paths that should be source mapped. Note that
+ // CreateBreakpoint doesn't apply source mapping and certain
+ // implementation ignore the source part of this event anyway.
+ protocol::Breakpoint protocol_bp = breakpoint.ToProtocolBreakpoint();
+
+ // "source" is not needed here, unless we add adapter data to be
+ // saved by the client.
+ if (protocol_bp.source && !protocol_bp.source->adapterData)
+ protocol_bp.source = std::nullopt;
+
+ llvm::json::Object body;
+ body.try_emplace("breakpoint", protocol_bp);
+ body.try_emplace("reason", "changed");
+
+ llvm::json::Object bp_event = CreateEventObject("breakpoint");
+ bp_event.try_emplace("body", std::move(body));
+
+ dap->SendJSON(llvm::json::Value(std::move(bp_event)));
+ }
+}
+
+void HandleThreadEvent(const lldb::SBEvent &event, Log *log) {
+ uint32_t event_type = event.GetType();
+
+ if (!(event_type & lldb::SBThread::eBroadcastBitStackChanged))
+ return;
+
+ lldb::SBThread thread = lldb::SBThread::GetThreadFromEvent(event);
+ if (!thread.IsValid())
+ return;
+
+ // Find the DAP instance that owns this thread's process/target.
+ DAP *dap = DAPSessionManager::FindDAP(thread.GetProcess().GetTarget());
+ if (!dap) {
+ DAP_LOG(log, "Unable to find DAP instance for thread");
+ return;
+ }
+
+ SendInvalidatedEvent(*dap, {protocol::InvalidatedEventBody::eAreaStacks},
+ thread.GetThreadID());
+}
+
+void HandleDiagnosticEvent(const lldb::SBEvent &event, Log *log) {
+ // Global debugger events - send to all DAP instances.
+ std::vector<DAP *> active_instances =
+ DAPSessionManager::GetInstance().GetActiveSessions();
+ for (DAP *dap_instance : active_instances) {
+ if (!dap_instance)
+ continue;
+
+ lldb::SBStructuredData data =
+ lldb::SBDebugger::GetDiagnosticFromEvent(event);
+ if (!data.IsValid())
+ continue;
+
+ std::string type = GetStringValue(data.GetValueForKey("type"));
+ std::string message = GetStringValue(data.GetValueForKey("message"));
+ dap_instance->SendOutput(OutputType::Important,
+ llvm::formatv("{0}: {1}", type, message).str());
+ }
+}
+
+// Note: EventThread() is architecturally
diff erent from the other functions in
+// this file. While the functions above are event helpers that operate on a
+// single DAP instance (taking `DAP &dap` as a parameter), EventThread() is a
+// shared event processing loop that:
+// 1. Listens to events from a shared debugger instance
+// 2. Dispatches events to the appropriate handler, which internally finds the
+// DAP instance using DAPSessionManager::FindDAP()
+// 3. Handles events for multiple
diff erent DAP sessions
+// This allows multiple DAP sessions to share a single debugger and event
+// thread, which is essential for the target handoff mechanism where child
+// processes/targets are debugged in separate DAP sessions.
+//
+// All events from the debugger, target, process, thread and frames are
+// received in this function that runs in its own thread. We are using a
+// "FILE *" to output packets back to VS Code and they have mutexes in them
+// them prevent multiple threads from writing simultaneously so no locking
+// is required.
+void EventThread(lldb::SBDebugger debugger, lldb::SBBroadcaster broadcaster,
+ llvm::StringRef client_name, Log *log) {
+ llvm::set_thread_name("lldb.DAP.client." + client_name + ".event_handler");
+ lldb::SBListener listener = debugger.GetListener();
+ broadcaster.AddListener(listener, eBroadcastBitStopEventThread);
+ debugger.GetBroadcaster().AddListener(
+ listener, lldb::eBroadcastBitError | lldb::eBroadcastBitWarning);
+
+ // listen for thread events.
+ listener.StartListeningForEventClass(
+ debugger, lldb::SBThread::GetBroadcasterClassName(),
+ lldb::SBThread::eBroadcastBitStackChanged);
+
+ lldb::SBEvent event;
+ bool done = false;
+ while (!done) {
+ if (!listener.WaitForEvent(UINT32_MAX, event))
+ continue;
+
+ const uint32_t event_mask = event.GetType();
+ if (lldb::SBProcess::EventIsProcessEvent(event)) {
+ HandleProcessEvent(event, /*&process_exited=*/done, log);
+ } else if (lldb::SBTarget::EventIsTargetEvent(event)) {
+ HandleTargetEvent(event, log);
+ } else if (lldb::SBBreakpoint::EventIsBreakpointEvent(event)) {
+ HandleBreakpointEvent(event, log);
+ } else if (lldb::SBThread::EventIsThreadEvent(event)) {
+ HandleThreadEvent(event, log);
+ } else if (event_mask & lldb::eBroadcastBitError ||
+ event_mask & lldb::eBroadcastBitWarning) {
+ HandleDiagnosticEvent(event, log);
+ } else if (event.BroadcasterMatchesRef(broadcaster)) {
+ if (event_mask & eBroadcastBitStopEventThread) {
+ done = true;
+ }
+ }
+ }
+}
+
} // namespace lldb_dap
diff --git a/lldb/tools/lldb-dap/EventHelper.h b/lldb/tools/lldb-dap/EventHelper.h
index be783d032a5ae..3beba2629b2e3 100644
--- a/lldb/tools/lldb-dap/EventHelper.h
+++ b/lldb/tools/lldb-dap/EventHelper.h
@@ -42,6 +42,26 @@ void SendInvalidatedEvent(
void SendMemoryEvent(DAP &dap, lldb::SBValue variable);
+/// Event thread function that handles debugger events for multiple DAP sessions
+/// sharing the same debugger instance. This runs in its own thread and
+/// dispatches events to the appropriate DAP instance.
+///
+/// \param debugger The debugger instance to listen for events from.
+/// \param broadcaster The broadcaster for stop event thread notifications.
+/// \param client_name The client name for thread naming/logging purposes.
+/// \param log The log instance for logging.
+void EventThread(lldb::SBDebugger debugger, lldb::SBBroadcaster broadcaster,
+ llvm::StringRef client_name, Log *log);
+
+/// Event handler functions called by EventThread.
+/// These handlers extract the necessary objects from events and find the
+/// appropriate DAP instance to handle them.
+void HandleProcessEvent(const lldb::SBEvent &event, bool &done, Log *log);
+void HandleTargetEvent(const lldb::SBEvent &event, Log *log);
+void HandleBreakpointEvent(const lldb::SBEvent &event, Log *log);
+void HandleThreadEvent(const lldb::SBEvent &event, Log *log);
+void HandleDiagnosticEvent(const lldb::SBEvent &event, Log *log);
+
} // namespace lldb_dap
#endif
diff --git a/lldb/tools/lldb-dap/Handler/AttachRequestHandler.cpp b/lldb/tools/lldb-dap/Handler/AttachRequestHandler.cpp
index 490513fe8a0b8..24c0ca2111f40 100644
--- a/lldb/tools/lldb-dap/Handler/AttachRequestHandler.cpp
+++ b/lldb/tools/lldb-dap/Handler/AttachRequestHandler.cpp
@@ -17,6 +17,7 @@
#include "lldb/lldb-defines.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
+#include <cstdint>
using namespace llvm;
using namespace lldb_dap::protocol;
@@ -29,14 +30,31 @@ namespace lldb_dap {
/// Since attaching is debugger/runtime specific, the arguments for this request
/// are not part of this specification.
Error AttachRequestHandler::Run(const AttachRequestArguments &args) const {
+ // Initialize DAP debugger and related components if not sharing previously
+ // launched debugger.
+ std::optional<int> debugger_id = args.debuggerId;
+ std::optional<lldb::user_id_t> target_id = args.targetId;
+
+ // Validate that both debugger_id and target_id are provided together.
+ if (debugger_id.has_value() != target_id.has_value()) {
+ return llvm::createStringError(
+ "Both debuggerId and targetId must be specified together for debugger "
+ "reuse, or both must be omitted to create a new debugger");
+ }
+
+ if (Error err = debugger_id && target_id
+ ? dap.InitializeDebugger(*debugger_id, *target_id)
+ : dap.InitializeDebugger())
+ return err;
+
// Validate that we have a well formed attach request.
if (args.attachCommands.empty() && args.coreFile.empty() &&
args.configuration.program.empty() &&
args.pid == LLDB_INVALID_PROCESS_ID &&
- args.gdbRemotePort == LLDB_DAP_INVALID_PORT)
+ args.gdbRemotePort == LLDB_DAP_INVALID_PORT && !target_id.has_value())
return make_error<DAPError>(
"expected one of 'pid', 'program', 'attachCommands', "
- "'coreFile' or 'gdb-remote-port' to be specified");
+ "'coreFile', 'gdb-remote-port', or target_id to be specified");
// Check if we have mutually exclusive arguments.
if ((args.pid != LLDB_INVALID_PROCESS_ID) &&
@@ -64,7 +82,18 @@ Error AttachRequestHandler::Run(const AttachRequestArguments &args) const {
dap.ConfigureSourceMaps();
lldb::SBError error;
- lldb::SBTarget target = dap.CreateTarget(error);
+ lldb::SBTarget target;
+ if (target_id) {
+ // Use the unique target ID to get the target.
+ target = dap.debugger.FindTargetByGloballyUniqueID(*target_id);
+ if (!target.IsValid()) {
+ error.SetErrorStringWithFormat("invalid target_id %lu in attach config",
+ *target_id);
+ }
+ } else {
+ target = dap.CreateTarget(error);
+ }
+
if (error.Fail())
return ToError(error);
@@ -114,7 +143,7 @@ Error AttachRequestHandler::Run(const AttachRequestArguments &args) const {
connect_url += std::to_string(args.gdbRemotePort);
dap.target.ConnectRemote(listener, connect_url.c_str(), "gdb-remote",
error);
- } else {
+ } else if (!target_id.has_value()) {
// Attach by pid or process name.
lldb::SBAttachInfo attach_info;
if (args.pid != LLDB_INVALID_PROCESS_ID)
diff --git a/lldb/tools/lldb-dap/Handler/InitializeRequestHandler.cpp b/lldb/tools/lldb-dap/Handler/InitializeRequestHandler.cpp
index 9069de4a3a690..53e1810a5b0e0 100644
--- a/lldb/tools/lldb-dap/Handler/InitializeRequestHandler.cpp
+++ b/lldb/tools/lldb-dap/Handler/InitializeRequestHandler.cpp
@@ -21,63 +21,9 @@ using namespace lldb_dap::protocol;
/// Initialize request; value of command field is 'initialize'.
llvm::Expected<InitializeResponse> InitializeRequestHandler::Run(
const InitializeRequestArguments &arguments) const {
+ // Store initialization arguments for later use in Launch/Attach.
dap.clientFeatures = arguments.supportedFeatures;
-
- // Do not source init files until in/out/err are configured.
- dap.debugger = lldb::SBDebugger::Create(false);
- dap.debugger.SetInputFile(dap.in);
- dap.target = dap.debugger.GetDummyTarget();
-
- llvm::Expected<int> out_fd = dap.out.GetWriteFileDescriptor();
- if (!out_fd)
- return out_fd.takeError();
- dap.debugger.SetOutputFile(lldb::SBFile(*out_fd, "w", false));
-
- llvm::Expected<int> err_fd = dap.err.GetWriteFileDescriptor();
- if (!err_fd)
- return err_fd.takeError();
- dap.debugger.SetErrorFile(lldb::SBFile(*err_fd, "w", false));
-
- auto interp = dap.debugger.GetCommandInterpreter();
-
- // The sourceInitFile option is not part of the DAP specification. It is an
- // extension used by the test suite to prevent sourcing `.lldbinit` and
- // changing its behavior. The CLI flag --no-lldbinit takes precedence over
- // the DAP parameter.
- bool should_source_init_files =
- !dap.no_lldbinit && arguments.lldbExtSourceInitFile.value_or(true);
- if (should_source_init_files) {
- dap.debugger.SkipLLDBInitFiles(false);
- dap.debugger.SkipAppInitFiles(false);
- lldb::SBCommandReturnObject init;
- interp.SourceInitFileInGlobalDirectory(init);
- interp.SourceInitFileInHomeDirectory(init);
- }
-
- if (llvm::Error err = dap.RunPreInitCommands())
- return err;
-
- auto cmd = dap.debugger.GetCommandInterpreter().AddMultiwordCommand(
- "lldb-dap", "Commands for managing lldb-dap.");
- if (arguments.supportedFeatures.contains(
- eClientFeatureStartDebuggingRequest)) {
- cmd.AddCommand(
- "start-debugging", new StartDebuggingCommand(dap),
- "Sends a startDebugging request from the debug adapter to the client "
- "to start a child debug session of the same type as the caller.");
- }
- cmd.AddCommand(
- "repl-mode", new ReplModeCommand(dap),
- "Get or set the repl behavior of lldb-dap evaluation requests.");
- cmd.AddCommand("send-event", new SendEventCommand(dap),
- "Sends an DAP event to the client.");
-
- if (arguments.supportedFeatures.contains(eClientFeatureProgressReporting))
- dap.StartProgressEventThread();
-
- // Start our event thread so we can receive events from the debugger, target,
- // process and more.
- dap.StartEventThread();
+ dap.sourceInitFile = arguments.lldbExtSourceInitFile.value_or(true);
return dap.GetCapabilities();
}
diff --git a/lldb/tools/lldb-dap/Handler/LaunchRequestHandler.cpp b/lldb/tools/lldb-dap/Handler/LaunchRequestHandler.cpp
index 553cbeaf849e2..329f0a7bf6453 100644
--- a/lldb/tools/lldb-dap/Handler/LaunchRequestHandler.cpp
+++ b/lldb/tools/lldb-dap/Handler/LaunchRequestHandler.cpp
@@ -22,6 +22,10 @@ namespace lldb_dap {
/// Launch request; value of command field is 'launch'.
Error LaunchRequestHandler::Run(const LaunchRequestArguments &arguments) const {
+ // Initialize DAP debugger.
+ if (Error err = dap.InitializeDebugger())
+ return err;
+
// Validate that we have a well formed launch request.
if (!arguments.launchCommands.empty() &&
arguments.console != protocol::eConsoleInternal)
diff --git a/lldb/tools/lldb-dap/Protocol/ProtocolRequests.cpp b/lldb/tools/lldb-dap/Protocol/ProtocolRequests.cpp
index ac01cfb95dd41..d53a520ade39b 100644
--- a/lldb/tools/lldb-dap/Protocol/ProtocolRequests.cpp
+++ b/lldb/tools/lldb-dap/Protocol/ProtocolRequests.cpp
@@ -317,7 +317,9 @@ bool fromJSON(const json::Value &Params, AttachRequestArguments &ARA,
O.mapOptional("waitFor", ARA.waitFor) &&
O.mapOptional("gdb-remote-port", ARA.gdbRemotePort) &&
O.mapOptional("gdb-remote-hostname", ARA.gdbRemoteHostname) &&
- O.mapOptional("coreFile", ARA.coreFile);
+ O.mapOptional("coreFile", ARA.coreFile) &&
+ O.mapOptional("targetId", ARA.targetId) &&
+ O.mapOptional("debuggerId", ARA.debuggerId);
}
bool fromJSON(const json::Value &Params, ContinueArguments &CA, json::Path P) {
diff --git a/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h b/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h
index c1e1e93f1e44a..37fc2465f6a05 100644
--- a/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h
+++ b/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h
@@ -350,6 +350,12 @@ struct AttachRequestArguments {
/// Path to the core file to debug.
std::string coreFile;
+ /// Unique ID of an existing target to attach to.
+ std::optional<lldb::user_id_t> targetId;
+
+ /// ID of an existing debugger instance to use.
+ std::optional<int> debuggerId;
+
/// @}
};
bool fromJSON(const llvm::json::Value &, AttachRequestArguments &,
diff --git a/lldb/tools/lldb-dap/package.json b/lldb/tools/lldb-dap/package.json
index 05dce285dd592..8e07c550b88c3 100644
--- a/lldb/tools/lldb-dap/package.json
+++ b/lldb/tools/lldb-dap/package.json
@@ -778,6 +778,10 @@
"description": "Custom commands that are executed instead of attaching to a process ID or to a process by name. These commands may optionally create a new target and must perform an attach. A valid process must exist after these commands complete or the \"attach\" will fail.",
"default": []
},
+ "targetId": {
+ "type": "number",
+ "description": "The globally unique target id to attach to. Used when a target is dynamically created."
+ },
"initCommands": {
"type": "array",
"items": {
diff --git a/lldb/tools/lldb-dap/tool/lldb-dap.cpp b/lldb/tools/lldb-dap/tool/lldb-dap.cpp
index f10ed12344cbd..27516b2a25678 100644
--- a/lldb/tools/lldb-dap/tool/lldb-dap.cpp
+++ b/lldb/tools/lldb-dap/tool/lldb-dap.cpp
@@ -445,12 +445,8 @@ static llvm::Error serveConnection(
g_connection_timeout_time_point,
connection_timeout_seconds.value());
std::condition_variable dap_sessions_condition;
- std::mutex dap_sessions_mutex;
- std::map<MainLoop *, DAP *> dap_sessions;
unsigned int clientCount = 0;
- auto handle = listener->Accept(g_loop, [=, &dap_sessions_condition,
- &dap_sessions_mutex, &dap_sessions,
- &clientCount](
+ auto handle = listener->Accept(g_loop, [=, &clientCount](
std::unique_ptr<Socket> sock) {
// Reset the keep alive timer, because we won't be killing the server
// while this connection is being served.
@@ -464,8 +460,7 @@ static llvm::Error serveConnection(
// Move the client into a background thread to unblock accepting the next
// client.
- std::thread client([=, &dap_sessions_condition, &dap_sessions_mutex,
- &dap_sessions]() {
+ std::thread client([=]() {
llvm::set_thread_name(client_name + ".runloop");
MainLoop loop;
Transport transport(client_name, log, io, io);
@@ -478,10 +473,8 @@ static llvm::Error serveConnection(
return;
}
- {
- std::scoped_lock<std::mutex> lock(dap_sessions_mutex);
- dap_sessions[&loop] = &dap;
- }
+ // Register the DAP session with the global manager.
+ DAPSessionManager::GetInstance().RegisterSession(&loop, &dap);
if (auto Err = dap.Loop()) {
llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(),
@@ -490,10 +483,8 @@ static llvm::Error serveConnection(
}
DAP_LOG(log, "({0}) client disconnected", client_name);
- std::unique_lock<std::mutex> lock(dap_sessions_mutex);
- dap_sessions.erase(&loop);
- std::notify_all_at_thread_exit(dap_sessions_condition, std::move(lock));
-
+ // Unregister the DAP session from the global manager.
+ DAPSessionManager::GetInstance().UnregisterSession(&loop);
// Start the countdown to kill the server at the end of each connection.
if (connection_timeout_seconds)
TrackConnectionTimeout(g_loop, g_connection_timeout_mutex,
@@ -516,29 +507,11 @@ static llvm::Error serveConnection(
log,
"lldb-dap server shutdown requested, disconnecting remaining clients...");
- bool client_failed = false;
- {
- std::scoped_lock<std::mutex> lock(dap_sessions_mutex);
- for (auto [loop, dap] : dap_sessions) {
- if (llvm::Error error = dap->Disconnect()) {
- client_failed = true;
- llvm::WithColor::error() << "DAP client disconnected failed: "
- << llvm::toString(std::move(error)) << "\n";
- }
- loop->AddPendingCallback(
- [](MainLoopBase &loop) { loop.RequestTermination(); });
- }
- }
-
- // Wait for all clients to finish disconnecting.
- std::unique_lock<std::mutex> lock(dap_sessions_mutex);
- dap_sessions_condition.wait(lock, [&] { return dap_sessions.empty(); });
-
- if (client_failed)
- return llvm::make_error<llvm::StringError>(
- "disconnecting all clients failed", llvm::inconvertibleErrorCode());
+ // Disconnect all active sessions using the global manager.
+ DAPSessionManager::GetInstance().DisconnectAllSessions();
- return llvm::Error::success();
+ // Wait for all clients to finish disconnecting and return any errors.
+ return DAPSessionManager::GetInstance().WaitForAllSessionsToDisconnect();
}
int main(int argc, char *argv[]) {
@@ -775,6 +748,10 @@ int main(int argc, char *argv[]) {
return EXIT_FAILURE;
}
+ // Register the DAP session with the global manager for stdio mode.
+ // This is needed for the event handling to find the correct DAP instance.
+ DAPSessionManager::GetInstance().RegisterSession(&loop, &dap);
+
// used only by TestVSCode_redirection_to_console.py
if (getenv("LLDB_DAP_TEST_STDOUT_STDERR_REDIRECTION") != nullptr)
redirection_test();
@@ -784,7 +761,9 @@ int main(int argc, char *argv[]) {
llvm::toStringWithoutConsuming(Err));
llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(),
"DAP session error: ");
+ DAPSessionManager::GetInstance().UnregisterSession(&loop);
return EXIT_FAILURE;
}
+ DAPSessionManager::GetInstance().UnregisterSession(&loop);
return EXIT_SUCCESS;
}
diff --git a/lldb/unittests/DAP/CMakeLists.txt b/lldb/unittests/DAP/CMakeLists.txt
index a478cf07eedb2..0f8e9db2fab31 100644
--- a/lldb/unittests/DAP/CMakeLists.txt
+++ b/lldb/unittests/DAP/CMakeLists.txt
@@ -1,6 +1,7 @@
add_lldb_unittest(DAPTests
ClientLauncherTest.cpp
DAPErrorTest.cpp
+ DAPSessionManagerTest.cpp
DAPTest.cpp
DAPTypesTest.cpp
FifoFilesTest.cpp
diff --git a/lldb/unittests/DAP/DAPSessionManagerTest.cpp b/lldb/unittests/DAP/DAPSessionManagerTest.cpp
new file mode 100644
index 0000000000000..b840d31ef116d
--- /dev/null
+++ b/lldb/unittests/DAP/DAPSessionManagerTest.cpp
@@ -0,0 +1,103 @@
+//===-- DAPSessionManagerTest.cpp ----------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "DAPSessionManager.h"
+#include "TestBase.h"
+#include "lldb/API/SBDebugger.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace lldb_dap;
+using namespace lldb;
+using namespace lldb_dap_tests;
+
+class DAPSessionManagerTest : public DAPTestBase {};
+
+TEST_F(DAPSessionManagerTest, GetInstanceReturnsSameSingleton) {
+ DAPSessionManager &instance1 = DAPSessionManager::GetInstance();
+ DAPSessionManager &instance2 = DAPSessionManager::GetInstance();
+
+ EXPECT_EQ(&instance1, &instance2);
+}
+
+// UnregisterSession uses std::notify_all_at_thread_exit, so it must be called
+// from a separate thread to properly release the mutex on thread exit.
+TEST_F(DAPSessionManagerTest, RegisterAndUnregisterSession) {
+ DAPSessionManager &manager = DAPSessionManager::GetInstance();
+
+ // Initially not registered.
+ std::vector<DAP *> sessions_before = manager.GetActiveSessions();
+ EXPECT_EQ(
+ std::count(sessions_before.begin(), sessions_before.end(), dap.get()), 0);
+
+ manager.RegisterSession(&loop, dap.get());
+
+ // Should be in active sessions after registration.
+ std::vector<DAP *> sessions_after = manager.GetActiveSessions();
+ EXPECT_EQ(std::count(sessions_after.begin(), sessions_after.end(), dap.get()),
+ 1);
+
+ // Unregister.
+ std::thread unregister_thread([&]() { manager.UnregisterSession(&loop); });
+
+ unregister_thread.join();
+
+ // There should no longer be active sessions.
+ std::vector<DAP *> sessions_final = manager.GetActiveSessions();
+ EXPECT_EQ(std::count(sessions_final.begin(), sessions_final.end(), dap.get()),
+ 0);
+}
+
+TEST_F(DAPSessionManagerTest, DisconnectAllSessions) {
+ DAPSessionManager &manager = DAPSessionManager::GetInstance();
+
+ manager.RegisterSession(&loop, dap.get());
+
+ std::vector<DAP *> sessions = manager.GetActiveSessions();
+ EXPECT_EQ(std::count(sessions.begin(), sessions.end(), dap.get()), 1);
+
+ manager.DisconnectAllSessions();
+
+ // DisconnectAllSessions shutdown but doesn't wait for
+ // sessions to complete or remove them from the active sessions map.
+ sessions = manager.GetActiveSessions();
+ EXPECT_EQ(std::count(sessions.begin(), sessions.end(), dap.get()), 1);
+
+ std::thread unregister_thread([&]() { manager.UnregisterSession(&loop); });
+ unregister_thread.join();
+}
+
+TEST_F(DAPSessionManagerTest, WaitForAllSessionsToDisconnect) {
+ DAPSessionManager &manager = DAPSessionManager::GetInstance();
+
+ manager.RegisterSession(&loop, dap.get());
+
+ std::vector<DAP *> sessions = manager.GetActiveSessions();
+ EXPECT_EQ(std::count(sessions.begin(), sessions.end(), dap.get()), 1);
+
+ // Unregister after a delay to test blocking behavior.
+ std::thread unregister_thread([&]() {
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ manager.UnregisterSession(&loop);
+ });
+
+ // WaitForAllSessionsToDisconnect should block until unregistered.
+ auto start = std::chrono::steady_clock::now();
+ llvm::Error err = manager.WaitForAllSessionsToDisconnect();
+ EXPECT_FALSE(err);
+ auto duration = std::chrono::steady_clock::now() - start;
+
+ // Verify it waited at least 100ms.
+ EXPECT_GE(duration, std::chrono::milliseconds(100));
+
+ // Session should be unregistered now.
+ sessions = manager.GetActiveSessions();
+ EXPECT_EQ(std::count(sessions.begin(), sessions.end(), dap.get()), 0);
+
+ unregister_thread.join();
+}
diff --git a/llvm/utils/gn/secondary/lldb/tools/lldb-dap/BUILD.gn b/llvm/utils/gn/secondary/lldb/tools/lldb-dap/BUILD.gn
index b6c2f465a7292..9c1aa88af7252 100644
--- a/llvm/utils/gn/secondary/lldb/tools/lldb-dap/BUILD.gn
+++ b/llvm/utils/gn/secondary/lldb/tools/lldb-dap/BUILD.gn
@@ -26,6 +26,7 @@ static_library("lib") {
"DAP.cpp",
"DAPError.cpp",
"DAPLog.cpp",
+ "DAPSessionManager.cpp",
"EventHelper.cpp",
"ExceptionBreakpoint.cpp",
"FifoFiles.cpp",
More information about the llvm-commits
mailing list