1//===-- SourceRequestHandler.cpp ------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "DAP.h"
10#include "Handler/RequestHandler.h"
11#include "LLDBUtils.h"
12#include "Protocol/ProtocolRequests.h"
13#include "Protocol/ProtocolTypes.h"
14#include "lldb/API/SBAddress.h"
15#include "lldb/API/SBExecutionContext.h"
16#include "lldb/API/SBFrame.h"
17#include "lldb/API/SBInstructionList.h"
18#include "lldb/API/SBProcess.h"
19#include "lldb/API/SBStream.h"
20#include "lldb/API/SBSymbol.h"
21#include "lldb/API/SBTarget.h"
22#include "lldb/API/SBThread.h"
23#include "lldb/lldb-types.h"
24#include "llvm/Support/Error.h"
25
26namespace lldb_dap {
27
28/// Source request; value of command field is 'source'. The request retrieves
29/// the source code for a given source reference.
30llvm::Expected<protocol::SourceResponseBody>
31SourceRequestHandler::Run(const protocol::SourceArguments &args) const {
32
33 uint32_t source_ref =
34 args.source->sourceReference.value_or(u: args.sourceReference);
35 const std::optional<lldb::addr_t> source_addr_opt =
36 dap.GetSourceReferenceAddress(reference: source_ref);
37
38 if (!source_addr_opt)
39 return llvm::make_error<DAPError>(
40 Args: llvm::formatv(Fmt: "Unknown source reference {}", Vals&: source_ref));
41
42 lldb::SBAddress address(*source_addr_opt, dap.target);
43 if (!address.IsValid())
44 return llvm::make_error<DAPError>(Args: "source not found");
45
46 lldb::SBSymbol symbol = address.GetSymbol();
47 lldb::SBInstructionList insts;
48
49 if (symbol.IsValid()) {
50 insts = symbol.GetInstructions(target: dap.target);
51 } else {
52 // No valid symbol, just return the disassembly.
53 insts = dap.target.ReadInstructions(
54 base_addr: address, count: dap.k_number_of_assembly_lines_for_nodebug);
55 }
56
57 if (!insts || insts.GetSize() == 0)
58 return llvm::make_error<DAPError>(
59 Args: llvm::formatv(Fmt: "no instruction source for address {}",
60 Vals: address.GetLoadAddress(target: dap.target)));
61
62 lldb::SBStream stream;
63 lldb::SBExecutionContext exe_ctx(dap.target);
64 insts.GetDescription(description&: stream, exe_ctx);
65 return protocol::SourceResponseBody{/*content=*/stream.GetData(),
66 /*mimeType=*/
67 "text/x-lldb.disassembly"};
68}
69
70} // namespace lldb_dap
71

source code of lldb/tools/lldb-dap/Handler/SourceRequestHandler.cpp