1//===-- ProtocolUtils.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 "ProtocolUtils.h"
10#include "JSONUtils.h"
11#include "LLDBUtils.h"
12
13#include "lldb/API/SBDebugger.h"
14#include "lldb/API/SBDeclaration.h"
15#include "lldb/API/SBFormat.h"
16#include "lldb/API/SBMutex.h"
17#include "lldb/API/SBStream.h"
18#include "lldb/API/SBTarget.h"
19#include "lldb/API/SBThread.h"
20#include "lldb/Host/PosixApi.h" // Adds PATH_MAX for windows
21
22#include <iomanip>
23#include <optional>
24#include <sstream>
25
26using namespace lldb_dap::protocol;
27namespace lldb_dap {
28
29static bool ShouldDisplayAssemblySource(
30 lldb::SBAddress address,
31 lldb::StopDisassemblyType stop_disassembly_display) {
32 if (stop_disassembly_display == lldb::eStopDisassemblyTypeNever)
33 return false;
34
35 if (stop_disassembly_display == lldb::eStopDisassemblyTypeAlways)
36 return true;
37
38 // A line entry of 0 indicates the line is compiler generated i.e. no source
39 // file is associated with the frame.
40 auto line_entry = address.GetLineEntry();
41 auto file_spec = line_entry.GetFileSpec();
42 if (!file_spec.IsValid() || line_entry.GetLine() == 0 ||
43 line_entry.GetLine() == LLDB_INVALID_LINE_NUMBER)
44 return true;
45
46 if (stop_disassembly_display == lldb::eStopDisassemblyTypeNoSource &&
47 !file_spec.Exists()) {
48 return true;
49 }
50
51 return false;
52}
53
54static uint64_t GetDebugInfoSizeInSection(lldb::SBSection section) {
55 uint64_t debug_info_size = 0;
56 const llvm::StringRef section_name(section.GetName());
57 if (section_name.starts_with(Prefix: ".debug") ||
58 section_name.starts_with(Prefix: "__debug") ||
59 section_name.starts_with(Prefix: ".apple") || section_name.starts_with(Prefix: "__apple"))
60 debug_info_size += section.GetFileByteSize();
61
62 const size_t num_sub_sections = section.GetNumSubSections();
63 for (size_t i = 0; i < num_sub_sections; i++)
64 debug_info_size +=
65 GetDebugInfoSizeInSection(section: section.GetSubSectionAtIndex(idx: i));
66
67 return debug_info_size;
68}
69
70static uint64_t GetDebugInfoSize(lldb::SBModule module) {
71 uint64_t debug_info_size = 0;
72 const size_t num_sections = module.GetNumSections();
73 for (size_t i = 0; i < num_sections; i++)
74 debug_info_size += GetDebugInfoSizeInSection(section: module.GetSectionAtIndex(idx: i));
75
76 return debug_info_size;
77}
78
79std::string ConvertDebugInfoSizeToString(uint64_t debug_size) {
80 std::ostringstream oss;
81 oss << std::fixed << std::setprecision(1);
82 if (debug_size < 1024) {
83 oss << debug_size << "B";
84 } else if (debug_size < static_cast<uint64_t>(1024 * 1024)) {
85 double kb = double(debug_size) / 1024.0;
86 oss << kb << "KB";
87 } else if (debug_size < 1024 * 1024 * 1024) {
88 double mb = double(debug_size) / (1024.0 * 1024.0);
89 oss << mb << "MB";
90 } else {
91 double gb = double(debug_size) / (1024.0 * 1024.0 * 1024.0);
92 oss << gb << "GB";
93 }
94 return oss.str();
95}
96
97std::optional<protocol::Module> CreateModule(const lldb::SBTarget &target,
98 lldb::SBModule &module,
99 bool id_only) {
100 if (!target.IsValid() || !module.IsValid())
101 return std::nullopt;
102
103 const llvm::StringRef uuid = module.GetUUIDString();
104 if (uuid.empty())
105 return std::nullopt;
106
107 protocol::Module p_module;
108 p_module.id = uuid;
109
110 if (id_only)
111 return p_module;
112
113 std::array<char, PATH_MAX> path_buffer{};
114 if (const lldb::SBFileSpec file_spec = module.GetFileSpec()) {
115 p_module.name = file_spec.GetFilename();
116
117 const uint32_t path_size =
118 file_spec.GetPath(dst_path: path_buffer.data(), dst_len: path_buffer.size());
119 p_module.path = std::string(path_buffer.data(), path_size);
120 }
121
122 if (const uint32_t num_compile_units = module.GetNumCompileUnits();
123 num_compile_units > 0) {
124 p_module.symbolStatus = "Symbols loaded.";
125
126 p_module.debugInfoSizeBytes = GetDebugInfoSize(module);
127
128 if (const lldb::SBFileSpec symbol_fspec = module.GetSymbolFileSpec()) {
129 const uint32_t path_size =
130 symbol_fspec.GetPath(dst_path: path_buffer.data(), dst_len: path_buffer.size());
131 p_module.symbolFilePath = std::string(path_buffer.data(), path_size);
132 }
133 } else {
134 p_module.symbolStatus = "Symbols not found.";
135 }
136
137 const auto load_address = module.GetObjectFileHeaderAddress();
138 if (const lldb::addr_t raw_address = load_address.GetLoadAddress(target);
139 raw_address != LLDB_INVALID_ADDRESS)
140 p_module.addressRange = llvm::formatv(Fmt: "{0:x}", Vals: raw_address);
141
142 std::array<uint32_t, 3> version_nums{};
143 const uint32_t num_versions =
144 module.GetVersion(versions: version_nums.data(), num_versions: version_nums.size());
145 if (num_versions > 0) {
146 p_module.version = llvm::formatv(
147 Fmt: "{:$[.]}", Vals: llvm::make_range(x: version_nums.begin(),
148 y: version_nums.begin() + num_versions));
149 }
150
151 return p_module;
152}
153
154std::optional<protocol::Source> CreateSource(const lldb::SBFileSpec &file) {
155 if (!file.IsValid())
156 return std::nullopt;
157
158 protocol::Source source;
159 if (const char *name = file.GetFilename())
160 source.name = name;
161 char path[PATH_MAX] = "";
162 if (file.GetPath(dst_path: path, dst_len: sizeof(path)) &&
163 lldb::SBFileSpec::ResolvePath(src_path: path, dst_path: path, PATH_MAX))
164 source.path = path;
165 return source;
166}
167
168bool IsAssemblySource(const protocol::Source &source) {
169 // According to the specification, a source must have either `path` or
170 // `sourceReference` specified. We use `path` for sources with known source
171 // code, and `sourceReferences` when falling back to assembly.
172 return source.sourceReference.value_or(LLDB_DAP_INVALID_SRC_REF) >
173 LLDB_DAP_INVALID_SRC_REF;
174}
175
176bool DisplayAssemblySource(lldb::SBDebugger &debugger,
177 lldb::SBAddress address) {
178 const lldb::StopDisassemblyType stop_disassembly_display =
179 GetStopDisassemblyDisplay(debugger);
180 return ShouldDisplayAssemblySource(address, stop_disassembly_display);
181}
182
183std::string GetLoadAddressString(const lldb::addr_t addr) {
184 return "0x" + llvm::utohexstr(X: addr, LowerCase: false, Width: 16);
185}
186
187protocol::Thread CreateThread(lldb::SBThread &thread, lldb::SBFormat &format) {
188 std::string name;
189 lldb::SBStream stream;
190 if (format && thread.GetDescriptionWithFormat(format, output&: stream).Success()) {
191 name = stream.GetData();
192 } else {
193 llvm::StringRef thread_name(thread.GetName());
194 llvm::StringRef queue_name(thread.GetQueueName());
195
196 if (!thread_name.empty()) {
197 name = thread_name.str();
198 } else if (!queue_name.empty()) {
199 auto kind = thread.GetQueue().GetKind();
200 std::string queue_kind_label = "";
201 if (kind == lldb::eQueueKindSerial)
202 queue_kind_label = " (serial)";
203 else if (kind == lldb::eQueueKindConcurrent)
204 queue_kind_label = " (concurrent)";
205
206 name = llvm::formatv(Fmt: "Thread {0} Queue: {1}{2}", Vals: thread.GetIndexID(),
207 Vals&: queue_name, Vals&: queue_kind_label)
208 .str();
209 } else {
210 name = llvm::formatv(Fmt: "Thread {0}", Vals: thread.GetIndexID()).str();
211 }
212 }
213 return protocol::Thread{.id: thread.GetThreadID(), .name: name};
214}
215
216std::vector<protocol::Thread> GetThreads(lldb::SBProcess process,
217 lldb::SBFormat &format) {
218 lldb::SBMutex lock = process.GetTarget().GetAPIMutex();
219 std::lock_guard<lldb::SBMutex> guard(lock);
220
221 std::vector<protocol::Thread> threads;
222
223 const uint32_t num_threads = process.GetNumThreads();
224 threads.reserve(n: num_threads);
225 for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
226 lldb::SBThread thread = process.GetThreadAtIndex(index: thread_idx);
227 threads.emplace_back(args: CreateThread(thread, format));
228 }
229 return threads;
230}
231
232ExceptionBreakpointsFilter
233CreateExceptionBreakpointFilter(const ExceptionBreakpoint &bp) {
234 ExceptionBreakpointsFilter filter;
235 filter.filter = bp.GetFilter();
236 filter.label = bp.GetLabel();
237 filter.description = bp.GetLabel();
238 filter.defaultState = ExceptionBreakpoint::kDefaultValue;
239 filter.supportsCondition = true;
240 return filter;
241}
242
243Variable CreateVariable(lldb::SBValue v, int64_t var_ref, bool format_hex,
244 bool auto_variable_summaries,
245 bool synthetic_child_debugging, bool is_name_duplicated,
246 std::optional<std::string> custom_name) {
247 VariableDescription desc(v, auto_variable_summaries, format_hex,
248 is_name_duplicated, custom_name);
249 Variable var;
250 var.name = desc.name;
251 var.value = desc.display_value;
252 var.type = desc.display_type_name;
253
254 if (!desc.evaluate_name.empty())
255 var.evaluateName = desc.evaluate_name;
256
257 // If we have a type with many children, we would like to be able to
258 // give a hint to the IDE that the type has indexed children so that the
259 // request can be broken up in grabbing only a few children at a time. We
260 // want to be careful and only call "v.GetNumChildren()" if we have an array
261 // type or if we have a synthetic child provider producing indexed children.
262 // We don't want to call "v.GetNumChildren()" on all objects as class, struct
263 // and union types don't need to be completed if they are never expanded. So
264 // we want to avoid calling this to only cases where we it makes sense to keep
265 // performance high during normal debugging.
266
267 // If we have an array type, say that it is indexed and provide the number
268 // of children in case we have a huge array. If we don't do this, then we
269 // might take a while to produce all children at onces which can delay your
270 // debug session.
271 if (desc.type_obj.IsArrayType()) {
272 var.indexedVariables = v.GetNumChildren();
273 } else if (v.IsSynthetic()) {
274 // For a type with a synthetic child provider, the SBType of "v" won't tell
275 // us anything about what might be displayed. Instead, we check if the first
276 // child's name is "[0]" and then say it is indexed. We call
277 // GetNumChildren() only if the child name matches to avoid a potentially
278 // expensive operation.
279 if (lldb::SBValue first_child = v.GetChildAtIndex(idx: 0)) {
280 llvm::StringRef first_child_name = first_child.GetName();
281 if (first_child_name == "[0]") {
282 size_t num_children = v.GetNumChildren();
283 // If we are creating a "[raw]" fake child for each synthetic type, we
284 // have to account for it when returning indexed variables.
285 if (synthetic_child_debugging)
286 ++num_children;
287 var.indexedVariables = num_children;
288 }
289 }
290 }
291
292 if (v.MightHaveChildren())
293 var.variablesReference = var_ref;
294
295 if (v.GetDeclaration().IsValid())
296 var.declarationLocationReference = PackLocation(var_ref, is_value_location: false);
297
298 if (ValuePointsToCode(v))
299 var.valueLocationReference = PackLocation(var_ref, is_value_location: true);
300
301 if (lldb::addr_t addr = v.GetLoadAddress(); addr != LLDB_INVALID_ADDRESS)
302 var.memoryReference = addr;
303
304 return var;
305}
306
307} // namespace lldb_dap
308

source code of lldb/tools/lldb-dap/ProtocolUtils.cpp