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