diff --git a/lldb/include/lldb/API/SBDebugger.h b/lldb/include/lldb/API/SBDebugger.h index f77b0c1d7f0ee..8a9ab760d9e0a 100644 --- a/lldb/include/lldb/API/SBDebugger.h +++ b/lldb/include/lldb/API/SBDebugger.h @@ -359,6 +359,9 @@ class LLDB_API SBDebugger { lldb::SBTarget FindTargetWithFileAndArch(const char *filename, const char *arch); + /// Find a target with the specified unique process ID + lldb::SBTarget FindTargetWithUniqueID(uint32_t id); + /// Get the number of targets in the debugger. uint32_t GetNumTargets(); diff --git a/lldb/include/lldb/API/SBTarget.h b/lldb/include/lldb/API/SBTarget.h index 2776a8f9010fe..d7ea9dc4ac712 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 @@ -69,6 +70,8 @@ class LLDB_API SBTarget { static lldb::SBModule GetModuleAtIndexFromEvent(const uint32_t idx, const lldb::SBEvent &event); + static const char *GetSessionNameFromEvent(const SBEvent &event); + static const char *GetBroadcasterClassName(); lldb::SBProcess GetProcess(); diff --git a/lldb/include/lldb/Target/Target.h b/lldb/include/lldb/Target/Target.h index f07e175a0ca25..00be8c99516b3 100644 --- a/lldb/include/lldb/Target/Target.h +++ b/lldb/include/lldb/Target/Target.h @@ -538,6 +538,7 @@ class Target : public std::enable_shared_from_this, eBroadcastBitWatchpointChanged = (1 << 3), eBroadcastBitSymbolsLoaded = (1 << 4), eBroadcastBitSymbolsChanged = (1 << 5), + eBroadcastBitNewTargetCreated = (1 << 6), }; // These two functions fill out the Broadcaster interface: @@ -557,6 +558,11 @@ class Target : public std::enable_shared_from_this, TargetEventData(const lldb::TargetSP &target_sp, const ModuleList &module_list); + TargetEventData(const lldb::TargetSP &target_sp, std::string session_name); + + TargetEventData(const lldb::TargetSP &target_sp, + const ModuleList &module_list, std::string session_name); + ~TargetEventData() override; static llvm::StringRef GetFlavorString(); @@ -565,6 +571,8 @@ class Target : public std::enable_shared_from_this, return TargetEventData::GetFlavorString(); } + static llvm::StringRef GetSessionNameFromEvent(const Event *event_ptr); + void Dump(Stream *s) const override; static const TargetEventData *GetEventDataFromEvent(const Event *event_ptr); @@ -580,6 +588,7 @@ class Target : public std::enable_shared_from_this, private: lldb::TargetSP m_target_sp; ModuleList m_module_list; + std::string m_session_name = ""; TargetEventData(const TargetEventData &) = delete; const TargetEventData &operator=(const TargetEventData &) = delete; @@ -601,6 +610,12 @@ class Target : public std::enable_shared_from_this, bool IsDummyTarget() const { return m_is_dummy_target; } + /// Get the unique ID for this target. + /// + /// \return + /// The unique ID for this target, or 0 if no ID has been assigned. + uint32_t GetUniqueID() const { return m_target_unique_id; } + const std::string &GetLabel() const { return m_label; } /// Set a label for a target. @@ -1663,6 +1678,7 @@ class Target : public std::enable_shared_from_this, bool m_suppress_stop_hooks; /// Used to not run stop hooks for expressions bool m_is_dummy_target; unsigned m_next_persistent_variable_index = 0; + uint32_t m_target_unique_id = 0; /// The unique ID assigned to this target /// An optional \a lldb_private::Trace object containing processor trace /// information of this target. lldb::TraceSP m_trace_sp; diff --git a/lldb/include/lldb/Target/TargetList.h b/lldb/include/lldb/Target/TargetList.h index 080a6039c7ff8..343fc1676ec30 100644 --- a/lldb/include/lldb/Target/TargetList.h +++ b/lldb/include/lldb/Target/TargetList.h @@ -159,6 +159,8 @@ class TargetList : public Broadcaster { lldb::TargetSP FindTargetWithProcess(lldb_private::Process *process) const; + lldb::TargetSP FindTargetWithUniqueID(uint32_t id) const; + lldb::TargetSP GetTargetSP(Target *target) const; /// Send an async interrupt to one or all processes. diff --git a/lldb/include/lldb/Utility/GPUGDBRemotePackets.h b/lldb/include/lldb/Utility/GPUGDBRemotePackets.h index bf653378ef3b9..264d766fd51c2 100644 --- a/lldb/include/lldb/Utility/GPUGDBRemotePackets.h +++ b/lldb/include/lldb/Utility/GPUGDBRemotePackets.h @@ -182,6 +182,8 @@ struct GPUActions { /// The name of the plugin. std::string plugin_name; + /// The name to give a DAP session + std::string session_name; /// The stop ID in the process that this action is associated with. If the /// wait_for_gpu_process_to_stop is true, this stop ID will be used to wait /// for. If the wait_for_gpu_process_to_resume is set to true it will wait 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 0b09893c7ed5b..12bf51521f491 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 @@ -12,7 +12,7 @@ import sys import threading import time -from typing import Any, Optional, Union, BinaryIO, TextIO +from typing import Any, Dict, Optional, Union, BinaryIO, TextIO ## DAP type references Event = dict[str, Any] @@ -315,8 +315,28 @@ def _handle_recv_packet(self, packet: Optional[ProtocolMessage]) -> bool: elif packet_type == "response": if packet["command"] == "disconnect": keepGoing = False + elif packet_type == "request": + # This is a reverse request automatically spawned from LLDB (eg. for GPU targets) + command = packet.get("command", "unknown") + self.reverse_requests.append(packet) + if command == "startDebugging": + self._handle_startDebugging_request(packet) + else: + desc = f"unhandled automatic reverse request of type {command}" + raise ValueError(desc) + self._enqueue_recv_packet(packet) return keepGoing + + def _handle_startDebugging_request(self, packet): + response = { + "type": "response", + "request_seq": packet["seq"], + "success": True, + "command": "startDebugging", + "body": {} + } + self.send_packet(response, set_sequence=True) def _process_continued(self, all_threads_continued: bool): self.frame_scopes = {} @@ -670,6 +690,7 @@ def request_attach( sourceMap: Optional[Union[list[tuple[str, str]], dict[str, str]]] = None, gdbRemotePort: Optional[int] = None, gdbRemoteHostname: Optional[str] = None, + targetId: Optional[int] = None, ): args_dict = {} if pid is not None: @@ -703,6 +724,8 @@ def request_attach( args_dict["gdb-remote-port"] = gdbRemotePort if gdbRemoteHostname is not None: args_dict["gdb-remote-hostname"] = gdbRemoteHostname + if targetId is not None: + args_dict["targetId"] = targetId command_dict = {"command": "attach", "type": "request", "arguments": args_dict} return self.send_recv(command_dict) @@ -1333,6 +1356,8 @@ def __init__( ): self.process = None self.connection = None + self.child_dap_sessions: Dict[int, "DebugAdapterServer"] = {} # Track child sessions for cleanup + if executable is not None: process, connection = DebugAdapterServer.launch( executable=executable, connection=connection, env=env, log_file=log_file @@ -1414,6 +1439,64 @@ def get_pid(self) -> int: if self.process: return self.process.pid return -1 + + def get_child_sessions(self) -> Dict[int, "DebugAdapterServer"]: + return self.child_dap_sessions + + def _handle_startDebugging_request(self, packet): + """Launch a new DebugAdapterServer with attach config parameters from the packet""" + try: + # Extract arguments from the packet + arguments = packet.get('arguments', {}) + request_type = arguments.get('request', 'attach') # 'attach' or 'launch' + configuration = arguments.get('configuration', {}) + + # Create a new DAP session that launches its own lldb-dap process + child_dap = DebugAdapterServer( + connection=self.connection, + log_file=self.log_file + ) + + # Configure the child session based on the request type and configuration + if request_type == 'attach': + # Initialize the child DAP session + child_dap.request_initialize() + + # Extract attach-specific parameters + attach_commands = configuration.get('attachCommands', []) + target_id = configuration.get('targetId', None) + # Track the child session for proper cleanup + self.child_dap_sessions[target_id] = child_dap + + # Send attach request to the child DAP + child_dap.request_attach( + attachCommands=attach_commands, + targetId=target_id, + ) + else: + raise ValueError(f"Unsupported startDebugging request type: {request_type}") + + # Send success response + response = { + "type": "response", + "request_seq": packet.get("seq", 0), + "success": True, + "command": "startDebugging", + "body": {} + } + + except Exception as e: + # Send error response + response = { + "type": "response", + "request_seq": packet.get("seq", 0), + "success": False, + "command": "startDebugging", + "message": f"Failed to start debugging: {str(e)}", + "body": {} + } + + self.send_packet(response, set_sequence=True) def terminate(self): try: diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py index 1567462839748..7c05234fdde0f 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-dap/lldbdap_testcase.py @@ -35,6 +35,119 @@ def create_debug_adapter( env=lldbDAPEnv, ) + def _get_dap_server(self, child_session_id: Optional[int] = None) -> dap_server.DebugAdapterServer: + """Get a specific DAP server instance. + + Args: + child_session_id: Unique id of child session, or None for main session + + Returns: + The requested DAP server instance + """ + if child_session_id is None: + return self.dap_server + else: + child_sessions = self.dap_server.get_child_sessions() + if child_session_id not in child_sessions: + raise IndexError(f"Child session id {child_session_id} not found.") + return child_sessions[child_session_id] + + def _set_source_breakpoints_impl(self, dap_server_instance, source_path, lines, data=None, wait_for_resolve=True): + """Implementation for setting source breakpoints on any DAP server""" + response = dap_server_instance.request_setBreakpoints(Source(source_path), lines, data) + if response is None or not response["success"]: + return [] + breakpoints = response["body"]["breakpoints"] + breakpoint_ids = [] + for breakpoint in breakpoints: + breakpoint_ids.append("%i" % (breakpoint["id"])) + if wait_for_resolve: + self._wait_for_breakpoints_to_resolve_impl(dap_server_instance, breakpoint_ids) + return breakpoint_ids + + def _wait_for_breakpoints_to_resolve_impl(self, dap_server_instance, breakpoint_ids, timeout=None): + """Implementation for waiting for breakpoints to resolve on any DAP server""" + if timeout is None: + timeout = self.DEFAULT_TIMEOUT + unresolved_breakpoints = dap_server_instance.wait_for_breakpoints_to_be_verified(breakpoint_ids, timeout) + self.assertEqual( + len(unresolved_breakpoints), + 0, + f"Expected to resolve all breakpoints. Unresolved breakpoint ids: {unresolved_breakpoints}", + ) + + def _verify_breakpoint_hit_impl(self, dap_server_instance, breakpoint_ids, timeout=None): + """Implementation for verifying breakpoint hit on any DAP server""" + if timeout is None: + timeout = self.DEFAULT_TIMEOUT + stopped_events = dap_server_instance.wait_for_stopped(timeout) + for stopped_event in stopped_events: + if "body" in stopped_event: + body = stopped_event["body"] + if "reason" not in body: + continue + if ( + body["reason"] != "breakpoint" + and body["reason"] != "instruction breakpoint" + ): + continue + if "description" not in body: + continue + # Descriptions for breakpoints will be in the form + # "breakpoint 1.1", so look for any description that matches + # ("breakpoint 1.") in the description field as verification + # that one of the breakpoint locations was hit. DAP doesn't + # allow breakpoints to have multiple locations, but LLDB does. + # So when looking at the description we just want to make sure + # the right breakpoint matches and not worry about the actual + # location. + description = body["description"] + for breakpoint_id in breakpoint_ids: + match_desc = f"breakpoint {breakpoint_id}." + if match_desc in description: + return + self.assertTrue(False, f"breakpoint not hit, stopped_events={stopped_events}") + + def _do_continue_impl(self, dap_server_instance): + """Implementation for continuing execution on any DAP server""" + resp = dap_server_instance.request_continue() + self.assertTrue(resp["success"], f"continue request failed: {resp}") + + # Multi-session methods for operating on specific sessions without switching context + def set_source_breakpoints_on(self, child_session_id: Optional[int], source_path, lines, data=None, wait_for_resolve=True): + """Set source breakpoints on a specific DAP session without switching the active session.""" + return self._set_source_breakpoints_impl( + self._get_dap_server(child_session_id), source_path, lines, data, wait_for_resolve + ) + + def verify_breakpoint_hit_on(self, child_session_id: Optional[int], breakpoint_ids: list[str], timeout=DEFAULT_TIMEOUT): + """Verify breakpoint hit on a specific DAP session without switching the active session.""" + return self._verify_breakpoint_hit_impl( + self._get_dap_server(child_session_id), breakpoint_ids, timeout + ) + + def do_continue_on(self, child_session_id: Optional[int]): + """Continue execution on a specific DAP session without switching the active session.""" + return self._do_continue_impl(self._get_dap_server(child_session_id)) + + def start_server(self, connection): + """ + Start an lldb-dap server process listening on the specified connection. + """ + log_file_path = self.getBuildArtifact("dap.txt") + (process, connection) = dap_server.DebugAdapterServer.launch( + executable=self.lldbDAPExec, + connection=connection, + log_file=log_file_path + ) + + def cleanup(): + process.terminate() + + self.addTearDownHook(cleanup) + + return (process, connection) + def build_and_create_debug_adapter( self, lldbDAPEnv: Optional[dict[str, str]] = None, @@ -59,18 +172,9 @@ def set_source_breakpoints( Each object in data is 1:1 mapping with the entry in lines. It contains optional location/hitCondition/logMessage parameters. """ - response = self.dap_server.request_setBreakpoints( - Source(source_path), lines, data + return self._set_source_breakpoints_impl( + self.dap_server, source_path, lines, data, wait_for_resolve ) - if response is None or not response["success"]: - return [] - breakpoints = response["body"]["breakpoints"] - breakpoint_ids = [] - for breakpoint in breakpoints: - breakpoint_ids.append("%i" % (breakpoint["id"])) - if wait_for_resolve: - self.wait_for_breakpoints_to_resolve(breakpoint_ids) - return breakpoint_ids def set_source_breakpoints_assembly( self, source_reference, lines, data=None, wait_for_resolve=True @@ -113,13 +217,8 @@ def set_function_breakpoints( def wait_for_breakpoints_to_resolve( self, breakpoint_ids: list[str], timeout: Optional[float] = DEFAULT_TIMEOUT ): - unresolved_breakpoints = self.dap_server.wait_for_breakpoints_to_be_verified( - breakpoint_ids, timeout - ) - self.assertEqual( - len(unresolved_breakpoints), - 0, - f"Expected to resolve all breakpoints. Unresolved breakpoint ids: {unresolved_breakpoints}", + return self._wait_for_breakpoints_to_resolve_impl( + self.dap_server, breakpoint_ids, timeout ) def waitUntil(self, condition_callback): @@ -145,33 +244,7 @@ def verify_breakpoint_hit(self, breakpoint_ids, timeout=DEFAULT_TIMEOUT): "breakpoint_ids" should be a list of breakpoint ID strings (["1", "2"]). The return value from self.set_source_breakpoints() or self.set_function_breakpoints() can be passed to this function""" - stopped_events = self.dap_server.wait_for_stopped(timeout) - for stopped_event in stopped_events: - if "body" in stopped_event: - body = stopped_event["body"] - if "reason" not in body: - continue - if ( - body["reason"] != "breakpoint" - and body["reason"] != "instruction breakpoint" - ): - continue - if "description" not in body: - continue - # Descriptions for breakpoints will be in the form - # "breakpoint 1.1", so look for any description that matches - # ("breakpoint 1.") in the description field as verification - # that one of the breakpoint locations was hit. DAP doesn't - # allow breakpoints to have multiple locations, but LLDB does. - # So when looking at the description we just want to make sure - # the right breakpoint matches and not worry about the actual - # location. - description = body["description"] - for breakpoint_id in breakpoint_ids: - match_desc = f"breakpoint {breakpoint_id}." - if match_desc in description: - return - self.assertTrue(False, f"breakpoint not hit, stopped_events={stopped_events}") + self._verify_breakpoint_hit_impl(self.dap_server, breakpoint_ids, timeout) def verify_all_breakpoints_hit(self, breakpoint_ids, timeout=DEFAULT_TIMEOUT): """Wait for the process we are debugging to stop, and verify we hit @@ -384,8 +457,7 @@ def stepOut(self, threadId=None, waitForStop=True, timeout=DEFAULT_TIMEOUT): return None def do_continue(self): # `continue` is a keyword. - resp = self.dap_server.request_continue() - self.assertTrue(resp["success"], f"continue request failed: {resp}") + self._do_continue_impl(self.dap_server) def continue_to_next_stop(self, timeout=DEFAULT_TIMEOUT): self.do_continue() @@ -478,7 +550,6 @@ def launch( **kwargs, ): """Sending launch request to dap""" - # Make sure we disconnect and terminate the DAP debug adapter, # if we throw an exception during the test case def cleanup(): diff --git a/lldb/source/API/SBDebugger.cpp b/lldb/source/API/SBDebugger.cpp index 603e306497841..f4b46cc3b1873 100644 --- a/lldb/source/API/SBDebugger.cpp +++ b/lldb/source/API/SBDebugger.cpp @@ -983,6 +983,16 @@ uint32_t SBDebugger::GetIndexOfTarget(lldb::SBTarget target) { return m_opaque_sp->GetTargetList().GetIndexOfTarget(target.GetSP()); } +SBTarget SBDebugger::FindTargetWithUniqueID(uint32_t id) { + LLDB_INSTRUMENT_VA(this, id); + SBTarget sb_target; + if (m_opaque_sp) { + // No need to lock, the target list is thread safe + sb_target.SetSP(m_opaque_sp->GetTargetList().FindTargetWithUniqueID(id)); + } + return sb_target; +} + SBTarget SBDebugger::FindTargetWithProcessID(lldb::pid_t pid) { LLDB_INSTRUMENT_VA(this, pid); diff --git a/lldb/source/API/SBTarget.cpp b/lldb/source/API/SBTarget.cpp index f26f7951edc6f..de3dfce85ef86 100644 --- a/lldb/source/API/SBTarget.cpp +++ b/lldb/source/API/SBTarget.cpp @@ -145,6 +145,14 @@ SBModule SBTarget::GetModuleAtIndexFromEvent(const uint32_t idx, return SBModule(module_list.GetModuleAtIndex(idx)); } +const char *SBTarget::GetSessionNameFromEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return ConstString( + Target::TargetEventData::GetSessionNameFromEvent(event.get())) + .AsCString(); +} + const char *SBTarget::GetBroadcasterClassName() { LLDB_INSTRUMENT(); diff --git a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp index d30cf5592fc0b..a63ea7ecce330 100644 --- a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp +++ b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp @@ -1068,6 +1068,10 @@ Status ProcessGDBRemote::HandleConnectionRequest(const GPUActions &gpu_action) { process_sp->GetTarget().shared_from_this()); LLDB_LOG(log, "ProcessGDBRemote::HandleConnectionRequest(): successfully " "created process!!!"); + auto event_sp = std::make_shared( + Target::eBroadcastBitNewTargetCreated, + new Target::TargetEventData(gpu_target_sp, gpu_action.session_name)); + GetTarget().BroadcastEvent(event_sp); return Status(); } diff --git a/lldb/source/Target/Target.cpp b/lldb/source/Target/Target.cpp index 5cffaae349515..b3f75eb26daa1 100644 --- a/lldb/source/Target/Target.cpp +++ b/lldb/source/Target/Target.cpp @@ -191,6 +191,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-spawned"); CheckInWithManager(); @@ -5144,13 +5145,22 @@ void TargetProperties::SetDebugUtilityExpression(bool debug) { } // Target::TargetEventData - Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp) - : EventData(), m_target_sp(target_sp), m_module_list() {} + : TargetEventData(target_sp, ModuleList(), "") {} Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp, const ModuleList &module_list) - : EventData(), m_target_sp(target_sp), m_module_list(module_list) {} + : TargetEventData(target_sp, module_list, "") {} + +Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp, + std::string session_name) + : TargetEventData(target_sp, ModuleList(), std::move(session_name)) {} + +Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp, + const ModuleList &module_list, + std::string session_name) + : EventData(), m_target_sp(target_sp), m_module_list(module_list), + m_session_name(std::move(session_name)) {} Target::TargetEventData::~TargetEventData() = default; @@ -5186,6 +5196,14 @@ TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) { return target_sp; } +llvm::StringRef +Target::TargetEventData::GetSessionNameFromEvent(const Event *event_ptr) { + const TargetEventData *event_data = GetEventDataFromEvent(event_ptr); + if (event_data) + return event_data->m_session_name; + return llvm::StringRef(); +} + ModuleList Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) { ModuleList module_list; diff --git a/lldb/source/Target/TargetList.cpp b/lldb/source/Target/TargetList.cpp index 7037dc2bea3cc..8497cf17e2141 100644 --- a/lldb/source/Target/TargetList.cpp +++ b/lldb/source/Target/TargetList.cpp @@ -176,7 +176,7 @@ Status TargetList::CreateTargetInternal( module_spec.GetArchitecture() = arch; if (module_specs.FindMatchingModuleSpec(module_spec, matching_module_spec)) - update_platform_arch(matching_module_spec.GetArchitecture()); + update_platform_arch(matching_module_spec.GetArchitecture()); } else { // Fat binary. No architecture specified, check if there is // only one platform for all of the architectures. @@ -256,6 +256,9 @@ Status TargetList::CreateTargetInternal(Debugger &debugger, Status error; const bool is_dummy_target = false; + // Global static counter for assigning unique IDs to targets + static uint32_t g_target_unique_id = 0; + ArchSpec arch(specified_arch); if (arch.IsValid()) { @@ -294,7 +297,7 @@ Status TargetList::CreateTargetInternal(Debugger &debugger, if (file.IsRelative() && !user_exe_path.empty()) { llvm::SmallString<64> cwd; - if (! llvm::sys::fs::current_path(cwd)) { + if (!llvm::sys::fs::current_path(cwd)) { FileSpec cwd_file(cwd.c_str()); cwd_file.AppendPathComponent(file); if (FileSystem::Instance().Exists(cwd_file)) @@ -344,6 +347,8 @@ Status TargetList::CreateTargetInternal(Debugger &debugger, if (!target_sp) return error; + target_sp->m_target_unique_id = ++g_target_unique_id; + // Set argv0 with what the user typed, unless the user specified a // directory. If the user specified a directory, then it is probably a // bundle that was resolved and we need to use the resolved bundle path @@ -428,6 +433,18 @@ TargetSP TargetList::FindTargetWithProcess(Process *process) const { return target_sp; } +TargetSP TargetList::FindTargetWithUniqueID(uint32_t id) const { + std::lock_guard guard(m_target_list_mutex); + auto it = llvm::find_if(m_target_list, [id](const TargetSP &item) { + return item->GetUniqueID() == id; + }); + + if (it != m_target_list.end()) + return *it; + + return TargetSP(); +} + TargetSP TargetList::GetTargetSP(Target *target) const { TargetSP target_sp; if (!target) @@ -554,29 +571,27 @@ bool TargetList::AnyTargetContainsModule(Module &module) { if (target_sp->GetImages().FindModule(&module)) return true; } - for (const auto &target_sp: m_in_process_target_list) { + for (const auto &target_sp : m_in_process_target_list) { if (target_sp->GetImages().FindModule(&module)) return true; } return false; } - void TargetList::RegisterInProcessTarget(TargetSP target_sp) { - std::lock_guard guard(m_target_list_mutex); - [[maybe_unused]] bool was_added; - std::tie(std::ignore, was_added) = - m_in_process_target_list.insert(target_sp); - assert(was_added && "Target pointer was left in the in-process map"); - } - - void TargetList::UnregisterInProcessTarget(TargetSP target_sp) { - std::lock_guard guard(m_target_list_mutex); - [[maybe_unused]] bool was_present = - m_in_process_target_list.erase(target_sp); - assert(was_present && "Target pointer being removed was not registered"); - } - - bool TargetList::IsTargetInProcess(TargetSP target_sp) { - std::lock_guard guard(m_target_list_mutex); - return m_in_process_target_list.count(target_sp) == 1; - } +void TargetList::RegisterInProcessTarget(TargetSP target_sp) { + std::lock_guard guard(m_target_list_mutex); + [[maybe_unused]] bool was_added; + std::tie(std::ignore, was_added) = m_in_process_target_list.insert(target_sp); + assert(was_added && "Target pointer was left in the in-process map"); +} + +void TargetList::UnregisterInProcessTarget(TargetSP target_sp) { + std::lock_guard guard(m_target_list_mutex); + [[maybe_unused]] bool was_present = m_in_process_target_list.erase(target_sp); + assert(was_present && "Target pointer being removed was not registered"); +} + +bool TargetList::IsTargetInProcess(TargetSP target_sp) { + std::lock_guard guard(m_target_list_mutex); + return m_in_process_target_list.count(target_sp) == 1; +} diff --git a/lldb/source/Utility/GPUGDBRemotePackets.cpp b/lldb/source/Utility/GPUGDBRemotePackets.cpp index eefc6240ed516..42af9a9d1519a 100644 --- a/lldb/source/Utility/GPUGDBRemotePackets.cpp +++ b/lldb/source/Utility/GPUGDBRemotePackets.cpp @@ -139,6 +139,7 @@ bool fromJSON(const llvm::json::Value &value, GPUActions &data, llvm::json::Path path) { ObjectMapper o(value, path); return o && o.map("plugin_name", data.plugin_name) && + o.map("session_name", data.session_name) && o.mapOptional("stop_id", data.stop_id) && o.map("breakpoints", data.breakpoints) && o.mapOptional("connect_info", data.connect_info) && @@ -153,6 +154,7 @@ bool fromJSON(const llvm::json::Value &value, GPUActions &data, llvm::json::Value toJSON(const GPUActions &data) { return json::Value(Object{ {"plugin_name", data.plugin_name}, + {"session_name", data.session_name}, {"stop_id", data.stop_id}, {"breakpoints", data.breakpoints}, {"connect_info", data.connect_info}, diff --git a/lldb/test/API/tools/lldb-dap/gpu/amd/Makefile b/lldb/test/API/tools/lldb-dap/gpu/amd/Makefile new file mode 100644 index 0000000000000..c3dbfba929f3e --- /dev/null +++ b/lldb/test/API/tools/lldb-dap/gpu/amd/Makefile @@ -0,0 +1,3 @@ +HIP_SOURCES := hello_world.hip + +include Makefile.rules diff --git a/lldb/test/API/tools/lldb-dap/gpu/amd/TestDAP_gpu_reverse_request.py b/lldb/test/API/tools/lldb-dap/gpu/amd/TestDAP_gpu_reverse_request.py new file mode 100644 index 0000000000000..2a6963b9d8d4e --- /dev/null +++ b/lldb/test/API/tools/lldb-dap/gpu/amd/TestDAP_gpu_reverse_request.py @@ -0,0 +1,109 @@ +""" +Test DAP reverse request functionality for GPU debugging. +Tests the changes that allow creating new DAP targets through reverse requests, +specifically for GPU debugging scenarios using AMD HIP. +""" + +import dap_server +import lldbdap_testcase +from subprocess import Popen, PIPE +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + +def _detect_rocm(): + """Detects rocm target.""" + try: + proc = Popen(["rocminfo"], stdout=PIPE, stderr=PIPE) + return "amd" + except Exception: + return None + +def skipUnlessHasROCm(func): + """Decorate the item to skip test unless ROCm is available.""" + + def has_rocm(): + if _detect_rocm() is None: + return "ROCm not available (rocminfo not found)" + return None + + return skipTestIfFn(has_rocm)(func) + + +class TestDAPAMDReverseRequest(lldbdap_testcase.DAPTestCaseBase): + """Test DAP session spawning - both basic and GPU scenarios""" + + def setUp(self): + super().setUp() + + @skipUnlessHasROCm + def test_automatic_reverse_request_detection(self): + """Test that we can detect when LLDB automatically sends reverse requests""" + program = self.getBuildArtifact("a.out") + + # Build and launch with settings that might trigger reverse requests + self.build_and_launch( + program + ) + source = "hello_world.hip" + breakpoint_line = line_number(source, "// CPU BREAKPOINT - BEFORE LAUNCH") + self.set_source_breakpoints(source, [breakpoint_line]) + self.continue_to_next_stop() + + reverse_request_count = len(self.dap_server.reverse_requests) + self.assertEqual(reverse_request_count, 1, "Should have received one reverse request") + # If reverse requests were found, validate them + req = self.dap_server.reverse_requests[0] + self.assertIn("command", req, "Reverse request should have command") + self.assertEqual(req["command"], "startDebugging") + + self.assertIn("arguments", req, "Reverse request should have arguments") + self.assertIn("configuration", req["arguments"], "Reverse request should have configuration") + + attach_config = req["arguments"]["configuration"] + self.assertIn("name", attach_config, "Attach config should have name") + self.assertIn("AMD GPU Session", attach_config["name"]) + self.assertIn("targetId", attach_config, "Attach config should have targetId") + self.assertEqual(attach_config["targetId"], 2, "Attach config should have target id 2") + + @skipUnlessHasROCm + def test_gpu_breakpoint_hit(self): + """ + Test that we can hit a breakpoint in GPU debugging session spawned through reverse requests. + """ + GPU_PROCESS_UNIQUE_ID = 2 + self.build() + log_file_path = self.getBuildArtifact("dap.txt") + # Enable detailed DAP logging to debug any issues + program = self.getBuildArtifact("a.out") + source = "hello_world.hip" + cpu_breakpoint_line = line_number(source, "// CPU BREAKPOINT") + gpu_breakpoint_line = line_number(source, "// GPU BREAKPOINT") + # Launch DAP server + _, connection = self.start_server(connection="listen://localhost:0") + + self.dap_server = dap_server.DebugAdapterServer( + connection=connection, + log_file=log_file_path + ) + self.launch( + program, disconnectAutomatically=False, + ) + + # Set CPU breakpoint and stop. + breakpoint_ids = self.set_source_breakpoints(source, [cpu_breakpoint_line]) + self.continue_to_breakpoints(breakpoint_ids, timeout=self.DEFAULT_TIMEOUT) + # We should have a GPU child session automatically spawned now + self.assertEqual(len(self.dap_server.get_child_sessions()), 1) + # Set breakpoint in GPU session + gpu_breakpoint_ids = self.set_source_breakpoints_on(GPU_PROCESS_UNIQUE_ID, source, [gpu_breakpoint_line]) + # Resume GPU execution after verifying breakpoint hit + self.do_continue_on(GPU_PROCESS_UNIQUE_ID) + # Continue main session + self.do_continue() + # Verify that the GPU breakpoint is hit in the child session + self.verify_breakpoint_hit_on(GPU_PROCESS_UNIQUE_ID, gpu_breakpoint_ids, timeout=self.DEFAULT_TIMEOUT * 3) + + # Manually disconnect sessions + for child_session in self.dap_server.get_child_sessions().values(): + child_session.request_disconnect() + self.dap_server.request_disconnect() diff --git a/lldb/test/API/tools/lldb-dap/gpu/amd/hello_world.hip b/lldb/test/API/tools/lldb-dap/gpu/amd/hello_world.hip new file mode 100644 index 0000000000000..63b1e68e0191d --- /dev/null +++ b/lldb/test/API/tools/lldb-dap/gpu/amd/hello_world.hip @@ -0,0 +1,43 @@ +#include +#include +#include + +constexpr int error_exit_code = -1; + +#define HIP_CHECK(condition) \ + { \ + const hipError_t error = (condition); \ + if (error != hipSuccess) { \ + fprintf(stderr, "HIP error: \"%s\" at %s:%d\n", \ + hipGetErrorString(error), __FILE__, __LINE__); \ + exit(error_exit_code); \ + } \ + } + +__global__ void add_one(int *data) { + int idx = threadIdx.x; + data[idx] = idx + 1; // GPU BREAKPOINT +} + +int main() { + const int n = 4; + int host_data[n] = {0, 0, 0, 0}; + int *device_data; + printf("Starting GPU test...\n"); // CPU BREAKPOINT - BEFORE LAUNCH + // Allocate device memory + HIP_CHECK(hipMalloc(&device_data, n * sizeof(int))); + // Copy data to device + HIP_CHECK(hipMemcpy(device_data, host_data, n * sizeof(int), hipMemcpyHostToDevice)); + // Launch kernel (single block, 4 threads) + add_one<<<1, n>>>(device_data); + // Check for kernel launch errors + HIP_CHECK(hipGetLastError()); + // Wait for GPU to finish + HIP_CHECK(hipDeviceSynchronize()); + // Copy results back to host + HIP_CHECK(hipMemcpy(host_data, device_data, n * sizeof(int), hipMemcpyDeviceToHost)); + printf("Results: %d %d %d %d\n", host_data[0], host_data[1], host_data[2], host_data[3]); // CPU BREAKPOINT - AFTER LAUNCH + // Cleanup + HIP_CHECK(hipFree(device_data)); + return 0; +} diff --git a/lldb/tools/lldb-dap/CMakeLists.txt b/lldb/tools/lldb-dap/CMakeLists.txt index 4cddfb1bea1c2..81f5baabf1cc4 100644 --- a/lldb/tools/lldb-dap/CMakeLists.txt +++ b/lldb/tools/lldb-dap/CMakeLists.txt @@ -12,6 +12,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 cbd3b14463e25..ebb19f11530ba 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" @@ -238,10 +239,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(); @@ -786,7 +789,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); } @@ -1209,13 +1213,89 @@ protocol::Capabilities DAP::GetCapabilities() { } 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); } +llvm::Error DAP::StartEventThreads() { + if (clientFeatures.contains(eClientFeatureProgressReporting)) + StartProgressEventThread(); + + StartEventThread(); + + return llvm::Error::success(); +} + +llvm::Error DAP::InitializeDebugger(std::optional target_id) { + // Initialize debugger instance (shared or individual) + if (target_id) { + auto shared_debugger = + DAPSessionManager::GetInstance().GetSharedDebugger(*target_id); + if (!shared_debugger) { + return llvm::createStringError( + llvm::inconvertibleErrorCode(), + "Unable to find existing debugger for target ID"); + } + debugger = shared_debugger.value(); + return StartEventThreads(); + } + + debugger = lldb::SBDebugger::Create(false); + + // Configure input/output/error file descriptors + debugger.SetInputFile(in); + target = debugger.GetDummyTarget(); + + llvm::Expected out_fd = out.GetWriteFileDescriptor(); + if (!out_fd) + return out_fd.takeError(); + debugger.SetOutputFile(lldb::SBFile(*out_fd, "w", false)); + + llvm::Expected 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. + if (sourceInitFile) { + 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."); + + return StartEventThreads(); +} + void DAP::ProgressEventThread() { lldb::SBListener listener("lldb-dap.progress.listener"); debugger.GetBroadcaster().AddListener( @@ -1294,6 +1374,11 @@ void DAP::EventThread() { const auto event_mask = event.GetType(); if (lldb::SBProcess::EventIsProcessEvent(event)) { lldb::SBProcess process = lldb::SBProcess::GetProcessFromEvent(event); + // Find the DAP instance that owns this process's target + DAP *dap_instance = DAPSessionManager::FindDAP(process.GetTarget()); + if (!dap_instance) + continue; + if (event_mask & lldb::SBProcess::eBroadcastBitStateChanged) { auto state = lldb::SBProcess::GetStateFromEvent(event); switch (state) { @@ -1310,89 +1395,144 @@ void DAP::EventThread() { // 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), + SendStdOutStdErr(*dap_instance, process); + if (llvm::Error err = SendThreadStoppedEvent(*dap_instance)) + DAP_LOG_ERROR(dap_instance->log, std::move(err), "({1}) reporting thread stopped: {0}", - transport.GetClientName()); + dap_instance->transport.GetClientName()); } break; case lldb::eStateRunning: case lldb::eStateStepping: - WillContinue(); - SendContinuedEvent(*this); + dap_instance->WillContinue(); + SendContinuedEvent(*dap_instance); break; case lldb::eStateExited: lldb::SBStream stream; process.GetStatus(stream); - SendOutput(OutputType::Console, stream.GetData()); + dap_instance->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; + process.GetProcessID() == dap_instance->restarting_process_id) { + dap_instance->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(); + dap_instance->RunExitCommands(); + SendProcessExitedEvent(*dap_instance, process); + dap_instance->SendTerminatedEvent(); done = true; } break; } } else if ((event_mask & lldb::SBProcess::eBroadcastBitSTDOUT) || (event_mask & lldb::SBProcess::eBroadcastBitSTDERR)) { - SendStdOutStdErr(*this, process); + SendStdOutStdErr(*dap_instance, process); } } else if (lldb::SBTarget::EventIsTargetEvent(event)) { if (event_mask & lldb::SBTarget::eBroadcastBitModulesLoaded || event_mask & lldb::SBTarget::eBroadcastBitModulesUnloaded || event_mask & lldb::SBTarget::eBroadcastBitSymbolsLoaded || event_mask & lldb::SBTarget::eBroadcastBitSymbolsChanged) { + lldb::SBTarget event_target = + lldb::SBTarget::GetTargetFromEvent(event); + // Find the DAP instance that owns this target + DAP *dap_instance = DAPSessionManager::FindDAP(event_target); + if (!dap_instance) + continue; + const uint32_t num_modules = lldb::SBTarget::GetNumModulesFromEvent(event); const bool remove_module = event_mask & lldb::SBTarget::eBroadcastBitModulesUnloaded; - std::lock_guard guard(modules_mutex); + std::lock_guard guard(dap_instance->modules_mutex); for (uint32_t i = 0; i < num_modules; ++i) { lldb::SBModule module = lldb::SBTarget::GetModuleAtIndexFromEvent(i, event); std::optional p_module = - CreateModule(target, module, remove_module); + CreateModule(dap_instance->target, module, remove_module); if (!p_module) continue; llvm::StringRef module_id = p_module->id; - const bool module_exists = modules.contains(module_id); + const bool module_exists = + dap_instance->modules.contains(module_id); if (remove_module && module_exists) { - modules.erase(module_id); - Send(protocol::Event{ + dap_instance->modules.erase(module_id); + dap_instance->Send(protocol::Event{ "module", ModuleEventBody{std::move(p_module).value(), ModuleEventBody::eReasonRemoved}}); } else if (module_exists) { - Send(protocol::Event{ + dap_instance->Send(protocol::Event{ "module", ModuleEventBody{std::move(p_module).value(), ModuleEventBody::eReasonChanged}}); } else if (!remove_module) { - modules.insert(module_id); - Send(protocol::Event{ + dap_instance->modules.insert(module_id); + dap_instance->Send(protocol::Event{ "module", ModuleEventBody{std::move(p_module).value(), ModuleEventBody::eReasonNew}}); } } + } else if (event_mask & lldb::SBTarget::eBroadcastBitNewTargetCreated) { + auto target = lldb::SBTarget::GetTargetFromEvent(event); + + // Generate unique target ID and set the shared debugger + uint32_t target_id = target.GetProcess().GetUniqueID(); + DAPSessionManager::GetInstance().SetSharedDebugger(target_id, + debugger); + + // We create an attach config that will select the unique + // target ID of the created target. The DAP instance will attach to + // this existing target and the debug session will be ready to go. + llvm::json::Object attach_config; + + // If we have a process name, add command to attach to the same + // process name + attach_config.try_emplace("type", "lldb"); + attach_config.try_emplace("targetId", target_id); + const char *session_name = + lldb::SBTarget::GetSessionNameFromEvent(event); + if (session_name && *session_name) { + attach_config.try_emplace("name", session_name); + } else { + std::string default_name = + llvm::formatv("Session {0}", target_id).str(); + attach_config.try_emplace("name", default_name); + } + + // 2. Construct the main 'startDebugging' request arguments. + llvm::json::Object start_debugging_args{ + {"request", "attach"}, + {"configuration", std::move(attach_config)}}; + + // Send the request. Note that this is a reverse request, so you don't + // expect a direct response in the same way as a client request. + SendReverseRequest( + "startDebugging", std::move(start_debugging_args)); } } else if (lldb::SBBreakpoint::EventIsBreakpointEvent(event)) { + lldb::SBBreakpoint bp = + lldb::SBBreakpoint::GetBreakpointFromEvent(event); + if (!bp.IsValid()) + continue; + + lldb::SBTarget event_target = bp.GetTarget(); + + // Find the DAP instance that owns this target + DAP *dap_instance = DAPSessionManager::FindDAP(event_target); + if (!dap_instance) + continue; + if (event_mask & lldb::SBTarget::eBroadcastBitBreakpointChanged) { auto event_type = lldb::SBBreakpoint::GetBreakpointEventTypeFromEvent(event); - auto bp = Breakpoint( - *this, lldb::SBBreakpoint::GetBreakpointFromEvent(event)); + auto breakpoint = Breakpoint(*dap_instance, 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 @@ -1400,13 +1540,13 @@ void DAP::EventThread() { if ((event_type & lldb::eBreakpointEventTypeLocationsAdded || event_type & lldb::eBreakpointEventTypeLocationsRemoved || event_type & lldb::eBreakpointEventTypeLocationsResolved) && - bp.MatchesName(BreakpointBase::kDAPBreakpointLabel)) { + 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. - llvm::json::Value source_bp = bp.ToProtocolBreakpoint(); + llvm::json::Value source_bp = breakpoint.ToProtocolBreakpoint(); source_bp.getAsObject()->erase("source"); llvm::json::Object body; @@ -1416,19 +1556,29 @@ void DAP::EventThread() { llvm::json::Object bp_event = CreateEventObject("breakpoint"); bp_event.try_emplace("body", std::move(body)); - SendJSON(llvm::json::Value(std::move(bp_event))); + dap_instance->SendJSON(llvm::json::Value(std::move(bp_event))); } } } else if (event_mask & lldb::eBroadcastBitError || event_mask & lldb::eBroadcastBitWarning) { - 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")); - SendOutput(OutputType::Important, - llvm::formatv("{0}: {1}", type, message).str()); + // Global debugger events - send to all DAP instances + std::vector 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()); + } } else if (event.BroadcasterMatchesRef(broadcaster)) { if (event_mask & eBroadcastBitStopEventThread) { done = true; diff --git a/lldb/tools/lldb-dap/DAP.h b/lldb/tools/lldb-dap/DAP.h index af4aabaafaae8..aae86682d0f2c 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" @@ -45,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -77,6 +79,8 @@ enum DAPBroadcasterBits { enum class ReplMode { Variable = 0, Command, Auto }; struct DAP { + friend class DAPSessionManager; + /// Path to the lldb-dap binary itself. static llvm::StringRef debug_adapter_path; @@ -151,6 +155,10 @@ struct DAP { /// The set of features supported by the connected client. llvm::DenseSet clientFeatures; + /// Used by the test suite to prevent sourcing `.lldbinit` and changing its + /// behavior. + bool sourceInitFile = true; + /// The initial thread list upon attaching. std::vector initial_thread_list; @@ -402,6 +410,18 @@ struct DAP { void StartEventThread(); void StartProgressEventThread(); + /// DAP debugger initialization functions + /// @{ + + /// Perform complete DAP initialization in one call + llvm::Error + InitializeDebugger(std::optional target_idx = std::nullopt); + + /// Start event handling threads based on client capabilities + llvm::Error 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`. @@ -438,7 +458,9 @@ struct DAP { void EventThread(); 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 event_thread_sp; std::thread progress_event_thread; /// @} diff --git a/lldb/tools/lldb-dap/DAPSessionManager.cpp b/lldb/tools/lldb-dap/DAPSessionManager.cpp new file mode 100644 index 0000000000000..7395f5b0ad16d --- /dev/null +++ b/lldb/tools/lldb-dap/DAPSessionManager.cpp @@ -0,0 +1,159 @@ +//===-- DAPSessionManager.cpp ----------------------------------*- C++ -*-===// +// +// 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 "lldb/API/SBBroadcaster.h" +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBTarget.h" +#include "llvm/Support/Threading.h" +#include +#include + +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() { + // NOTE: intentional leak to avoid issues with C++ destructor chain + // Use std::call_once for thread-safe initialization + static std::once_flag initialized; + static DAPSessionManager *instance = nullptr; + + std::call_once(initialized, []() { instance = new DAPSessionManager(); }); + + return *instance; +} + +void DAPSessionManager::RegisterSession(lldb::IOObjectSP io, DAP *dap) { + std::lock_guard lock(m_sessions_mutex); + m_active_sessions[io] = dap; +} + +void DAPSessionManager::UnregisterSession(lldb::IOObjectSP io) { + std::unique_lock lock(m_sessions_mutex); + m_active_sessions.erase(io); + + // Clean up shared resources when the last session exits + if (m_active_sessions.empty()) { + CleanupSharedResources(); + } + + std::notify_all_at_thread_exit(m_sessions_condition, std::move(lock)); +} + +std::vector DAPSessionManager::GetActiveSessions() { + std::lock_guard lock(m_sessions_mutex); + std::vector sessions; + for (const auto &[io, dap] : m_active_sessions) { + if (dap) { + sessions.push_back(dap); + } + } + return sessions; +} + +void DAPSessionManager::DisconnectAllSessions() { + std::lock_guard lock(m_sessions_mutex); + for (const auto &[io, dap] : m_active_sessions) { + if (dap) { + if (llvm::Error error = dap->Disconnect()) { + llvm::errs() << "DAP client " << dap->transport.GetClientName() + << " disconnected failed: " + << llvm::toString(std::move(error)) << "\n"; + } + } + } +} + +void DAPSessionManager::WaitForAllSessionsToDisconnect() { + std::unique_lock lock(m_sessions_mutex); + m_sessions_condition.wait(lock, [this] { return m_active_sessions.empty(); }); +} + +std::shared_ptr +DAPSessionManager::GetEventThreadForDebugger(lldb::SBDebugger debugger, + DAP *requesting_dap) { + lldb::user_id_t debugger_id = debugger.GetID(); + std::lock_guard 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 (auto 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( + requesting_dap->broadcaster, + std::thread(&DAP::EventThread, requesting_dap)); + m_debugger_event_threads[debugger_id] = new_thread_sp; + return new_thread_sp; +} + +void DAPSessionManager::SetSharedDebugger(uint32_t target_id, + lldb::SBDebugger debugger) { + std::lock_guard lock(m_sessions_mutex); + m_target_to_debugger_map[target_id] = debugger; +} + +std::optional +DAPSessionManager::GetSharedDebugger(uint32_t target_id) { + std::lock_guard lock(m_sessions_mutex); + auto pos = m_target_to_debugger_map.find(target_id); + if (pos == m_target_to_debugger_map.end()) + return std::nullopt; + lldb::SBDebugger debugger = pos->second; + m_target_to_debugger_map.erase(pos); + return debugger; +} + +DAP *DAPSessionManager::FindDAPForTarget(lldb::SBTarget target) { + std::lock_guard lock(m_sessions_mutex); + + for (const auto &[io, dap] : m_active_sessions) { + if (dap && dap->target.IsValid() && dap->target == target) { + return dap; + } + } + + return nullptr; +} + +void DAPSessionManager::CleanupSharedResources() { + // SBDebugger destructors will handle cleanup when the map entries are + // destroyed + m_target_to_debugger_map.clear(); +} + +void DAPSessionManager::ReleaseExpiredEventThreads() { + std::lock_guard 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..9eb54f2ffa00f --- /dev/null +++ b/lldb/tools/lldb-dap/DAPSessionManager.h @@ -0,0 +1,115 @@ +//===-- DAPSessionManager.h ------------------------------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#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/lldb-types.h" +#include +#include +#include +#include +#include +#include +#include + +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 +class DAPSessionManager { +public: + /// Get the singleton instance of the DAP session manager + static DAPSessionManager &GetInstance(); + + /// Register a DAP session + void RegisterSession(lldb::IOObjectSP io, DAP *dap); + + /// Unregister a DAP session + void UnregisterSession(lldb::IOObjectSP io); + + /// Get all active DAP sessions + std::vector GetActiveSessions(); + + /// Disconnect all active sessions + void DisconnectAllSessions(); + + /// Wait for all sessions to finish disconnecting + void WaitForAllSessionsToDisconnect(); + + /// Set the shared debugger instance for a unique target ID + void SetSharedDebugger(uint32_t target_id, lldb::SBDebugger debugger); + + /// Get the shared debugger instance for a unique target ID + std::optional GetSharedDebugger(uint32_t target_id); + + /// Get or create event thread for a specific debugger + std::shared_ptr + 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 shared resources when the last session exits + void CleanupSharedResources(); + + /// 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; + + std::mutex m_sessions_mutex; + std::condition_variable m_sessions_condition; + std::map m_active_sessions; + + /// Optional map from target ID to shared debugger set when the native + /// process spawns a new GPU target + std::map m_target_to_debugger_map; + + /// Map from debugger ID to its event thread used for when + /// multiple DAP sessions are using the same debugger instance. + std::map> + m_debugger_event_threads; +}; + +} // namespace lldb_dap + +#endif // LLDB_TOOLS_LLDB_DAP_DAPSESSIONMANAGER_H diff --git a/lldb/tools/lldb-dap/Handler/AttachRequestHandler.cpp b/lldb/tools/lldb-dap/Handler/AttachRequestHandler.cpp index 371349a26866e..224af5fee3528 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 using namespace llvm; using namespace lldb_dap::protocol; @@ -29,14 +30,20 @@ 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 target_id = args.targetId; + if (Error err = dap.InitializeDebugger(target_id)) + 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( "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,15 +71,25 @@ 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.FindTargetWithUniqueID(*target_id); + if (!target.IsValid()) { + error.SetErrorStringWithFormat("invalid target_id %u in attach config", + *target_id); + } + } else { + target = dap.CreateTarget(error); + } + if (error.Fail()) return ToError(error); - dap.SetTarget(target); - // Run any pre run LLDB commands the user specified in the launch.json - if (Error err = dap.RunPreRunCommands()) + if (Error err = dap.RunPreRunCommands()) { return err; + } if ((args.pid == LLDB_INVALID_PROCESS_ID || args.gdbRemotePort == LLDB_DAP_INVALID_PORT) && @@ -114,7 +131,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 b499a69876e2c..e4f8f31cb7962 100644 --- a/lldb/tools/lldb-dap/Handler/InitializeRequestHandler.cpp +++ b/lldb/tools/lldb-dap/Handler/InitializeRequestHandler.cpp @@ -21,60 +21,9 @@ using namespace lldb_dap::protocol; /// Initialize request; value of command field is 'initialize'. llvm::Expected 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 out_fd = dap.out.GetWriteFileDescriptor(); - if (!out_fd) - return out_fd.takeError(); - dap.debugger.SetOutputFile(lldb::SBFile(*out_fd, "w", false)); - - llvm::Expected 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. - if (arguments.lldbExtSourceInitFile.value_or(true)) { - 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..fef82dddea909 100644 --- a/lldb/tools/lldb-dap/Handler/LaunchRequestHandler.cpp +++ b/lldb/tools/lldb-dap/Handler/LaunchRequestHandler.cpp @@ -22,6 +22,11 @@ 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 29855ca50e9e0..ccf97f78680fb 100644 --- a/lldb/tools/lldb-dap/Protocol/ProtocolRequests.cpp +++ b/lldb/tools/lldb-dap/Protocol/ProtocolRequests.cpp @@ -315,7 +315,8 @@ 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); } 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 c45ee10e77d1c..fe84c429fa21f 100644 --- a/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h +++ b/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h @@ -345,6 +345,9 @@ struct AttachRequestArguments { /// Path to the core file to debug. std::string coreFile; + /// Unique ID of an existing target to attach to. + std::optional targetId; + /// @} }; bool fromJSON(const llvm::json::Value &, AttachRequestArguments &, diff --git a/lldb/tools/lldb-dap/package.json b/lldb/tools/lldb-dap/package.json index d677a81cc7974..f3b35978adf0f 100644 --- a/lldb/tools/lldb-dap/package.json +++ b/lldb/tools/lldb-dap/package.json @@ -678,6 +678,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": [] }, + "targetIdx": { + "type": "number", + "description": "The index of an existing target to attach to. Used only for child/GPU process debugging." + }, "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 8bba4162aa7bf..b9a4db386a55a 100644 --- a/lldb/tools/lldb-dap/tool/lldb-dap.cpp +++ b/lldb/tools/lldb-dap/tool/lldb-dap.cpp @@ -282,13 +282,8 @@ serveConnection(const Socket::SocketProtocol &protocol, const std::string &name, g_loop.AddPendingCallback( [](MainLoopBase &loop) { loop.RequestTermination(); }); }); - std::condition_variable dap_sessions_condition; - std::mutex dap_sessions_mutex; - std::map 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 sock) { std::string client_name = llvm::formatv("client_{0}", clientCount++).str(); DAP_LOG(log, "({0}) client connected", client_name); @@ -297,8 +292,7 @@ serveConnection(const Socket::SocketProtocol &protocol, const std::string &name, // 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"); Transport transport(client_name, log, io, io); DAP dap(log, default_repl_mode, pre_init_commands, transport); @@ -309,10 +303,8 @@ serveConnection(const Socket::SocketProtocol &protocol, const std::string &name, return; } - { - std::scoped_lock lock(dap_sessions_mutex); - dap_sessions[io.get()] = &dap; - } + // Register the DAP session with the global manager + DAPSessionManager::GetInstance().RegisterSession(io, &dap); if (auto Err = dap.Loop()) { llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), @@ -321,9 +313,8 @@ serveConnection(const Socket::SocketProtocol &protocol, const std::string &name, } DAP_LOG(log, "({0}) client disconnected", client_name); - std::unique_lock lock(dap_sessions_mutex); - dap_sessions.erase(io.get()); - std::notify_all_at_thread_exit(dap_sessions_condition, std::move(lock)); + // Unregister the DAP session from the global manager + DAPSessionManager::GetInstance().UnregisterSession(io); }); client.detach(); }); @@ -341,26 +332,11 @@ serveConnection(const Socket::SocketProtocol &protocol, const std::string &name, log, "lldb-dap server shutdown requested, disconnecting remaining clients..."); - bool client_failed = false; - { - std::scoped_lock lock(dap_sessions_mutex); - for (auto [sock, dap] : dap_sessions) { - if (llvm::Error error = dap->Disconnect()) { - client_failed = true; - llvm::errs() << "DAP client " << dap->transport.GetClientName() - << " disconnected failed: " - << llvm::toString(std::move(error)) << "\n"; - } - } - } + // Disconnect all active sessions using the global manager + DAPSessionManager::GetInstance().DisconnectAllSessions(); // Wait for all clients to finish disconnecting. - std::unique_lock lock(dap_sessions_mutex); - dap_sessions_condition.wait(lock, [&] { return dap_sessions.empty(); }); - - if (client_failed) - return llvm::make_error( - "disconnecting all clients failed", llvm::inconvertibleErrorCode()); + DAPSessionManager::GetInstance().WaitForAllSessionsToDisconnect(); return llvm::Error::success(); } @@ -560,6 +536,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(input, &dap); + // used only by TestVSCode_redirection_to_console.py if (getenv("LLDB_DAP_TEST_STDOUT_STDERR_REDIRECTION") != nullptr) redirection_test(); @@ -569,7 +549,9 @@ int main(int argc, char *argv[]) { llvm::toStringWithoutConsuming(Err)); llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "DAP session error: "); + DAPSessionManager::GetInstance().UnregisterSession(input); return EXIT_FAILURE; } + DAPSessionManager::GetInstance().UnregisterSession(input); return EXIT_SUCCESS; } diff --git a/lldb/tools/lldb-server/Plugins/AMDGPU/LLDBServerPluginAMDGPU.cpp b/lldb/tools/lldb-server/Plugins/AMDGPU/LLDBServerPluginAMDGPU.cpp index 42ef81b80828a..67e9065f2a6bc 100644 --- a/lldb/tools/lldb-server/Plugins/AMDGPU/LLDBServerPluginAMDGPU.cpp +++ b/lldb/tools/lldb-server/Plugins/AMDGPU/LLDBServerPluginAMDGPU.cpp @@ -161,6 +161,10 @@ LLDBServerPluginAMDGPU::~LLDBServerPluginAMDGPU() { } llvm::StringRef LLDBServerPluginAMDGPU::GetPluginName() { return "amd-gpu"; } +llvm::StringRef LLDBServerPluginAMDGPU::GetSessionName() { + return "AMD GPU Session"; +} + Status LLDBServerPluginAMDGPU::InitializeAmdDbgApi() { LLDB_LOGF(GetLog(GDBRLog::Plugin), "%s called", __FUNCTION__); @@ -451,6 +455,7 @@ bool LLDBServerPluginAMDGPU::ReadyToSetGpuLoaderBreakpointByAddress() { GPUActions LLDBServerPluginAMDGPU::SetConnectionInfo() { GPUActions actions; actions.plugin_name = GetPluginName(); + actions.session_name = GetSessionName(); actions.connect_info = CreateConnection(); return actions; } diff --git a/lldb/tools/lldb-server/Plugins/AMDGPU/LLDBServerPluginAMDGPU.h b/lldb/tools/lldb-server/Plugins/AMDGPU/LLDBServerPluginAMDGPU.h index ce62f2e88a1a0..ef36bebc97ee4 100644 --- a/lldb/tools/lldb-server/Plugins/AMDGPU/LLDBServerPluginAMDGPU.h +++ b/lldb/tools/lldb-server/Plugins/AMDGPU/LLDBServerPluginAMDGPU.h @@ -72,6 +72,7 @@ class LLDBServerPluginAMDGPU : public LLDBServerPlugin { void FreeDbgApiClientMemory(void *mem); bool CreateGPUBreakpoint(uint64_t addr); + llvm::StringRef GetSessionName(); void GpuRuntimeDidLoad(); diff --git a/lldb/tools/lldb-server/Plugins/MockGPU/LLDBServerPluginMockGPU.cpp b/lldb/tools/lldb-server/Plugins/MockGPU/LLDBServerPluginMockGPU.cpp index c781e071f94d9..d7149a5eb77e7 100644 --- a/lldb/tools/lldb-server/Plugins/MockGPU/LLDBServerPluginMockGPU.cpp +++ b/lldb/tools/lldb-server/Plugins/MockGPU/LLDBServerPluginMockGPU.cpp @@ -183,6 +183,7 @@ LLDBServerPluginMockGPU::BreakpointWasHit(GPUPluginBreakpointHitArgs &args) { LLDB_LOGF(log, "LLDBServerPluginMockGPU::BreakpointWasHit(%u) disabling breakpoint", bp_identifier); response.actions.connect_info = CreateConnection(); + response.actions.session_name = "Mock GPU Session"; // We asked for the symbol "gpu_shlib_load" to be delivered as a symbol // value when the "gpu_initialize" breakpoint was set. So we will use this 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 30a1e03e3bffa..04650130b1cbc 100644 --- a/llvm/utils/gn/secondary/lldb/tools/lldb-dap/BUILD.gn +++ b/llvm/utils/gn/secondary/lldb/tools/lldb-dap/BUILD.gn @@ -25,6 +25,7 @@ static_library("lib") { "DAP.cpp", "DAPError.cpp", "DAPLog.cpp", + "DAPSessionManager.cpp", "EventHelper.cpp", "ExceptionBreakpoint.cpp", "FifoFiles.cpp",