From 8b79cd751c70d3e8aec78df0cc39e9779493adf1 Mon Sep 17 00:00:00 2001 From: Ebuka Ezike Date: Mon, 16 Jun 2025 11:00:05 +0100 Subject: [PATCH 1/4] [lldb-dap] Fix source references The protocol expects that `sourceReference` be less than `(2^31)-1`, but we currently represent memory address as source reference, this can be truncated either when sending through json or by the client. Instead, generate new source references based on the memory address. Make the `CreateSource` function return an optional source. # Conflicts: # lldb/tools/lldb-dap/Handler/DisassembleRequestHandler.cpp --- .../TestDAP_breakpointAssembly.py | 14 ++--- lldb/tools/lldb-dap/Breakpoint.cpp | 7 ++- lldb/tools/lldb-dap/DAP.cpp | 19 +++++++ lldb/tools/lldb-dap/DAP.h | 7 ++- .../Handler/DisassembleRequestHandler.cpp | 16 +++--- .../Handler/LocationsRequestHandler.cpp | 22 +++++++- .../lldb-dap/Handler/SourceRequestHandler.cpp | 32 +++++++----- .../Handler/StackTraceRequestHandler.cpp | 2 +- lldb/tools/lldb-dap/JSONUtils.cpp | 12 +++-- lldb/tools/lldb-dap/JSONUtils.h | 5 +- .../lldb-dap/Protocol/ProtocolRequests.h | 2 +- .../tools/lldb-dap/Protocol/ProtocolTypes.cpp | 2 +- lldb/tools/lldb-dap/Protocol/ProtocolTypes.h | 3 +- lldb/tools/lldb-dap/ProtocolUtils.cpp | 51 ++++++++++++------- lldb/tools/lldb-dap/ProtocolUtils.h | 13 +++-- lldb/tools/lldb-dap/SourceBreakpoint.cpp | 8 ++- 16 files changed, 152 insertions(+), 63 deletions(-) diff --git a/lldb/test/API/tools/lldb-dap/breakpoint-assembly/TestDAP_breakpointAssembly.py b/lldb/test/API/tools/lldb-dap/breakpoint-assembly/TestDAP_breakpointAssembly.py index 8bccc2bcf4156..674bfe4199b4a 100644 --- a/lldb/test/API/tools/lldb-dap/breakpoint-assembly/TestDAP_breakpointAssembly.py +++ b/lldb/test/API/tools/lldb-dap/breakpoint-assembly/TestDAP_breakpointAssembly.py @@ -67,19 +67,19 @@ def test_break_on_invalid_source_reference(self): "Invalid sourceReference.", ) - # Verify that setting a breakpoint on a source reference without a symbol also fails + # Verify that setting a breakpoint on a source reference that is not created fails response = self.dap_server.request_setBreakpoints( - Source(source_reference=0), [1] + Source(source_reference=200), [1] ) self.assertIsNotNone(response) breakpoints = response["body"]["breakpoints"] self.assertEqual(len(breakpoints), 1) - breakpoint = breakpoints[0] + break_point = breakpoints[0] self.assertFalse( - breakpoint["verified"], "Expected breakpoint to not be verified" + break_point["verified"], "Expected breakpoint to not be verified" ) - self.assertIn("message", breakpoint, "Expected message to be present") + self.assertIn("message", break_point, "Expected message to be present") self.assertEqual( - breakpoint["message"], - "Breakpoints in assembly without a valid symbol are not supported yet.", + break_point["message"], + "Invalid sourceReference.", ) diff --git a/lldb/tools/lldb-dap/Breakpoint.cpp b/lldb/tools/lldb-dap/Breakpoint.cpp index ef5646c4c3d16..e1b073405ebb2 100644 --- a/lldb/tools/lldb-dap/Breakpoint.cpp +++ b/lldb/tools/lldb-dap/Breakpoint.cpp @@ -64,8 +64,11 @@ protocol::Breakpoint Breakpoint::ToProtocolBreakpoint() { "0x" + llvm::utohexstr(bp_addr.GetLoadAddress(m_bp.GetTarget())); breakpoint.instructionReference = formatted_addr; - auto source = CreateSource(bp_addr, m_dap.target); - if (!IsAssemblySource(source)) { + std::optional source = + CreateSource(bp_addr, m_dap.target, [this](lldb::addr_t addr) { + return m_dap.CreateSourceReference(addr); + }); + if (source && !IsAssemblySource(*source)) { auto line_entry = bp_addr.GetLineEntry(); const auto line = line_entry.GetLine(); if (line != LLDB_INVALID_LINE_NUMBER) diff --git a/lldb/tools/lldb-dap/DAP.cpp b/lldb/tools/lldb-dap/DAP.cpp index 9fe8227cd2d6f..56bb5903080dc 100644 --- a/lldb/tools/lldb-dap/DAP.cpp +++ b/lldb/tools/lldb-dap/DAP.cpp @@ -510,6 +510,25 @@ DAP::SendFormattedOutput(OutputType o, const char *format, ...) { o, llvm::StringRef(buffer, std::min(actual_length, sizeof(buffer)))); } +int32_t DAP::CreateSourceReference(lldb::addr_t address) { + auto iter = llvm::find(source_references, address); + if (iter != source_references.end()) + return std::distance(source_references.begin(), iter) + 1; + + source_references.emplace_back(address); + return static_cast(source_references.size()); +} + +std::optional DAP::GetSourceReferenceAddress(int32_t reference) { + if (reference <= LLDB_DAP_INVALID_SRC_REF) + return std::nullopt; + + if (static_cast(reference) > source_references.size()) + return std::nullopt; + + return source_references[reference - 1]; +} + ExceptionBreakpoint *DAP::GetExceptionBPFromStopReason(lldb::SBThread &thread) { const auto num = thread.GetStopReasonDataCount(); // Check to see if have hit an exception breakpoint and change the diff --git a/lldb/tools/lldb-dap/DAP.h b/lldb/tools/lldb-dap/DAP.h index 89bc827c1141f..2766c11b48963 100644 --- a/lldb/tools/lldb-dap/DAP.h +++ b/lldb/tools/lldb-dap/DAP.h @@ -105,6 +105,9 @@ struct DAP { /// Map step in target id to list of function targets that user can choose. llvm::DenseMap step_in_targets; + /// list of addresses mapped by sourceReference(index - 1) + std::vector source_references; + /// A copy of the last LaunchRequest so we can reuse its arguments if we get a /// RestartRequest. Restarting an AttachRequest is not supported. std::optional last_launch_request; @@ -219,7 +222,9 @@ struct DAP { void __attribute__((format(printf, 3, 4))) SendFormattedOutput(OutputType o, const char *format, ...); - static int64_t GetNextSourceReference(); + int32_t CreateSourceReference(lldb::addr_t address); + + std::optional GetSourceReferenceAddress(int32_t reference); ExceptionBreakpoint *GetExceptionBPFromStopReason(lldb::SBThread &thread); diff --git a/lldb/tools/lldb-dap/Handler/DisassembleRequestHandler.cpp b/lldb/tools/lldb-dap/Handler/DisassembleRequestHandler.cpp index 85214b84b5c9c..e345293387b41 100644 --- a/lldb/tools/lldb-dap/Handler/DisassembleRequestHandler.cpp +++ b/lldb/tools/lldb-dap/Handler/DisassembleRequestHandler.cpp @@ -85,7 +85,8 @@ static lldb::SBAddress GetDisassembleStartAddress(lldb::SBTarget target, } static DisassembledInstruction ConvertSBInstructionToDisassembledInstruction( - lldb::SBTarget &target, lldb::SBInstruction &inst, bool resolve_symbols) { + DAP &dap, lldb::SBInstruction &inst, bool resolve_symbols) { + lldb::SBTarget target = dap.target; if (!inst.IsValid()) return GetInvalidInstruction(); @@ -138,14 +139,17 @@ static DisassembledInstruction ConvertSBInstructionToDisassembledInstruction( si << " ; " << c; } - protocol::Source source = CreateSource(addr, target); + std::optional source = + CreateSource(addr, target, [&dap](lldb::addr_t addr) { + return dap.CreateSourceReference(addr); + }); lldb::SBLineEntry line_entry = GetLineEntryForAddress(target, addr); // If the line number is 0 then the entry represents a compiler generated // location. - if (!IsAssemblySource(source) && line_entry.GetStartAddress() == addr && - line_entry.IsValid() && line_entry.GetFileSpec().IsValid() && - line_entry.GetLine() != 0) { + if (source && !IsAssemblySource(*source) && + line_entry.GetStartAddress() == addr && line_entry.IsValid() && + line_entry.GetFileSpec().IsValid() && line_entry.GetLine() != 0) { disassembled_inst.location = std::move(source); const auto line = line_entry.GetLine(); @@ -221,7 +225,7 @@ DisassembleRequestHandler::Run(const DisassembleArguments &args) const { original_address_index = i; instructions.push_back(ConvertSBInstructionToDisassembledInstruction( - dap.target, inst, resolve_symbols)); + dap, inst, resolve_symbols)); } // Check if we miss instructions at the beginning. diff --git a/lldb/tools/lldb-dap/Handler/LocationsRequestHandler.cpp b/lldb/tools/lldb-dap/Handler/LocationsRequestHandler.cpp index 804bdcd622a2b..cf9b5a3dbd06b 100644 --- a/lldb/tools/lldb-dap/Handler/LocationsRequestHandler.cpp +++ b/lldb/tools/lldb-dap/Handler/LocationsRequestHandler.cpp @@ -137,7 +137,16 @@ void LocationsRequestHandler::operator()( return; } - body.try_emplace("source", CreateSource(line_entry.GetFileSpec())); + const std::optional source = + CreateSource(line_entry.GetFileSpec()); + if (!source) { + response["success"] = false; + response["message"] = "Failed to resolve file path for location"; + dap.SendJSON(llvm::json::Value(std::move(response))); + return; + } + + body.try_emplace("source", *source); if (int line = line_entry.GetLine()) body.try_emplace("line", line); if (int column = line_entry.GetColumn()) @@ -152,7 +161,16 @@ void LocationsRequestHandler::operator()( return; } - body.try_emplace("source", CreateSource(decl.GetFileSpec())); + const std::optional source = + CreateSource(decl.GetFileSpec()); + if (!source) { + response["success"] = false; + response["message"] = "Failed to resolve file path for location"; + dap.SendJSON(llvm::json::Value(std::move(response))); + return; + } + + body.try_emplace("source", *source); if (int line = decl.GetLine()) body.try_emplace("line", line); if (int column = decl.GetColumn()) diff --git a/lldb/tools/lldb-dap/Handler/SourceRequestHandler.cpp b/lldb/tools/lldb-dap/Handler/SourceRequestHandler.cpp index 353d3365564f5..755ad206abe26 100644 --- a/lldb/tools/lldb-dap/Handler/SourceRequestHandler.cpp +++ b/lldb/tools/lldb-dap/Handler/SourceRequestHandler.cpp @@ -29,34 +29,42 @@ namespace lldb_dap { /// the source code for a given source reference. llvm::Expected SourceRequestHandler::Run(const protocol::SourceArguments &args) const { - const auto source = + + uint32_t source_ref = args.source->sourceReference.value_or(args.sourceReference); + const std::optional source_addr_opt = + dap.GetSourceReferenceAddress(source_ref); - if (!source) + if (!source_addr_opt) return llvm::make_error( - "invalid arguments, expected source.sourceReference to be set"); + llvm::formatv("Unknown source reference {}", source_ref)); - lldb::SBAddress address(source, dap.target); + lldb::SBAddress address(*source_addr_opt, dap.target); if (!address.IsValid()) return llvm::make_error("source not found"); lldb::SBSymbol symbol = address.GetSymbol(); - - lldb::SBStream stream; - lldb::SBExecutionContext exe_ctx(dap.target); + lldb::SBInstructionList insts; if (symbol.IsValid()) { - lldb::SBInstructionList insts = symbol.GetInstructions(dap.target); - insts.GetDescription(stream, exe_ctx); + insts = symbol.GetInstructions(dap.target); } else { // No valid symbol, just return the disassembly. - lldb::SBInstructionList insts = dap.target.ReadInstructions( + insts = dap.target.ReadInstructions( address, dap.k_number_of_assembly_lines_for_nodebug); - insts.GetDescription(stream, exe_ctx); } + if (!insts || insts.GetSize() == 0) + return llvm::make_error( + llvm::formatv("no instruction source for address {}", + address.GetLoadAddress(dap.target))); + + lldb::SBStream stream; + lldb::SBExecutionContext exe_ctx(dap.target); + insts.GetDescription(stream, exe_ctx); return protocol::SourceResponseBody{/*content=*/stream.GetData(), - /*mimeType=*/"text/x-lldb.disassembly"}; + /*mimeType=*/ + "text/x-lldb.disassembly"}; } } // namespace lldb_dap diff --git a/lldb/tools/lldb-dap/Handler/StackTraceRequestHandler.cpp b/lldb/tools/lldb-dap/Handler/StackTraceRequestHandler.cpp index 4ea4cd1e517d4..77ef952a1e343 100644 --- a/lldb/tools/lldb-dap/Handler/StackTraceRequestHandler.cpp +++ b/lldb/tools/lldb-dap/Handler/StackTraceRequestHandler.cpp @@ -69,7 +69,7 @@ static bool FillStackFrames(DAP &dap, lldb::SBThread &thread, break; } - stack_frames.emplace_back(CreateStackFrame(frame, frame_format)); + stack_frames.emplace_back(CreateStackFrame(dap, frame, frame_format)); } if (include_all && reached_end_of_stack) { diff --git a/lldb/tools/lldb-dap/JSONUtils.cpp b/lldb/tools/lldb-dap/JSONUtils.cpp index 6cdde63e9796e..8091809f55791 100644 --- a/lldb/tools/lldb-dap/JSONUtils.cpp +++ b/lldb/tools/lldb-dap/JSONUtils.cpp @@ -552,7 +552,7 @@ CreateExceptionBreakpointFilter(const ExceptionBreakpoint &bp) { // }, // "required": [ "id", "name", "line", "column" ] // } -llvm::json::Value CreateStackFrame(lldb::SBFrame &frame, +llvm::json::Value CreateStackFrame(DAP &dap, lldb::SBFrame &frame, lldb::SBFormat &format) { llvm::json::Object object; int64_t frame_id = MakeDAPFrameID(frame); @@ -582,8 +582,11 @@ llvm::json::Value CreateStackFrame(lldb::SBFrame &frame, EmplaceSafeString(object, "name", frame_name); auto target = frame.GetThread().GetProcess().GetTarget(); - auto source = CreateSource(frame.GetPCAddress(), target); - if (!IsAssemblySource(source)) { + std::optional source = + CreateSource(frame.GetPCAddress(), target, [&dap](lldb::addr_t addr) { + return dap.CreateSourceReference(addr); + }); + if (source && !IsAssemblySource(*source)) { // This is a normal source with a valid line entry. auto line_entry = frame.GetLineEntry(); object.try_emplace("line", line_entry.GetLine()); @@ -607,7 +610,8 @@ llvm::json::Value CreateStackFrame(lldb::SBFrame &frame, object.try_emplace("column", 1); } - object.try_emplace("source", std::move(source)); + if (source) + object.try_emplace("source", std::move(source).value()); const auto pc = frame.GetPC(); if (pc != LLDB_INVALID_ADDRESS) { diff --git a/lldb/tools/lldb-dap/JSONUtils.h b/lldb/tools/lldb-dap/JSONUtils.h index 10dc46b94184f..dcf9453a72e90 100644 --- a/lldb/tools/lldb-dap/JSONUtils.h +++ b/lldb/tools/lldb-dap/JSONUtils.h @@ -246,6 +246,9 @@ CreateExceptionBreakpointFilter(const ExceptionBreakpoint &bp); /// "line" - the source file line number as an integer /// "column" - the source file column number as an integer /// +/// \param[in] dap +/// The DAP session associated with the stopped thread. +/// /// \param[in] frame /// The LLDB stack frame to use when populating out the "StackFrame" /// object. @@ -257,7 +260,7 @@ CreateExceptionBreakpointFilter(const ExceptionBreakpoint &bp); /// \return /// A "StackFrame" JSON object with that follows the formal JSON /// definition outlined by Microsoft. -llvm::json::Value CreateStackFrame(lldb::SBFrame &frame, +llvm::json::Value CreateStackFrame(DAP &dap, lldb::SBFrame &frame, lldb::SBFormat &format); /// Create a "StackFrame" label object for a LLDB thread. diff --git a/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h b/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h index 583c203be8e1a..7a0a01a9ce94f 100644 --- a/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h +++ b/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h @@ -468,7 +468,7 @@ struct SourceArguments { /// The reference to the source. This is the same as `source.sourceReference`. /// This is provided for backward compatibility since old clients do not /// understand the `source` attribute. - int64_t sourceReference; + int64_t sourceReference = LLDB_DAP_INVALID_SRC_REF; }; bool fromJSON(const llvm::json::Value &, SourceArguments &, llvm::json::Path); diff --git a/lldb/tools/lldb-dap/Protocol/ProtocolTypes.cpp b/lldb/tools/lldb-dap/Protocol/ProtocolTypes.cpp index c21f8382320a5..24c459da49be5 100644 --- a/lldb/tools/lldb-dap/Protocol/ProtocolTypes.cpp +++ b/lldb/tools/lldb-dap/Protocol/ProtocolTypes.cpp @@ -65,7 +65,7 @@ llvm::json::Value toJSON(const Source &S) { result.insert({"name", *S.name}); if (S.path) result.insert({"path", *S.path}); - if (S.sourceReference) + if (S.sourceReference && (*S.sourceReference > LLDB_DAP_INVALID_SRC_REF)) result.insert({"sourceReference", *S.sourceReference}); if (S.presentationHint) result.insert({"presentationHint", *S.presentationHint}); diff --git a/lldb/tools/lldb-dap/Protocol/ProtocolTypes.h b/lldb/tools/lldb-dap/Protocol/ProtocolTypes.h index d7094fbab9e59..4919d9e83d83b 100644 --- a/lldb/tools/lldb-dap/Protocol/ProtocolTypes.h +++ b/lldb/tools/lldb-dap/Protocol/ProtocolTypes.h @@ -28,6 +28,7 @@ #include #define LLDB_DAP_INVALID_VARRERF UINT64_MAX +#define LLDB_DAP_INVALID_SRC_REF 0 namespace lldb_dap::protocol { @@ -309,7 +310,7 @@ struct Source { /// `source` request (even if a path is specified). Since a `sourceReference` /// is only valid for a session, it can not be used to persist a source. The /// value should be less than or equal to 2147483647 (2^31-1). - std::optional sourceReference; + std::optional sourceReference; /// A hint for how to present the source in the UI. A value of `deemphasize` /// can be used to indicate that the source is not available or that it is diff --git a/lldb/tools/lldb-dap/ProtocolUtils.cpp b/lldb/tools/lldb-dap/ProtocolUtils.cpp index 6e0adf5bc8b59..aa43b298339ba 100644 --- a/lldb/tools/lldb-dap/ProtocolUtils.cpp +++ b/lldb/tools/lldb-dap/ProtocolUtils.cpp @@ -46,21 +46,27 @@ static bool ShouldDisplayAssemblySource( return false; } -static protocol::Source CreateAssemblySource(const lldb::SBTarget &target, - lldb::SBAddress address) { - protocol::Source source; +static std::optional CreateAssemblySource( + const lldb::SBTarget &target, lldb::SBAddress address, + llvm::function_ref create_reference) { - auto symbol = address.GetSymbol(); + lldb::SBSymbol symbol = address.GetSymbol(); + lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; std::string name; if (symbol.IsValid()) { - source.sourceReference = symbol.GetStartAddress().GetLoadAddress(target); + load_addr = symbol.GetStartAddress().GetLoadAddress(target); name = symbol.GetName(); } else { - const auto load_addr = address.GetLoadAddress(target); - source.sourceReference = load_addr; + load_addr = address.GetLoadAddress(target); name = GetLoadAddressString(load_addr); } + if (load_addr == LLDB_INVALID_ADDRESS) { + return std::nullopt; + } + + protocol::Source source; + source.sourceReference = create_reference(load_addr); lldb::SBModule module = address.GetModule(); if (module.IsValid()) { lldb::SBFileSpec file_spec = module.GetFileSpec(); @@ -81,27 +87,33 @@ static protocol::Source CreateAssemblySource(const lldb::SBTarget &target, return source; } -protocol::Source CreateSource(const lldb::SBFileSpec &file) { +std::optional CreateSource(const lldb::SBFileSpec &file) { + if (!file.IsValid()) + return std::nullopt; + protocol::Source source; - if (file.IsValid()) { - if (const char *name = file.GetFilename()) - source.name = name; - char path[PATH_MAX] = ""; - if (file.GetPath(path, sizeof(path)) && - lldb::SBFileSpec::ResolvePath(path, path, PATH_MAX)) - source.path = path; - } + if (const char *name = file.GetFilename()) + source.name = name; + char path[PATH_MAX] = ""; + if (file.GetPath(path, sizeof(path)) && + lldb::SBFileSpec::ResolvePath(path, path, PATH_MAX)) + source.path = path; return source; } -protocol::Source CreateSource(lldb::SBAddress address, lldb::SBTarget &target) { +std::optional +CreateSource(lldb::SBAddress address, lldb::SBTarget &target, + llvm::function_ref create_reference) { lldb::SBDebugger debugger = target.GetDebugger(); lldb::StopDisassemblyType stop_disassembly_display = GetStopDisassemblyDisplay(debugger); if (ShouldDisplayAssemblySource(address, stop_disassembly_display)) - return CreateAssemblySource(target, address); + return CreateAssemblySource(target, address, create_reference); lldb::SBLineEntry line_entry = GetLineEntryForAddress(target, address); + if (!line_entry.IsValid()) + return std::nullopt; + return CreateSource(line_entry.GetFileSpec()); } @@ -109,7 +121,8 @@ bool IsAssemblySource(const protocol::Source &source) { // According to the specification, a source must have either `path` or // `sourceReference` specified. We use `path` for sources with known source // code, and `sourceReferences` when falling back to assembly. - return source.sourceReference.value_or(0) != 0; + return source.sourceReference.value_or(LLDB_DAP_INVALID_SRC_REF) > + LLDB_DAP_INVALID_SRC_REF; } std::string GetLoadAddressString(const lldb::addr_t addr) { diff --git a/lldb/tools/lldb-dap/ProtocolUtils.h b/lldb/tools/lldb-dap/ProtocolUtils.h index 2b2ac9e8e35fd..bed5cc686335e 100644 --- a/lldb/tools/lldb-dap/ProtocolUtils.h +++ b/lldb/tools/lldb-dap/ProtocolUtils.h @@ -25,9 +25,9 @@ namespace lldb_dap { /// The SBFileSpec to use when populating out the "Source" object /// /// \return -/// A "Source" JSON object that follows the formal JSON +/// An optional "Source" JSON object that follows the formal JSON /// definition outlined by Microsoft. -protocol::Source CreateSource(const lldb::SBFileSpec &file); +std::optional CreateSource(const lldb::SBFileSpec &file); /// Create a "Source" JSON object as described in the debug adapter definition. /// @@ -37,10 +37,15 @@ protocol::Source CreateSource(const lldb::SBFileSpec &file); /// \param[in] target /// The target that has the address. /// +/// \param[in] create_reference +/// function used to create a source_reference +/// /// \return -/// A "Source" JSON object that follows the formal JSON +/// An optional "Source" JSON object that follows the formal JSON /// definition outlined by Microsoft. -protocol::Source CreateSource(lldb::SBAddress address, lldb::SBTarget &target); +std::optional +CreateSource(lldb::SBAddress address, lldb::SBTarget &target, + llvm::function_ref create_reference); /// Checks if the given source is for assembly code. bool IsAssemblySource(const protocol::Source &source); diff --git a/lldb/tools/lldb-dap/SourceBreakpoint.cpp b/lldb/tools/lldb-dap/SourceBreakpoint.cpp index a4327ae18cf6c..5fce9fe0ddbb3 100644 --- a/lldb/tools/lldb-dap/SourceBreakpoint.cpp +++ b/lldb/tools/lldb-dap/SourceBreakpoint.cpp @@ -46,7 +46,13 @@ llvm::Error SourceBreakpoint::SetBreakpoint(const protocol::Source &source) { if (source.sourceReference) { // Breakpoint set by assembly source. - lldb::SBAddress source_address(*source.sourceReference, m_dap.target); + std::optional raw_addr = + m_dap.GetSourceReferenceAddress(*source.sourceReference); + if (!raw_addr) + return llvm::createStringError(llvm::inconvertibleErrorCode(), + "Invalid sourceReference."); + + lldb::SBAddress source_address(*raw_addr, m_dap.target); if (!source_address.IsValid()) return llvm::createStringError(llvm::inconvertibleErrorCode(), "Invalid sourceReference."); From 03a10993b06b2aa0d3ff04ea7060b934f31bea66 Mon Sep 17 00:00:00 2001 From: Ebuka Ezike Date: Tue, 17 Jun 2025 12:39:42 +0100 Subject: [PATCH 2/4] [lldb-dap] add review changes. --- lldb/tools/lldb-dap/Breakpoint.cpp | 5 +-- lldb/tools/lldb-dap/DAP.cpp | 33 +++++++++++++++---- lldb/tools/lldb-dap/DAP.h | 18 ++++++++-- .../Handler/DisassembleRequestHandler.cpp | 5 +-- lldb/tools/lldb-dap/JSONUtils.cpp | 5 ++- lldb/tools/lldb-dap/ProtocolUtils.cpp | 27 +++++---------- lldb/tools/lldb-dap/ProtocolUtils.h | 14 ++++---- 7 files changed, 62 insertions(+), 45 deletions(-) diff --git a/lldb/tools/lldb-dap/Breakpoint.cpp b/lldb/tools/lldb-dap/Breakpoint.cpp index e1b073405ebb2..b4e593eb83d27 100644 --- a/lldb/tools/lldb-dap/Breakpoint.cpp +++ b/lldb/tools/lldb-dap/Breakpoint.cpp @@ -64,10 +64,7 @@ protocol::Breakpoint Breakpoint::ToProtocolBreakpoint() { "0x" + llvm::utohexstr(bp_addr.GetLoadAddress(m_bp.GetTarget())); breakpoint.instructionReference = formatted_addr; - std::optional source = - CreateSource(bp_addr, m_dap.target, [this](lldb::addr_t addr) { - return m_dap.CreateSourceReference(addr); - }); + std::optional source = m_dap.ResolveSource(bp_addr); if (source && !IsAssemblySource(*source)) { auto line_entry = bp_addr.GetLineEntry(); const auto line = line_entry.GetLine(); diff --git a/lldb/tools/lldb-dap/DAP.cpp b/lldb/tools/lldb-dap/DAP.cpp index 56bb5903080dc..f33a920067e30 100644 --- a/lldb/tools/lldb-dap/DAP.cpp +++ b/lldb/tools/lldb-dap/DAP.cpp @@ -17,6 +17,7 @@ #include "Protocol/ProtocolBase.h" #include "Protocol/ProtocolRequests.h" #include "Protocol/ProtocolTypes.h" +#include "ProtocolUtils.h" #include "Transport.h" #include "lldb/API/SBBreakpoint.h" #include "lldb/API/SBCommandInterpreter.h" @@ -511,22 +512,24 @@ DAP::SendFormattedOutput(OutputType o, const char *format, ...) { } int32_t DAP::CreateSourceReference(lldb::addr_t address) { - auto iter = llvm::find(source_references, address); - if (iter != source_references.end()) - return std::distance(source_references.begin(), iter) + 1; + std::lock_guard guard(m_source_references_mutex); + auto iter = llvm::find(m_source_references, address); + if (iter != m_source_references.end()) + return std::distance(m_source_references.begin(), iter) + 1; - source_references.emplace_back(address); - return static_cast(source_references.size()); + m_source_references.emplace_back(address); + return static_cast(m_source_references.size()); } std::optional DAP::GetSourceReferenceAddress(int32_t reference) { + std::lock_guard guard(m_source_references_mutex); if (reference <= LLDB_DAP_INVALID_SRC_REF) return std::nullopt; - if (static_cast(reference) > source_references.size()) + if (static_cast(reference) > m_source_references.size()) return std::nullopt; - return source_references[reference - 1]; + return m_source_references[reference - 1]; } ExceptionBreakpoint *DAP::GetExceptionBPFromStopReason(lldb::SBThread &thread) { @@ -634,6 +637,22 @@ ReplMode DAP::DetectReplMode(lldb::SBFrame frame, std::string &expression, llvm_unreachable("enum cases exhausted."); } +std::optional DAP::ResolveSource(lldb::SBAddress address) { + + if (DisplayAssemblySource(debugger, address)) { + auto create_reference = [this](lldb::addr_t addr) { + return CreateSourceReference(addr); + }; + return CreateAssemblySource(target, address, create_reference); + } + + lldb::SBLineEntry line_entry = GetLineEntryForAddress(target, address); + if (!line_entry.IsValid()) + return std::nullopt; + + return CreateSource(line_entry.GetFileSpec()); +} + bool DAP::RunLLDBCommands(llvm::StringRef prefix, llvm::ArrayRef commands) { bool required_command_failed = false; diff --git a/lldb/tools/lldb-dap/DAP.h b/lldb/tools/lldb-dap/DAP.h index 2766c11b48963..dd16f8d9eba9c 100644 --- a/lldb/tools/lldb-dap/DAP.h +++ b/lldb/tools/lldb-dap/DAP.h @@ -105,9 +105,6 @@ struct DAP { /// Map step in target id to list of function targets that user can choose. llvm::DenseMap step_in_targets; - /// list of addresses mapped by sourceReference(index - 1) - std::vector source_references; - /// A copy of the last LaunchRequest so we can reuse its arguments if we get a /// RestartRequest. Restarting an AttachRequest is not supported. std::optional last_launch_request; @@ -257,6 +254,17 @@ struct DAP { ReplMode DetectReplMode(lldb::SBFrame frame, std::string &expression, bool partial_expression); + /// Create a "Source" JSON object as described in the debug adapter + /// definition. + /// + /// \param[in] address + /// The address to use when populating out the "Source" object. + /// + /// \return + /// An optional "Source" JSON object that follows the formal JSON + /// definition outlined by Microsoft. + std::optional ResolveSource(lldb::SBAddress address); + /// \return /// \b false if a fatal error was found while executing these commands, /// according to the rules of \a LLDBUtils::RunLLDBCommands. @@ -411,6 +419,10 @@ struct DAP { std::thread progress_event_thread; /// @} + /// list of addresses mapped by sourceReference(index - 1) + std::vector m_source_references; + std::mutex m_source_references_mutex; + /// Queue for all incoming messages. std::deque m_queue; std::mutex m_queue_mutex; diff --git a/lldb/tools/lldb-dap/Handler/DisassembleRequestHandler.cpp b/lldb/tools/lldb-dap/Handler/DisassembleRequestHandler.cpp index e345293387b41..f66c87fa9893d 100644 --- a/lldb/tools/lldb-dap/Handler/DisassembleRequestHandler.cpp +++ b/lldb/tools/lldb-dap/Handler/DisassembleRequestHandler.cpp @@ -139,10 +139,7 @@ static DisassembledInstruction ConvertSBInstructionToDisassembledInstruction( si << " ; " << c; } - std::optional source = - CreateSource(addr, target, [&dap](lldb::addr_t addr) { - return dap.CreateSourceReference(addr); - }); + std::optional source = dap.ResolveSource(addr); lldb::SBLineEntry line_entry = GetLineEntryForAddress(target, addr); // If the line number is 0 then the entry represents a compiler generated diff --git a/lldb/tools/lldb-dap/JSONUtils.cpp b/lldb/tools/lldb-dap/JSONUtils.cpp index 8091809f55791..e314240cd81cb 100644 --- a/lldb/tools/lldb-dap/JSONUtils.cpp +++ b/lldb/tools/lldb-dap/JSONUtils.cpp @@ -583,9 +583,8 @@ llvm::json::Value CreateStackFrame(DAP &dap, lldb::SBFrame &frame, auto target = frame.GetThread().GetProcess().GetTarget(); std::optional source = - CreateSource(frame.GetPCAddress(), target, [&dap](lldb::addr_t addr) { - return dap.CreateSourceReference(addr); - }); + dap.ResolveSource(frame.GetPCAddress()); + if (source && !IsAssemblySource(*source)) { // This is a normal source with a valid line entry. auto line_entry = frame.GetLineEntry(); diff --git a/lldb/tools/lldb-dap/ProtocolUtils.cpp b/lldb/tools/lldb-dap/ProtocolUtils.cpp index aa43b298339ba..d08d53048b6d6 100644 --- a/lldb/tools/lldb-dap/ProtocolUtils.cpp +++ b/lldb/tools/lldb-dap/ProtocolUtils.cpp @@ -46,9 +46,9 @@ static bool ShouldDisplayAssemblySource( return false; } -static std::optional CreateAssemblySource( +std::optional CreateAssemblySource( const lldb::SBTarget &target, lldb::SBAddress address, - llvm::function_ref create_reference) { + llvm::function_ref create_reference) { lldb::SBSymbol symbol = address.GetSymbol(); lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; @@ -101,22 +101,6 @@ std::optional CreateSource(const lldb::SBFileSpec &file) { return source; } -std::optional -CreateSource(lldb::SBAddress address, lldb::SBTarget &target, - llvm::function_ref create_reference) { - lldb::SBDebugger debugger = target.GetDebugger(); - lldb::StopDisassemblyType stop_disassembly_display = - GetStopDisassemblyDisplay(debugger); - if (ShouldDisplayAssemblySource(address, stop_disassembly_display)) - return CreateAssemblySource(target, address, create_reference); - - lldb::SBLineEntry line_entry = GetLineEntryForAddress(target, address); - if (!line_entry.IsValid()) - return std::nullopt; - - return CreateSource(line_entry.GetFileSpec()); -} - bool IsAssemblySource(const protocol::Source &source) { // According to the specification, a source must have either `path` or // `sourceReference` specified. We use `path` for sources with known source @@ -125,6 +109,13 @@ bool IsAssemblySource(const protocol::Source &source) { LLDB_DAP_INVALID_SRC_REF; } +bool DisplayAssemblySource(lldb::SBDebugger &debugger, + lldb::SBAddress address) { + const lldb::StopDisassemblyType stop_disassembly_display = + GetStopDisassemblyDisplay(debugger); + return ShouldDisplayAssemblySource(address, stop_disassembly_display); +} + std::string GetLoadAddressString(const lldb::addr_t addr) { return "0x" + llvm::utohexstr(addr, false, 16); } diff --git a/lldb/tools/lldb-dap/ProtocolUtils.h b/lldb/tools/lldb-dap/ProtocolUtils.h index bed5cc686335e..09d559c9f3943 100644 --- a/lldb/tools/lldb-dap/ProtocolUtils.h +++ b/lldb/tools/lldb-dap/ProtocolUtils.h @@ -31,25 +31,27 @@ std::optional CreateSource(const lldb::SBFileSpec &file); /// Create a "Source" JSON object as described in the debug adapter definition. /// -/// \param[in] address -/// The address to use when populating out the "Source" object. -/// /// \param[in] target /// The target that has the address. /// +/// \param[in] address +/// The address to use when populating out the "Source" object. +/// /// \param[in] create_reference /// function used to create a source_reference /// /// \return /// An optional "Source" JSON object that follows the formal JSON /// definition outlined by Microsoft. -std::optional -CreateSource(lldb::SBAddress address, lldb::SBTarget &target, - llvm::function_ref create_reference); +std::optional CreateAssemblySource( + const lldb::SBTarget &target, lldb::SBAddress address, + llvm::function_ref create_reference); /// Checks if the given source is for assembly code. bool IsAssemblySource(const protocol::Source &source); +bool DisplayAssemblySource(lldb::SBDebugger &debugger, lldb::SBAddress address); + /// Get the address as a 16-digit hex string, e.g. "0x0000000000012345" std::string GetLoadAddressString(const lldb::addr_t addr); From 4064ac6c38ccc65bf79e9d3b33f4cd8de7da402c Mon Sep 17 00:00:00 2001 From: Ebuka Ezike Date: Tue, 17 Jun 2025 20:23:56 +0100 Subject: [PATCH 3/4] [lldb-dap] add review changes --- lldb/tools/lldb-dap/DAP.h | 2 +- lldb/tools/lldb-dap/ProtocolUtils.cpp | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/lldb/tools/lldb-dap/DAP.h b/lldb/tools/lldb-dap/DAP.h index dd16f8d9eba9c..eace5b04dfa49 100644 --- a/lldb/tools/lldb-dap/DAP.h +++ b/lldb/tools/lldb-dap/DAP.h @@ -419,7 +419,7 @@ struct DAP { std::thread progress_event_thread; /// @} - /// list of addresses mapped by sourceReference(index - 1) + /// List of addresses mapped by sourceReference. std::vector m_source_references; std::mutex m_source_references_mutex; diff --git a/lldb/tools/lldb-dap/ProtocolUtils.cpp b/lldb/tools/lldb-dap/ProtocolUtils.cpp index d08d53048b6d6..07e5d9a1a946e 100644 --- a/lldb/tools/lldb-dap/ProtocolUtils.cpp +++ b/lldb/tools/lldb-dap/ProtocolUtils.cpp @@ -61,9 +61,8 @@ std::optional CreateAssemblySource( name = GetLoadAddressString(load_addr); } - if (load_addr == LLDB_INVALID_ADDRESS) { + if (load_addr == LLDB_INVALID_ADDRESS) return std::nullopt; - } protocol::Source source; source.sourceReference = create_reference(load_addr); From 3ad8dec8a43fe23e8f057cd9c9942d333babb11e Mon Sep 17 00:00:00 2001 From: Ebuka Ezike Date: Wed, 18 Jun 2025 13:56:38 +0100 Subject: [PATCH 4/4] [lldb-dap] move create createAssemblyReference to DAP.cpp --- lldb/tools/lldb-dap/DAP.cpp | 47 +++++++++++++++++++++++---- lldb/tools/lldb-dap/DAP.h | 12 +++++++ lldb/tools/lldb-dap/ProtocolUtils.cpp | 40 ----------------------- lldb/tools/lldb-dap/ProtocolUtils.h | 18 ---------- 4 files changed, 52 insertions(+), 65 deletions(-) diff --git a/lldb/tools/lldb-dap/DAP.cpp b/lldb/tools/lldb-dap/DAP.cpp index f33a920067e30..64516ef2024e5 100644 --- a/lldb/tools/lldb-dap/DAP.cpp +++ b/lldb/tools/lldb-dap/DAP.cpp @@ -638,13 +638,8 @@ ReplMode DAP::DetectReplMode(lldb::SBFrame frame, std::string &expression, } std::optional DAP::ResolveSource(lldb::SBAddress address) { - - if (DisplayAssemblySource(debugger, address)) { - auto create_reference = [this](lldb::addr_t addr) { - return CreateSourceReference(addr); - }; - return CreateAssemblySource(target, address, create_reference); - } + if (DisplayAssemblySource(debugger, address)) + return ResolveAssemblySource(address); lldb::SBLineEntry line_entry = GetLineEntryForAddress(target, address); if (!line_entry.IsValid()) @@ -653,6 +648,44 @@ std::optional DAP::ResolveSource(lldb::SBAddress address) { return CreateSource(line_entry.GetFileSpec()); } +std::optional +DAP::ResolveAssemblySource(lldb::SBAddress address) { + lldb::SBSymbol symbol = address.GetSymbol(); + lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; + std::string name; + if (symbol.IsValid()) { + load_addr = symbol.GetStartAddress().GetLoadAddress(target); + name = symbol.GetName(); + } else { + load_addr = address.GetLoadAddress(target); + name = GetLoadAddressString(load_addr); + } + + if (load_addr == LLDB_INVALID_ADDRESS) + return std::nullopt; + + protocol::Source source; + source.sourceReference = CreateSourceReference(load_addr); + lldb::SBModule module = address.GetModule(); + if (module.IsValid()) { + lldb::SBFileSpec file_spec = module.GetFileSpec(); + if (file_spec.IsValid()) { + std::string path = GetSBFileSpecPath(file_spec); + if (!path.empty()) + source.path = path + '`' + name; + } + } + + source.name = std::move(name); + + // Mark the source as deemphasized since users will only be able to view + // assembly for these frames. + source.presentationHint = + protocol::Source::eSourcePresentationHintDeemphasize; + + return source; +} + bool DAP::RunLLDBCommands(llvm::StringRef prefix, llvm::ArrayRef commands) { bool required_command_failed = false; diff --git a/lldb/tools/lldb-dap/DAP.h b/lldb/tools/lldb-dap/DAP.h index eace5b04dfa49..5356d0859b00d 100644 --- a/lldb/tools/lldb-dap/DAP.h +++ b/lldb/tools/lldb-dap/DAP.h @@ -265,6 +265,18 @@ struct DAP { /// definition outlined by Microsoft. std::optional ResolveSource(lldb::SBAddress address); + /// Create a "Source" JSON object as described in the debug adapter + /// definition. + /// + /// \param[in] address + /// The address to use when populating out the "Source" object. + /// + /// \return + /// An optional "Source" JSON object that follows the formal JSON + /// definition outlined by Microsoft. + std::optional + ResolveAssemblySource(lldb::SBAddress address); + /// \return /// \b false if a fatal error was found while executing these commands, /// according to the rules of \a LLDBUtils::RunLLDBCommands. diff --git a/lldb/tools/lldb-dap/ProtocolUtils.cpp b/lldb/tools/lldb-dap/ProtocolUtils.cpp index 07e5d9a1a946e..8fd341b5681bc 100644 --- a/lldb/tools/lldb-dap/ProtocolUtils.cpp +++ b/lldb/tools/lldb-dap/ProtocolUtils.cpp @@ -46,46 +46,6 @@ static bool ShouldDisplayAssemblySource( return false; } -std::optional CreateAssemblySource( - const lldb::SBTarget &target, lldb::SBAddress address, - llvm::function_ref create_reference) { - - lldb::SBSymbol symbol = address.GetSymbol(); - lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; - std::string name; - if (symbol.IsValid()) { - load_addr = symbol.GetStartAddress().GetLoadAddress(target); - name = symbol.GetName(); - } else { - load_addr = address.GetLoadAddress(target); - name = GetLoadAddressString(load_addr); - } - - if (load_addr == LLDB_INVALID_ADDRESS) - return std::nullopt; - - protocol::Source source; - source.sourceReference = create_reference(load_addr); - lldb::SBModule module = address.GetModule(); - if (module.IsValid()) { - lldb::SBFileSpec file_spec = module.GetFileSpec(); - if (file_spec.IsValid()) { - std::string path = GetSBFileSpecPath(file_spec); - if (!path.empty()) - source.path = path + '`' + name; - } - } - - source.name = std::move(name); - - // Mark the source as deemphasized since users will only be able to view - // assembly for these frames. - source.presentationHint = - protocol::Source::PresentationHint::eSourcePresentationHintDeemphasize; - - return source; -} - std::optional CreateSource(const lldb::SBFileSpec &file) { if (!file.IsValid()) return std::nullopt; diff --git a/lldb/tools/lldb-dap/ProtocolUtils.h b/lldb/tools/lldb-dap/ProtocolUtils.h index 09d559c9f3943..fd75a1af862c2 100644 --- a/lldb/tools/lldb-dap/ProtocolUtils.h +++ b/lldb/tools/lldb-dap/ProtocolUtils.h @@ -29,24 +29,6 @@ namespace lldb_dap { /// definition outlined by Microsoft. std::optional CreateSource(const lldb::SBFileSpec &file); -/// Create a "Source" JSON object as described in the debug adapter definition. -/// -/// \param[in] target -/// The target that has the address. -/// -/// \param[in] address -/// The address to use when populating out the "Source" object. -/// -/// \param[in] create_reference -/// function used to create a source_reference -/// -/// \return -/// An optional "Source" JSON object that follows the formal JSON -/// definition outlined by Microsoft. -std::optional CreateAssemblySource( - const lldb::SBTarget &target, lldb::SBAddress address, - llvm::function_ref create_reference); - /// Checks if the given source is for assembly code. bool IsAssemblySource(const protocol::Source &source);