266 lines · cpp
1//===-- LLDBUtils.cpp -------------------------------------------*- C++ -*-===//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 "LLDBUtils.h"10#include "DAPError.h"11#include "JSONUtils.h"12#include "lldb/API/SBCommandInterpreter.h"13#include "lldb/API/SBCommandReturnObject.h"14#include "lldb/API/SBDebugger.h"15#include "lldb/API/SBFrame.h"16#include "lldb/API/SBStringList.h"17#include "lldb/API/SBStructuredData.h"18#include "lldb/API/SBThread.h"19#include "lldb/lldb-enumerations.h"20#include "llvm/ADT/ArrayRef.h"21#include "llvm/Support/Error.h"22#include "llvm/Support/JSON.h"23#include "llvm/Support/raw_ostream.h"24 25#include <cstring>26#include <mutex>27#include <system_error>28 29namespace lldb_dap {30 31bool RunLLDBCommands(lldb::SBDebugger &debugger, llvm::StringRef prefix,32 const llvm::ArrayRef<std::string> &commands,33 llvm::raw_ostream &strm, bool parse_command_directives,34 bool echo_commands) {35 if (commands.empty())36 return true;37 38 bool did_print_prefix = false;39 40 // We only need the prompt when echoing commands.41 std::string prompt_string;42 if (echo_commands) {43 prompt_string = "(lldb) ";44 45 // Get the current prompt from settings.46 if (const lldb::SBStructuredData prompt = debugger.GetSetting("prompt")) {47 const size_t prompt_length = prompt.GetStringValue(nullptr, 0);48 49 if (prompt_length != 0) {50 prompt_string.resize(prompt_length + 1);51 prompt.GetStringValue(prompt_string.data(), prompt_string.length());52 }53 }54 }55 56 lldb::SBCommandInterpreter interp = debugger.GetCommandInterpreter();57 for (llvm::StringRef command : commands) {58 lldb::SBCommandReturnObject result;59 bool quiet_on_success = false;60 bool check_error = false;61 62 while (parse_command_directives) {63 if (command.starts_with("?")) {64 command = command.drop_front();65 quiet_on_success = true;66 } else if (command.starts_with("!")) {67 command = command.drop_front();68 check_error = true;69 } else {70 break;71 }72 }73 74 {75 // Prevent simultaneous calls to HandleCommand, e.g. EventThreadFunction76 // may asynchronously call RunExitCommands when we are already calling77 // RunTerminateCommands.78 static std::mutex handle_command_mutex;79 std::lock_guard<std::mutex> locker(handle_command_mutex);80 interp.HandleCommand(command.str().c_str(), result,81 /*add_to_history=*/true);82 }83 84 const bool got_error = !result.Succeeded();85 // The if statement below is assuming we always print out `!` prefixed86 // lines. The only time we don't print is when we have `quiet_on_success ==87 // true` and we don't have an error.88 if (quiet_on_success ? got_error : true) {89 if (!did_print_prefix && !prefix.empty()) {90 strm << prefix << "\n";91 did_print_prefix = true;92 }93 94 if (echo_commands)95 strm << prompt_string.c_str() << command << '\n';96 97 auto output_len = result.GetOutputSize();98 if (output_len) {99 const char *output = result.GetOutput();100 strm << output;101 }102 auto error_len = result.GetErrorSize();103 if (error_len) {104 const char *error = result.GetError();105 strm << error;106 }107 }108 if (check_error && got_error)109 return false; // Stop running commands.110 }111 return true;112}113 114std::string RunLLDBCommands(lldb::SBDebugger &debugger, llvm::StringRef prefix,115 const llvm::ArrayRef<std::string> &commands,116 bool &required_command_failed,117 bool parse_command_directives, bool echo_commands) {118 required_command_failed = false;119 std::string s;120 llvm::raw_string_ostream strm(s);121 required_command_failed =122 !RunLLDBCommands(debugger, prefix, commands, strm,123 parse_command_directives, echo_commands);124 return s;125}126 127bool ThreadHasStopReason(lldb::SBThread &thread) {128 switch (thread.GetStopReason()) {129 case lldb::eStopReasonTrace:130 case lldb::eStopReasonPlanComplete:131 case lldb::eStopReasonBreakpoint:132 case lldb::eStopReasonWatchpoint:133 case lldb::eStopReasonInstrumentation:134 case lldb::eStopReasonSignal:135 case lldb::eStopReasonException:136 case lldb::eStopReasonExec:137 case lldb::eStopReasonProcessorTrace:138 case lldb::eStopReasonFork:139 case lldb::eStopReasonVFork:140 case lldb::eStopReasonVForkDone:141 case lldb::eStopReasonInterrupt:142 case lldb::eStopReasonHistoryBoundary:143 return true;144 case lldb::eStopReasonThreadExiting:145 case lldb::eStopReasonInvalid:146 case lldb::eStopReasonNone:147 break;148 }149 return false;150}151 152static uint32_t constexpr THREAD_INDEX_SHIFT = 19;153 154uint32_t GetLLDBThreadIndexID(uint64_t dap_frame_id) {155 return dap_frame_id >> THREAD_INDEX_SHIFT;156}157 158uint32_t GetLLDBFrameID(uint64_t dap_frame_id) {159 return dap_frame_id & ((1u << THREAD_INDEX_SHIFT) - 1);160}161 162int64_t MakeDAPFrameID(lldb::SBFrame &frame) {163 return ((int64_t)frame.GetThread().GetIndexID() << THREAD_INDEX_SHIFT) |164 frame.GetFrameID();165}166 167lldb::SBEnvironment168GetEnvironmentFromArguments(const llvm::json::Object &arguments) {169 lldb::SBEnvironment envs{};170 constexpr llvm::StringRef env_key = "env";171 const llvm::json::Value *raw_json_env = arguments.get(env_key);172 173 if (!raw_json_env)174 return envs;175 176 if (raw_json_env->kind() == llvm::json::Value::Object) {177 auto env_map = GetStringMap(arguments, env_key);178 for (const auto &[key, value] : env_map)179 envs.Set(key.c_str(), value.c_str(), true);180 181 } else if (raw_json_env->kind() == llvm::json::Value::Array) {182 const auto envs_strings = GetStrings(&arguments, env_key);183 lldb::SBStringList entries{};184 for (const auto &env : envs_strings)185 entries.AppendString(env.c_str());186 187 envs.SetEntries(entries, true);188 }189 return envs;190}191 192lldb::StopDisassemblyType193GetStopDisassemblyDisplay(lldb::SBDebugger &debugger) {194 lldb::StopDisassemblyType result =195 lldb::StopDisassemblyType::eStopDisassemblyTypeNoDebugInfo;196 lldb::SBStructuredData string_result =197 debugger.GetSetting("stop-disassembly-display");198 const size_t result_length = string_result.GetStringValue(nullptr, 0);199 if (result_length > 0) {200 std::string result_string(result_length, '\0');201 string_result.GetStringValue(result_string.data(), result_length + 1);202 203 result =204 llvm::StringSwitch<lldb::StopDisassemblyType>(result_string)205 .Case("never", lldb::StopDisassemblyType::eStopDisassemblyTypeNever)206 .Case("always",207 lldb::StopDisassemblyType::eStopDisassemblyTypeAlways)208 .Case("no-source",209 lldb::StopDisassemblyType::eStopDisassemblyTypeNoSource)210 .Case("no-debuginfo",211 lldb::StopDisassemblyType::eStopDisassemblyTypeNoDebugInfo)212 .Default(213 lldb::StopDisassemblyType::eStopDisassemblyTypeNoDebugInfo);214 }215 216 return result;217}218 219llvm::Error ToError(const lldb::SBError &error, bool show_user) {220 if (error.Success())221 return llvm::Error::success();222 223 return llvm::make_error<DAPError>(224 /*message=*/error.GetCString(),225 /*EC=*/std::error_code(error.GetError(), std::generic_category()),226 /*show_user=*/show_user);227}228 229std::string GetStringValue(const lldb::SBStructuredData &data) {230 if (!data.IsValid())231 return "";232 233 const size_t str_length = data.GetStringValue(nullptr, 0);234 if (!str_length)235 return "";236 237 std::string str(str_length, 0);238 data.GetStringValue(str.data(), str_length + 1);239 return str;240}241 242ScopeSyncMode::ScopeSyncMode(lldb::SBDebugger &debugger)243 : m_debugger(debugger), m_async(m_debugger.GetAsync()) {244 m_debugger.SetAsync(false);245}246 247ScopeSyncMode::~ScopeSyncMode() { m_debugger.SetAsync(m_async); }248 249std::string GetSBFileSpecPath(const lldb::SBFileSpec &file_spec) {250 const auto directory_length = ::strlen(file_spec.GetDirectory());251 const auto file_name_length = ::strlen(file_spec.GetFilename());252 253 std::string path(directory_length + file_name_length + 1, '\0');254 file_spec.GetPath(path.data(), path.length() + 1);255 return path;256}257 258lldb::SBLineEntry GetLineEntryForAddress(lldb::SBTarget &target,259 const lldb::SBAddress &address) {260 lldb::SBSymbolContext sc = target.ResolveSymbolContextForAddress(261 address, lldb::eSymbolContextLineEntry);262 return sc.GetLineEntry();263}264 265} // namespace lldb_dap266