brintos

brintos / llvm-project-archived public Read only

0
0
Text · 51.2 KiB · 7a4bebf Raw
1761 lines · cpp
1//===-- SBDebugger.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 "lldb/API/SBDebugger.h"10#include "SystemInitializerFull.h"11#include "lldb/Utility/Instrumentation.h"12#include "lldb/Utility/LLDBLog.h"13 14#include "lldb/API/SBBroadcaster.h"15#include "lldb/API/SBCommandInterpreter.h"16#include "lldb/API/SBCommandInterpreterRunOptions.h"17#include "lldb/API/SBCommandReturnObject.h"18#include "lldb/API/SBError.h"19#include "lldb/API/SBEvent.h"20#include "lldb/API/SBFile.h"21#include "lldb/API/SBFrame.h"22#include "lldb/API/SBListener.h"23#include "lldb/API/SBProcess.h"24#include "lldb/API/SBSourceManager.h"25#include "lldb/API/SBStream.h"26#include "lldb/API/SBStringList.h"27#include "lldb/API/SBStructuredData.h"28#include "lldb/API/SBTarget.h"29#include "lldb/API/SBThread.h"30#include "lldb/API/SBTrace.h"31#include "lldb/API/SBTypeCategory.h"32#include "lldb/API/SBTypeFilter.h"33#include "lldb/API/SBTypeFormat.h"34#include "lldb/API/SBTypeNameSpecifier.h"35#include "lldb/API/SBTypeSummary.h"36#include "lldb/API/SBTypeSynthetic.h"37 38#include "lldb/Core/Debugger.h"39#include "lldb/Core/DebuggerEvents.h"40#include "lldb/Core/PluginManager.h"41#include "lldb/Core/Progress.h"42#include "lldb/Core/StructuredDataImpl.h"43#include "lldb/DataFormatters/DataVisualization.h"44#include "lldb/Host/Config.h"45#include "lldb/Host/StreamFile.h"46#include "lldb/Host/XML.h"47#include "lldb/Initialization/SystemLifetimeManager.h"48#include "lldb/Interpreter/CommandInterpreter.h"49#include "lldb/Interpreter/OptionArgParser.h"50#include "lldb/Interpreter/OptionGroupPlatform.h"51#include "lldb/Target/Process.h"52#include "lldb/Target/TargetList.h"53#include "lldb/Utility/Args.h"54#include "lldb/Utility/Diagnostics.h"55#include "lldb/Utility/State.h"56#include "lldb/Version/Version.h"57 58#include "llvm/ADT/STLExtras.h"59#include "llvm/ADT/StringRef.h"60#include "llvm/Config/llvm-config.h" // for LLVM_ENABLE_CURL61#include "llvm/Support/DynamicLibrary.h"62#include "llvm/Support/ManagedStatic.h"63#include "llvm/Support/PrettyStackTrace.h"64#include "llvm/Support/Signals.h"65 66using namespace lldb;67using namespace lldb_private;68 69static llvm::ManagedStatic<SystemLifetimeManager> g_debugger_lifetime;70 71SBError SBInputReader::Initialize(72    lldb::SBDebugger &sb_debugger,73    unsigned long (*callback)(void *, lldb::SBInputReader *,74                              lldb::InputReaderAction, char const *,75                              unsigned long),76    void *a, lldb::InputReaderGranularity b, char const *c, char const *d,77    bool e) {78  LLDB_INSTRUMENT_VA(this, sb_debugger, callback, a, b, c, d, e);79 80  return SBError();81}82 83void SBInputReader::SetIsDone(bool b) { LLDB_INSTRUMENT_VA(this, b); }84 85bool SBInputReader::IsActive() const {86  LLDB_INSTRUMENT_VA(this);87 88  return false;89}90 91SBDebugger::SBDebugger() { LLDB_INSTRUMENT_VA(this); }92 93SBDebugger::SBDebugger(const lldb::DebuggerSP &debugger_sp)94    : m_opaque_sp(debugger_sp) {95  LLDB_INSTRUMENT_VA(this, debugger_sp);96}97 98SBDebugger::SBDebugger(const SBDebugger &rhs) : m_opaque_sp(rhs.m_opaque_sp) {99  LLDB_INSTRUMENT_VA(this, rhs);100}101 102SBDebugger::~SBDebugger() = default;103 104SBDebugger &SBDebugger::operator=(const SBDebugger &rhs) {105  LLDB_INSTRUMENT_VA(this, rhs);106 107  if (this != &rhs) {108    m_opaque_sp = rhs.m_opaque_sp;109  }110  return *this;111}112 113const char *SBDebugger::GetBroadcasterClass() {114  LLDB_INSTRUMENT();115 116  return ConstString(Debugger::GetStaticBroadcasterClass()).AsCString();117}118 119const char *SBDebugger::GetProgressFromEvent(const lldb::SBEvent &event,120                                             uint64_t &progress_id,121                                             uint64_t &completed,122                                             uint64_t &total,123                                             bool &is_debugger_specific) {124  LLDB_INSTRUMENT_VA(event);125 126  const ProgressEventData *progress_data =127      ProgressEventData::GetEventDataFromEvent(event.get());128  if (progress_data == nullptr)129    return nullptr;130  progress_id = progress_data->GetID();131  completed = progress_data->GetCompleted();132  total = progress_data->GetTotal();133  is_debugger_specific = progress_data->IsDebuggerSpecific();134  ConstString message(progress_data->GetMessage());135  return message.AsCString();136}137 138lldb::SBStructuredData139SBDebugger::GetProgressDataFromEvent(const lldb::SBEvent &event) {140  LLDB_INSTRUMENT_VA(event);141 142  StructuredData::DictionarySP dictionary_sp =143      ProgressEventData::GetAsStructuredData(event.get());144 145  if (!dictionary_sp)146    return {};147 148  SBStructuredData data;149  data.m_impl_up->SetObjectSP(std::move(dictionary_sp));150  return data;151}152 153lldb::SBStructuredData154SBDebugger::GetDiagnosticFromEvent(const lldb::SBEvent &event) {155  LLDB_INSTRUMENT_VA(event);156 157  StructuredData::DictionarySP dictionary_sp =158      DiagnosticEventData::GetAsStructuredData(event.get());159 160  if (!dictionary_sp)161    return {};162 163  SBStructuredData data;164  data.m_impl_up->SetObjectSP(std::move(dictionary_sp));165  return data;166}167 168SBBroadcaster SBDebugger::GetBroadcaster() {169  LLDB_INSTRUMENT_VA(this);170  SBBroadcaster broadcaster(&m_opaque_sp->GetBroadcaster(), false);171  return broadcaster;172}173 174void SBDebugger::Initialize() {175  LLDB_INSTRUMENT();176  SBError ignored = SBDebugger::InitializeWithErrorHandling();177}178 179lldb::SBError SBDebugger::InitializeWithErrorHandling() {180  LLDB_INSTRUMENT();181 182  SBError error;183  if (auto e = g_debugger_lifetime->Initialize(184          std::make_unique<SystemInitializerFull>())) {185    error.SetError(Status::FromError(std::move(e)));186  }187  return error;188}189 190void SBDebugger::PrintStackTraceOnError() {191  LLDB_INSTRUMENT();192 193  llvm::EnablePrettyStackTrace();194  static std::string executable =195      llvm::sys::fs::getMainExecutable(nullptr, nullptr);196  llvm::sys::PrintStackTraceOnErrorSignal(executable);197}198 199static void DumpDiagnostics(void *cookie) {200  Diagnostics::Instance().Dump(llvm::errs());201}202 203void SBDebugger::PrintDiagnosticsOnError() {204  LLDB_INSTRUMENT();205 206  llvm::sys::AddSignalHandler(&DumpDiagnostics, nullptr);207}208 209void SBDebugger::Terminate() {210  LLDB_INSTRUMENT();211 212  g_debugger_lifetime->Terminate();213}214 215void SBDebugger::Clear() {216  LLDB_INSTRUMENT_VA(this);217 218  if (m_opaque_sp)219    m_opaque_sp->ClearIOHandlers();220 221  m_opaque_sp.reset();222}223 224SBDebugger SBDebugger::Create() {225  LLDB_INSTRUMENT();226 227  return SBDebugger::Create(false, nullptr, nullptr);228}229 230SBDebugger SBDebugger::Create(bool source_init_files) {231  LLDB_INSTRUMENT_VA(source_init_files);232 233  return SBDebugger::Create(source_init_files, nullptr, nullptr);234}235 236SBDebugger SBDebugger::Create(bool source_init_files,237                              lldb::LogOutputCallback callback, void *baton)238 239{240  LLDB_INSTRUMENT_VA(source_init_files, callback, baton);241 242  SBDebugger debugger;243 244  // Currently we have issues if this function is called simultaneously on two245  // different threads. The issues mainly revolve around the fact that the246  // lldb_private::FormatManager uses global collections and having two threads247  // parsing the .lldbinit files can cause mayhem. So to get around this for248  // now we need to use a mutex to prevent bad things from happening.249  static std::recursive_mutex g_mutex;250  std::lock_guard<std::recursive_mutex> guard(g_mutex);251 252  debugger.reset(Debugger::CreateInstance(callback, baton));253 254  SBCommandInterpreter interp = debugger.GetCommandInterpreter();255  if (source_init_files) {256    interp.get()->SkipLLDBInitFiles(false);257    interp.get()->SkipAppInitFiles(false);258    SBCommandReturnObject result;259    interp.SourceInitFileInGlobalDirectory(result);260    interp.SourceInitFileInHomeDirectory(result, false);261  } else {262    interp.get()->SkipLLDBInitFiles(true);263    interp.get()->SkipAppInitFiles(true);264  }265  return debugger;266}267 268void SBDebugger::Destroy(SBDebugger &debugger) {269  LLDB_INSTRUMENT_VA(debugger);270 271  Debugger::Destroy(debugger.m_opaque_sp);272 273  if (debugger.m_opaque_sp.get() != nullptr)274    debugger.m_opaque_sp.reset();275}276 277void SBDebugger::MemoryPressureDetected() {278  LLDB_INSTRUMENT();279 280  // Since this function can be call asynchronously, we allow it to be non-281  // mandatory. We have seen deadlocks with this function when called so we282  // need to safeguard against this until we can determine what is causing the283  // deadlocks.284 285  const bool mandatory = false;286 287  ModuleList::RemoveOrphanSharedModules(mandatory);288}289 290bool SBDebugger::IsValid() const {291  LLDB_INSTRUMENT_VA(this);292  return this->operator bool();293}294SBDebugger::operator bool() const {295  LLDB_INSTRUMENT_VA(this);296 297  return m_opaque_sp.get() != nullptr;298}299 300void SBDebugger::SetAsync(bool b) {301  LLDB_INSTRUMENT_VA(this, b);302 303  if (m_opaque_sp)304    m_opaque_sp->SetAsyncExecution(b);305}306 307bool SBDebugger::GetAsync() {308  LLDB_INSTRUMENT_VA(this);309 310  return (m_opaque_sp ? m_opaque_sp->GetAsyncExecution() : false);311}312 313void SBDebugger::SkipLLDBInitFiles(bool b) {314  LLDB_INSTRUMENT_VA(this, b);315 316  if (m_opaque_sp)317    m_opaque_sp->GetCommandInterpreter().SkipLLDBInitFiles(b);318}319 320void SBDebugger::SkipAppInitFiles(bool b) {321  LLDB_INSTRUMENT_VA(this, b);322 323  if (m_opaque_sp)324    m_opaque_sp->GetCommandInterpreter().SkipAppInitFiles(b);325}326 327void SBDebugger::SetInputFileHandle(FILE *fh, bool transfer_ownership) {328  LLDB_INSTRUMENT_VA(this, fh, transfer_ownership);329  if (m_opaque_sp)330    m_opaque_sp->SetInputFile((FileSP)std::make_shared<NativeFile>(331        fh, File::eOpenOptionReadOnly, transfer_ownership));332}333 334SBError SBDebugger::SetInputString(const char *data) {335  LLDB_INSTRUMENT_VA(this, data);336  SBError sb_error;337  if (data == nullptr) {338    sb_error = Status::FromErrorString("String data is null");339    return sb_error;340  }341 342  size_t size = strlen(data);343  if (size == 0) {344    sb_error = Status::FromErrorString("String data is empty");345    return sb_error;346  }347 348  if (!m_opaque_sp) {349    sb_error = Status::FromErrorString("invalid debugger");350    return sb_error;351  }352 353  sb_error.SetError(m_opaque_sp->SetInputString(data));354  return sb_error;355}356 357// Shouldn't really be settable after initialization as this could cause lots358// of problems; don't want users trying to switch modes in the middle of a359// debugging session.360SBError SBDebugger::SetInputFile(SBFile file) {361  LLDB_INSTRUMENT_VA(this, file);362 363  SBError error;364  if (!m_opaque_sp) {365    error.ref() = Status::FromErrorString("invalid debugger");366    return error;367  }368  if (!file) {369    error.ref() = Status::FromErrorString("invalid file");370    return error;371  }372  m_opaque_sp->SetInputFile(file.m_opaque_sp);373  return error;374}375 376SBError SBDebugger::SetInputFile(FileSP file_sp) {377  LLDB_INSTRUMENT_VA(this, file_sp);378  return SetInputFile(SBFile(file_sp));379}380 381SBError SBDebugger::SetOutputFile(FileSP file_sp) {382  LLDB_INSTRUMENT_VA(this, file_sp);383  return SetOutputFile(SBFile(file_sp));384}385 386void SBDebugger::SetOutputFileHandle(FILE *fh, bool transfer_ownership) {387  LLDB_INSTRUMENT_VA(this, fh, transfer_ownership);388  SetOutputFile((FileSP)std::make_shared<NativeFile>(389      fh, File::eOpenOptionWriteOnly, transfer_ownership));390}391 392SBError SBDebugger::SetOutputFile(SBFile file) {393  LLDB_INSTRUMENT_VA(this, file);394  SBError error;395  if (!m_opaque_sp) {396    error.ref() = Status::FromErrorString("invalid debugger");397    return error;398  }399  if (!file) {400    error.ref() = Status::FromErrorString("invalid file");401    return error;402  }403  m_opaque_sp->SetOutputFile(file.m_opaque_sp);404  return error;405}406 407void SBDebugger::SetErrorFileHandle(FILE *fh, bool transfer_ownership) {408  LLDB_INSTRUMENT_VA(this, fh, transfer_ownership);409  SetErrorFile((FileSP)std::make_shared<NativeFile>(410      fh, File::eOpenOptionWriteOnly, transfer_ownership));411}412 413SBError SBDebugger::SetErrorFile(FileSP file_sp) {414  LLDB_INSTRUMENT_VA(this, file_sp);415  return SetErrorFile(SBFile(file_sp));416}417 418SBError SBDebugger::SetErrorFile(SBFile file) {419  LLDB_INSTRUMENT_VA(this, file);420  SBError error;421  if (!m_opaque_sp) {422    error.ref() = Status::FromErrorString("invalid debugger");423    return error;424  }425  if (!file) {426    error.ref() = Status::FromErrorString("invalid file");427    return error;428  }429  m_opaque_sp->SetErrorFile(file.m_opaque_sp);430  return error;431}432 433lldb::SBStructuredData SBDebugger::GetSetting(const char *setting) {434  LLDB_INSTRUMENT_VA(this, setting);435 436  SBStructuredData data;437  if (!m_opaque_sp)438    return data;439 440  StreamString json_strm;441  ExecutionContext exe_ctx(442      m_opaque_sp->GetCommandInterpreter().GetExecutionContext());443  if (setting && strlen(setting) > 0)444    m_opaque_sp->DumpPropertyValue(&exe_ctx, json_strm, setting,445                                   /*dump_mask*/ 0,446                                   /*is_json*/ true);447  else448    m_opaque_sp->DumpAllPropertyValues(&exe_ctx, json_strm, /*dump_mask*/ 0,449                                       /*is_json*/ true);450 451  data.m_impl_up->SetObjectSP(StructuredData::ParseJSON(json_strm.GetString()));452  return data;453}454 455FILE *SBDebugger::GetInputFileHandle() {456  LLDB_INSTRUMENT_VA(this);457  if (m_opaque_sp) {458    File &file_sp = m_opaque_sp->GetInputFile();459    return file_sp.GetStream();460  }461  return nullptr;462}463 464SBFile SBDebugger::GetInputFile() {465  LLDB_INSTRUMENT_VA(this);466  if (m_opaque_sp) {467    return SBFile(m_opaque_sp->GetInputFileSP());468  }469  return SBFile();470}471 472FILE *SBDebugger::GetOutputFileHandle() {473  LLDB_INSTRUMENT_VA(this);474  if (m_opaque_sp)475    return m_opaque_sp->GetOutputFileSP()->GetStream();476  return nullptr;477}478 479SBFile SBDebugger::GetOutputFile() {480  LLDB_INSTRUMENT_VA(this);481  if (m_opaque_sp)482    return SBFile(m_opaque_sp->GetOutputFileSP());483  return SBFile();484}485 486FILE *SBDebugger::GetErrorFileHandle() {487  LLDB_INSTRUMENT_VA(this);488 489  if (m_opaque_sp)490    return m_opaque_sp->GetErrorFileSP()->GetStream();491  return nullptr;492}493 494SBFile SBDebugger::GetErrorFile() {495  LLDB_INSTRUMENT_VA(this);496  SBFile file;497  if (m_opaque_sp)498    return SBFile(m_opaque_sp->GetErrorFileSP());499  return SBFile();500}501 502void SBDebugger::SaveInputTerminalState() {503  LLDB_INSTRUMENT_VA(this);504 505  if (m_opaque_sp)506    m_opaque_sp->SaveInputTerminalState();507}508 509void SBDebugger::RestoreInputTerminalState() {510  LLDB_INSTRUMENT_VA(this);511 512  if (m_opaque_sp)513    m_opaque_sp->RestoreInputTerminalState();514}515SBCommandInterpreter SBDebugger::GetCommandInterpreter() {516  LLDB_INSTRUMENT_VA(this);517 518  SBCommandInterpreter sb_interpreter;519  if (m_opaque_sp)520    sb_interpreter.reset(&m_opaque_sp->GetCommandInterpreter());521 522  return sb_interpreter;523}524 525void SBDebugger::HandleCommand(const char *command) {526  LLDB_INSTRUMENT_VA(this, command);527 528  if (m_opaque_sp) {529    TargetSP target_sp(m_opaque_sp->GetSelectedTarget());530    std::unique_lock<std::recursive_mutex> lock;531    if (target_sp)532      lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex());533 534    SBCommandInterpreter sb_interpreter(GetCommandInterpreter());535    SBCommandReturnObject result;536 537    sb_interpreter.HandleCommand(command, result, false);538 539    result.PutError(m_opaque_sp->GetErrorFileSP());540    result.PutOutput(m_opaque_sp->GetOutputFileSP());541 542    if (!m_opaque_sp->GetAsyncExecution()) {543      SBProcess process(GetCommandInterpreter().GetProcess());544      ProcessSP process_sp(process.GetSP());545      if (process_sp) {546        EventSP event_sp;547        ListenerSP lldb_listener_sp = m_opaque_sp->GetListener();548        while (lldb_listener_sp->GetEventForBroadcaster(549            process_sp.get(), event_sp, std::chrono::seconds(0))) {550          SBEvent event(event_sp);551          HandleProcessEvent(process, event, GetOutputFile(), GetErrorFile());552        }553      }554    }555  }556}557 558SBListener SBDebugger::GetListener() {559  LLDB_INSTRUMENT_VA(this);560 561  SBListener sb_listener;562  if (m_opaque_sp)563    sb_listener.reset(m_opaque_sp->GetListener());564 565  return sb_listener;566}567 568void SBDebugger::HandleProcessEvent(const SBProcess &process,569                                    const SBEvent &event, SBFile out,570                                    SBFile err) {571  LLDB_INSTRUMENT_VA(this, process, event, out, err);572 573  return HandleProcessEvent(process, event, out.m_opaque_sp, err.m_opaque_sp);574}575 576void SBDebugger::HandleProcessEvent(const SBProcess &process,577                                    const SBEvent &event, FILE *out,578                                    FILE *err) {579  LLDB_INSTRUMENT_VA(this, process, event, out, err);580 581  FileSP outfile =582      std::make_shared<NativeFile>(out, File::eOpenOptionWriteOnly, false);583  FileSP errfile =584      std::make_shared<NativeFile>(err, File::eOpenOptionWriteOnly, false);585  return HandleProcessEvent(process, event, outfile, errfile);586}587 588void SBDebugger::HandleProcessEvent(const SBProcess &process,589                                    const SBEvent &event, FileSP out_sp,590                                    FileSP err_sp) {591 592  LLDB_INSTRUMENT_VA(this, process, event, out_sp, err_sp);593 594  if (!process.IsValid())595    return;596 597  TargetSP target_sp(process.GetTarget().GetSP());598  if (!target_sp)599    return;600 601  const uint32_t event_type = event.GetType();602  char stdio_buffer[1024];603  size_t len;604 605  std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());606 607  if (event_type &608      (Process::eBroadcastBitSTDOUT | Process::eBroadcastBitStateChanged)) {609    // Drain stdout when we stop just in case we have any bytes610    while ((len = process.GetSTDOUT(stdio_buffer, sizeof(stdio_buffer))) > 0)611      if (out_sp)612        out_sp->Write(stdio_buffer, len);613  }614 615  if (event_type &616      (Process::eBroadcastBitSTDERR | Process::eBroadcastBitStateChanged)) {617    // Drain stderr when we stop just in case we have any bytes618    while ((len = process.GetSTDERR(stdio_buffer, sizeof(stdio_buffer))) > 0)619      if (err_sp)620        err_sp->Write(stdio_buffer, len);621  }622 623  if (event_type & Process::eBroadcastBitStateChanged) {624    StateType event_state = SBProcess::GetStateFromEvent(event);625 626    if (event_state == eStateInvalid)627      return;628 629    bool is_stopped = StateIsStoppedState(event_state);630    if (!is_stopped)631      process.ReportEventState(event, out_sp);632  }633}634 635SBSourceManager SBDebugger::GetSourceManager() {636  LLDB_INSTRUMENT_VA(this);637 638  SBSourceManager sb_source_manager(*this);639  return sb_source_manager;640}641 642bool SBDebugger::GetDefaultArchitecture(char *arch_name, size_t arch_name_len) {643  LLDB_INSTRUMENT_VA(arch_name, arch_name_len);644 645  if (arch_name && arch_name_len) {646    ArchSpec default_arch = Target::GetDefaultArchitecture();647 648    if (default_arch.IsValid()) {649      const std::string &triple_str = default_arch.GetTriple().str();650      if (!triple_str.empty())651        ::snprintf(arch_name, arch_name_len, "%s", triple_str.c_str());652      else653        ::snprintf(arch_name, arch_name_len, "%s",654                   default_arch.GetArchitectureName());655      return true;656    }657  }658  if (arch_name && arch_name_len)659    arch_name[0] = '\0';660  return false;661}662 663bool SBDebugger::SetDefaultArchitecture(const char *arch_name) {664  LLDB_INSTRUMENT_VA(arch_name);665 666  if (arch_name) {667    ArchSpec arch(arch_name);668    if (arch.IsValid()) {669      Target::SetDefaultArchitecture(arch);670      return true;671    }672  }673  return false;674}675 676ScriptLanguage677SBDebugger::GetScriptingLanguage(const char *script_language_name) {678  LLDB_INSTRUMENT_VA(this, script_language_name);679 680  if (!script_language_name)681    return eScriptLanguageDefault;682  return OptionArgParser::ToScriptLanguage(683      llvm::StringRef(script_language_name), eScriptLanguageDefault, nullptr);684}685 686SBStructuredData687SBDebugger::GetScriptInterpreterInfo(lldb::ScriptLanguage language) {688  LLDB_INSTRUMENT_VA(this, language);689  SBStructuredData data;690  if (m_opaque_sp) {691    lldb_private::ScriptInterpreter *interp =692        m_opaque_sp->GetScriptInterpreter(language);693    if (interp) {694      data.m_impl_up->SetObjectSP(interp->GetInterpreterInfo());695    }696  }697  return data;698}699 700const char *SBDebugger::GetVersionString() {701  LLDB_INSTRUMENT();702 703  return lldb_private::GetVersion();704}705 706const char *SBDebugger::StateAsCString(StateType state) {707  LLDB_INSTRUMENT_VA(state);708 709  return lldb_private::StateAsCString(state);710}711 712static void AddBoolConfigEntry(StructuredData::Dictionary &dict,713                               llvm::StringRef name, bool value,714                               llvm::StringRef description) {715  auto entry_up = std::make_unique<StructuredData::Dictionary>();716  entry_up->AddBooleanItem("value", value);717  entry_up->AddStringItem("description", description);718  dict.AddItem(name, std::move(entry_up));719}720 721static void AddLLVMTargets(StructuredData::Dictionary &dict) {722  auto array_up = std::make_unique<StructuredData::Array>();723#define LLVM_TARGET(target)                                                    \724  array_up->AddItem(std::make_unique<StructuredData::String>(#target));725#include "llvm/Config/Targets.def"726  auto entry_up = std::make_unique<StructuredData::Dictionary>();727  entry_up->AddItem("value", std::move(array_up));728  entry_up->AddStringItem("description", "A list of configured LLVM targets.");729  dict.AddItem("targets", std::move(entry_up));730}731 732SBStructuredData SBDebugger::GetBuildConfiguration() {733  LLDB_INSTRUMENT();734 735  auto config_up = std::make_unique<StructuredData::Dictionary>();736  AddBoolConfigEntry(737      *config_up, "xml", XMLDocument::XMLEnabled(),738      "A boolean value that indicates if XML support is enabled in LLDB");739  AddBoolConfigEntry(740      *config_up, "curl", LLVM_ENABLE_CURL,741      "A boolean value that indicates if CURL support is enabled in LLDB");742  AddBoolConfigEntry(743      *config_up, "curses", LLDB_ENABLE_CURSES,744      "A boolean value that indicates if curses support is enabled in LLDB");745  AddBoolConfigEntry(746      *config_up, "editline", LLDB_ENABLE_LIBEDIT,747      "A boolean value that indicates if editline support is enabled in LLDB");748  AddBoolConfigEntry(*config_up, "editline_wchar", LLDB_EDITLINE_USE_WCHAR,749                     "A boolean value that indicates if editline wide "750                     "characters support is enabled in LLDB");751  AddBoolConfigEntry(752      *config_up, "lzma", LLDB_ENABLE_LZMA,753      "A boolean value that indicates if lzma support is enabled in LLDB");754  AddBoolConfigEntry(755      *config_up, "python", LLDB_ENABLE_PYTHON,756      "A boolean value that indicates if python support is enabled in LLDB");757  AddBoolConfigEntry(758      *config_up, "lua", LLDB_ENABLE_LUA,759      "A boolean value that indicates if lua support is enabled in LLDB");760  AddBoolConfigEntry(*config_up, "fbsdvmcore", LLDB_ENABLE_FBSDVMCORE,761                     "A boolean value that indicates if fbsdvmcore support is "762                     "enabled in LLDB");763  AddLLVMTargets(*config_up);764 765  SBStructuredData data;766  data.m_impl_up->SetObjectSP(std::move(config_up));767  return data;768}769 770bool SBDebugger::StateIsRunningState(StateType state) {771  LLDB_INSTRUMENT_VA(state);772 773  const bool result = lldb_private::StateIsRunningState(state);774 775  return result;776}777 778bool SBDebugger::StateIsStoppedState(StateType state) {779  LLDB_INSTRUMENT_VA(state);780 781  const bool result = lldb_private::StateIsStoppedState(state, false);782 783  return result;784}785 786lldb::SBTarget SBDebugger::CreateTarget(const char *filename,787                                        const char *target_triple,788                                        const char *platform_name,789                                        bool add_dependent_modules,790                                        lldb::SBError &sb_error) {791  LLDB_INSTRUMENT_VA(this, filename, target_triple, platform_name,792                     add_dependent_modules, sb_error);793 794  SBTarget sb_target;795  TargetSP target_sp;796  if (m_opaque_sp) {797    sb_error.Clear();798    OptionGroupPlatform platform_options(false);799    platform_options.SetPlatformName(platform_name);800 801    sb_error.ref() = m_opaque_sp->GetTargetList().CreateTarget(802        *m_opaque_sp, filename, target_triple,803        add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo,804        &platform_options, target_sp);805 806    if (sb_error.Success())807      sb_target.SetSP(target_sp);808  } else {809    sb_error = Status::FromErrorString("invalid debugger");810  }811 812  Log *log = GetLog(LLDBLog::API);813  LLDB_LOGF(log,814            "SBDebugger(%p)::CreateTarget (filename=\"%s\", triple=%s, "815            "platform_name=%s, add_dependent_modules=%u, error=%s) => "816            "SBTarget(%p)",817            static_cast<void *>(m_opaque_sp.get()), filename, target_triple,818            platform_name, add_dependent_modules, sb_error.GetCString(),819            static_cast<void *>(target_sp.get()));820 821  return sb_target;822}823 824SBTarget825SBDebugger::CreateTargetWithFileAndTargetTriple(const char *filename,826                                                const char *target_triple) {827  LLDB_INSTRUMENT_VA(this, filename, target_triple);828 829  SBTarget sb_target;830  TargetSP target_sp;831  if (m_opaque_sp) {832    const bool add_dependent_modules = true;833    Status error(m_opaque_sp->GetTargetList().CreateTarget(834        *m_opaque_sp, filename, target_triple,835        add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo, nullptr,836        target_sp));837    sb_target.SetSP(target_sp);838  }839 840  Log *log = GetLog(LLDBLog::API);841  LLDB_LOGF(log,842            "SBDebugger(%p)::CreateTargetWithFileAndTargetTriple "843            "(filename=\"%s\", triple=%s) => SBTarget(%p)",844            static_cast<void *>(m_opaque_sp.get()), filename, target_triple,845            static_cast<void *>(target_sp.get()));846 847  return sb_target;848}849 850SBTarget SBDebugger::CreateTargetWithFileAndArch(const char *filename,851                                                 const char *arch_cstr) {852  LLDB_INSTRUMENT_VA(this, filename, arch_cstr);853 854  Log *log = GetLog(LLDBLog::API);855 856  SBTarget sb_target;857  TargetSP target_sp;858  if (m_opaque_sp) {859    Status error;860    if (arch_cstr == nullptr) {861      // The version of CreateTarget that takes an ArchSpec won't accept an862      // empty ArchSpec, so when the arch hasn't been specified, we need to863      // call the target triple version.864      error = m_opaque_sp->GetTargetList().CreateTarget(865          *m_opaque_sp, filename, arch_cstr, eLoadDependentsYes, nullptr,866          target_sp);867    } else {868      PlatformSP platform_sp =869          m_opaque_sp->GetPlatformList().GetSelectedPlatform();870      ArchSpec arch =871          Platform::GetAugmentedArchSpec(platform_sp.get(), arch_cstr);872      if (arch.IsValid())873        error = m_opaque_sp->GetTargetList().CreateTarget(874            *m_opaque_sp, filename, arch, eLoadDependentsYes, platform_sp,875            target_sp);876      else877        error = Status::FromErrorStringWithFormat("invalid arch_cstr: %s",878                                                  arch_cstr);879    }880    if (error.Success())881      sb_target.SetSP(target_sp);882  }883 884  LLDB_LOGF(log,885            "SBDebugger(%p)::CreateTargetWithFileAndArch (filename=\"%s\", "886            "arch=%s) => SBTarget(%p)",887            static_cast<void *>(m_opaque_sp.get()),888            filename ? filename : "<unspecified>",889            arch_cstr ? arch_cstr : "<unspecified>",890            static_cast<void *>(target_sp.get()));891 892  return sb_target;893}894 895SBTarget SBDebugger::CreateTarget(const char *filename) {896  LLDB_INSTRUMENT_VA(this, filename);897 898  SBTarget sb_target;899  TargetSP target_sp;900  if (m_opaque_sp) {901    Status error;902    const bool add_dependent_modules = true;903    error = m_opaque_sp->GetTargetList().CreateTarget(904        *m_opaque_sp, filename, "",905        add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo, nullptr,906        target_sp);907 908    if (error.Success())909      sb_target.SetSP(target_sp);910  }911  Log *log = GetLog(LLDBLog::API);912  LLDB_LOGF(log,913            "SBDebugger(%p)::CreateTarget (filename=\"%s\") => SBTarget(%p)",914            static_cast<void *>(m_opaque_sp.get()), filename,915            static_cast<void *>(target_sp.get()));916  return sb_target;917}918 919SBTarget SBDebugger::GetDummyTarget() {920  LLDB_INSTRUMENT_VA(this);921 922  SBTarget sb_target;923  if (m_opaque_sp) {924    sb_target.SetSP(m_opaque_sp->GetDummyTarget().shared_from_this());925  }926  Log *log = GetLog(LLDBLog::API);927  LLDB_LOGF(log, "SBDebugger(%p)::GetDummyTarget() => SBTarget(%p)",928            static_cast<void *>(m_opaque_sp.get()),929            static_cast<void *>(sb_target.GetSP().get()));930  return sb_target;931}932 933void SBDebugger::DispatchClientTelemetry(const lldb::SBStructuredData &entry) {934  LLDB_INSTRUMENT_VA(this);935  if (m_opaque_sp) {936    m_opaque_sp->DispatchClientTelemetry(*entry.m_impl_up);937  } else {938    Log *log = GetLog(LLDBLog::API);939    LLDB_LOGF(log,940              "Could not send telemetry from SBDebugger - debugger was null.");941  }942}943 944bool SBDebugger::DeleteTarget(lldb::SBTarget &target) {945  LLDB_INSTRUMENT_VA(this, target);946 947  bool result = false;948  if (m_opaque_sp) {949    TargetSP target_sp(target.GetSP());950    if (target_sp) {951      // No need to lock, the target list is thread safe952      result = m_opaque_sp->GetTargetList().DeleteTarget(target_sp);953      target_sp->Destroy();954      target.Clear();955    }956  }957 958  Log *log = GetLog(LLDBLog::API);959  LLDB_LOGF(log, "SBDebugger(%p)::DeleteTarget (SBTarget(%p)) => %i",960            static_cast<void *>(m_opaque_sp.get()),961            static_cast<void *>(target.m_opaque_sp.get()), result);962 963  return result;964}965 966SBTarget SBDebugger::GetTargetAtIndex(uint32_t idx) {967  LLDB_INSTRUMENT_VA(this, idx);968 969  SBTarget sb_target;970  if (m_opaque_sp) {971    // No need to lock, the target list is thread safe972    sb_target.SetSP(m_opaque_sp->GetTargetList().GetTargetAtIndex(idx));973  }974  return sb_target;975}976 977uint32_t SBDebugger::GetIndexOfTarget(lldb::SBTarget target) {978  LLDB_INSTRUMENT_VA(this, target);979 980  lldb::TargetSP target_sp = target.GetSP();981  if (!target_sp)982    return UINT32_MAX;983 984  if (!m_opaque_sp)985    return UINT32_MAX;986 987  return m_opaque_sp->GetTargetList().GetIndexOfTarget(target.GetSP());988}989 990SBTarget SBDebugger::FindTargetByGloballyUniqueID(lldb::user_id_t id) {991  LLDB_INSTRUMENT_VA(this, id);992  SBTarget sb_target;993  if (m_opaque_sp) {994    // No need to lock, the target list is thread safe995    sb_target.SetSP(996        m_opaque_sp->GetTargetList().FindTargetByGloballyUniqueID(id));997  }998  return sb_target;999}1000 1001SBTarget SBDebugger::FindTargetWithProcessID(lldb::pid_t pid) {1002  LLDB_INSTRUMENT_VA(this, pid);1003 1004  SBTarget sb_target;1005  if (m_opaque_sp) {1006    // No need to lock, the target list is thread safe1007    sb_target.SetSP(m_opaque_sp->GetTargetList().FindTargetWithProcessID(pid));1008  }1009  return sb_target;1010}1011 1012SBTarget SBDebugger::FindTargetWithFileAndArch(const char *filename,1013                                               const char *arch_name) {1014  LLDB_INSTRUMENT_VA(this, filename, arch_name);1015 1016  SBTarget sb_target;1017  if (m_opaque_sp && filename && filename[0]) {1018    // No need to lock, the target list is thread safe1019    ArchSpec arch = Platform::GetAugmentedArchSpec(1020        m_opaque_sp->GetPlatformList().GetSelectedPlatform().get(), arch_name);1021    TargetSP target_sp(1022        m_opaque_sp->GetTargetList().FindTargetWithExecutableAndArchitecture(1023            FileSpec(filename), arch_name ? &arch : nullptr));1024    sb_target.SetSP(target_sp);1025  }1026  return sb_target;1027}1028 1029SBTarget SBDebugger::FindTargetWithLLDBProcess(const ProcessSP &process_sp) {1030  SBTarget sb_target;1031  if (m_opaque_sp) {1032    // No need to lock, the target list is thread safe1033    sb_target.SetSP(1034        m_opaque_sp->GetTargetList().FindTargetWithProcess(process_sp.get()));1035  }1036  return sb_target;1037}1038 1039uint32_t SBDebugger::GetNumTargets() {1040  LLDB_INSTRUMENT_VA(this);1041 1042  if (m_opaque_sp) {1043    // No need to lock, the target list is thread safe1044    return m_opaque_sp->GetTargetList().GetNumTargets();1045  }1046  return 0;1047}1048 1049SBTarget SBDebugger::GetSelectedTarget() {1050  LLDB_INSTRUMENT_VA(this);1051 1052  Log *log = GetLog(LLDBLog::API);1053 1054  SBTarget sb_target;1055  TargetSP target_sp;1056  if (m_opaque_sp) {1057    // No need to lock, the target list is thread safe1058    target_sp = m_opaque_sp->GetTargetList().GetSelectedTarget();1059    sb_target.SetSP(target_sp);1060  }1061 1062  if (log) {1063    SBStream sstr;1064    sb_target.GetDescription(sstr, eDescriptionLevelBrief);1065    LLDB_LOGF(log, "SBDebugger(%p)::GetSelectedTarget () => SBTarget(%p): %s",1066              static_cast<void *>(m_opaque_sp.get()),1067              static_cast<void *>(target_sp.get()), sstr.GetData());1068  }1069 1070  return sb_target;1071}1072 1073void SBDebugger::SetSelectedTarget(SBTarget &sb_target) {1074  LLDB_INSTRUMENT_VA(this, sb_target);1075 1076  Log *log = GetLog(LLDBLog::API);1077 1078  TargetSP target_sp(sb_target.GetSP());1079  if (m_opaque_sp) {1080    m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp);1081  }1082  if (log) {1083    SBStream sstr;1084    sb_target.GetDescription(sstr, eDescriptionLevelBrief);1085    LLDB_LOGF(log, "SBDebugger(%p)::SetSelectedTarget () => SBTarget(%p): %s",1086              static_cast<void *>(m_opaque_sp.get()),1087              static_cast<void *>(target_sp.get()), sstr.GetData());1088  }1089}1090 1091SBPlatform SBDebugger::GetSelectedPlatform() {1092  LLDB_INSTRUMENT_VA(this);1093 1094  Log *log = GetLog(LLDBLog::API);1095 1096  SBPlatform sb_platform;1097  DebuggerSP debugger_sp(m_opaque_sp);1098  if (debugger_sp) {1099    sb_platform.SetSP(debugger_sp->GetPlatformList().GetSelectedPlatform());1100  }1101  LLDB_LOGF(log, "SBDebugger(%p)::GetSelectedPlatform () => SBPlatform(%p): %s",1102            static_cast<void *>(m_opaque_sp.get()),1103            static_cast<void *>(sb_platform.GetSP().get()),1104            sb_platform.GetName());1105  return sb_platform;1106}1107 1108void SBDebugger::SetSelectedPlatform(SBPlatform &sb_platform) {1109  LLDB_INSTRUMENT_VA(this, sb_platform);1110 1111  Log *log = GetLog(LLDBLog::API);1112 1113  DebuggerSP debugger_sp(m_opaque_sp);1114  if (debugger_sp) {1115    debugger_sp->GetPlatformList().SetSelectedPlatform(sb_platform.GetSP());1116  }1117 1118  LLDB_LOGF(log, "SBDebugger(%p)::SetSelectedPlatform (SBPlatform(%p) %s)",1119            static_cast<void *>(m_opaque_sp.get()),1120            static_cast<void *>(sb_platform.GetSP().get()),1121            sb_platform.GetName());1122}1123 1124uint32_t SBDebugger::GetNumPlatforms() {1125  LLDB_INSTRUMENT_VA(this);1126 1127  if (m_opaque_sp) {1128    // No need to lock, the platform list is thread safe1129    return m_opaque_sp->GetPlatformList().GetSize();1130  }1131  return 0;1132}1133 1134SBPlatform SBDebugger::GetPlatformAtIndex(uint32_t idx) {1135  LLDB_INSTRUMENT_VA(this, idx);1136 1137  SBPlatform sb_platform;1138  if (m_opaque_sp) {1139    // No need to lock, the platform list is thread safe1140    sb_platform.SetSP(m_opaque_sp->GetPlatformList().GetAtIndex(idx));1141  }1142  return sb_platform;1143}1144 1145uint32_t SBDebugger::GetNumAvailablePlatforms() {1146  LLDB_INSTRUMENT_VA(this);1147 1148  uint32_t idx = 0;1149  while (true) {1150    if (PluginManager::GetPlatformPluginNameAtIndex(idx).empty()) {1151      break;1152    }1153    ++idx;1154  }1155  // +1 for the host platform, which should always appear first in the list.1156  return idx + 1;1157}1158 1159SBStructuredData SBDebugger::GetAvailablePlatformInfoAtIndex(uint32_t idx) {1160  LLDB_INSTRUMENT_VA(this, idx);1161 1162  SBStructuredData data;1163  auto platform_dict = std::make_unique<StructuredData::Dictionary>();1164  llvm::StringRef name_str("name"), desc_str("description");1165 1166  if (idx == 0) {1167    PlatformSP host_platform_sp(Platform::GetHostPlatform());1168    platform_dict->AddStringItem(name_str, host_platform_sp->GetPluginName());1169    platform_dict->AddStringItem(1170        desc_str, llvm::StringRef(host_platform_sp->GetDescription()));1171  } else if (idx > 0) {1172    llvm::StringRef plugin_name =1173        PluginManager::GetPlatformPluginNameAtIndex(idx - 1);1174    if (plugin_name.empty()) {1175      return data;1176    }1177    platform_dict->AddStringItem(name_str, llvm::StringRef(plugin_name));1178 1179    llvm::StringRef plugin_desc =1180        PluginManager::GetPlatformPluginDescriptionAtIndex(idx - 1);1181    platform_dict->AddStringItem(desc_str, llvm::StringRef(plugin_desc));1182  }1183 1184  data.m_impl_up->SetObjectSP(1185      StructuredData::ObjectSP(platform_dict.release()));1186  return data;1187}1188 1189void SBDebugger::DispatchInput(void *baton, const void *data, size_t data_len) {1190  LLDB_INSTRUMENT_VA(this, baton, data, data_len);1191 1192  DispatchInput(data, data_len);1193}1194 1195void SBDebugger::DispatchInput(const void *data, size_t data_len) {1196  LLDB_INSTRUMENT_VA(this, data, data_len);1197 1198  //    Log *log(GetLog (LLDBLog::API));1199  //1200  //    if (log)1201  //        LLDB_LOGF(log, "SBDebugger(%p)::DispatchInput (data=\"%.*s\",1202  //        size_t=%" PRIu64 ")",1203  //                     m_opaque_sp.get(),1204  //                     (int) data_len,1205  //                     (const char *) data,1206  //                     (uint64_t)data_len);1207  //1208  //    if (m_opaque_sp)1209  //        m_opaque_sp->DispatchInput ((const char *) data, data_len);1210}1211 1212void SBDebugger::DispatchInputInterrupt() {1213  LLDB_INSTRUMENT_VA(this);1214 1215  if (m_opaque_sp)1216    m_opaque_sp->DispatchInputInterrupt();1217}1218 1219void SBDebugger::DispatchInputEndOfFile() {1220  LLDB_INSTRUMENT_VA(this);1221 1222  if (m_opaque_sp)1223    m_opaque_sp->DispatchInputEndOfFile();1224}1225 1226void SBDebugger::PushInputReader(SBInputReader &reader) {1227  LLDB_INSTRUMENT_VA(this, reader);1228}1229 1230void SBDebugger::RunCommandInterpreter(bool auto_handle_events,1231                                       bool spawn_thread) {1232  LLDB_INSTRUMENT_VA(this, auto_handle_events, spawn_thread);1233 1234  if (m_opaque_sp) {1235    CommandInterpreterRunOptions options;1236    options.SetAutoHandleEvents(auto_handle_events);1237    options.SetSpawnThread(spawn_thread);1238    m_opaque_sp->GetCommandInterpreter().RunCommandInterpreter(options);1239  }1240}1241 1242void SBDebugger::RunCommandInterpreter(bool auto_handle_events,1243                                       bool spawn_thread,1244                                       SBCommandInterpreterRunOptions &options,1245                                       int &num_errors, bool &quit_requested,1246                                       bool &stopped_for_crash)1247 1248{1249  LLDB_INSTRUMENT_VA(this, auto_handle_events, spawn_thread, options,1250                     num_errors, quit_requested, stopped_for_crash);1251 1252  if (m_opaque_sp) {1253    options.SetAutoHandleEvents(auto_handle_events);1254    options.SetSpawnThread(spawn_thread);1255    CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter();1256    CommandInterpreterRunResult result =1257        interp.RunCommandInterpreter(options.ref());1258    num_errors = result.GetNumErrors();1259    quit_requested =1260        result.IsResult(lldb::eCommandInterpreterResultQuitRequested);1261    stopped_for_crash =1262        result.IsResult(lldb::eCommandInterpreterResultInferiorCrash);1263  }1264}1265 1266SBCommandInterpreterRunResult SBDebugger::RunCommandInterpreter(1267    const SBCommandInterpreterRunOptions &options) {1268  LLDB_INSTRUMENT_VA(this, options);1269 1270  if (!m_opaque_sp)1271    return SBCommandInterpreterRunResult();1272 1273  CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter();1274  CommandInterpreterRunResult result =1275      interp.RunCommandInterpreter(options.ref());1276 1277  return SBCommandInterpreterRunResult(result);1278}1279 1280SBError SBDebugger::RunREPL(lldb::LanguageType language,1281                            const char *repl_options) {1282  LLDB_INSTRUMENT_VA(this, language, repl_options);1283 1284  SBError error;1285  if (m_opaque_sp)1286    error.ref() = m_opaque_sp->RunREPL(language, repl_options);1287  else1288    error = Status::FromErrorString("invalid debugger");1289  return error;1290}1291 1292void SBDebugger::reset(const DebuggerSP &debugger_sp) {1293  m_opaque_sp = debugger_sp;1294}1295 1296Debugger *SBDebugger::get() const { return m_opaque_sp.get(); }1297 1298Debugger &SBDebugger::ref() const {1299  assert(m_opaque_sp.get());1300  return *m_opaque_sp;1301}1302 1303const lldb::DebuggerSP &SBDebugger::get_sp() const { return m_opaque_sp; }1304 1305SBDebugger SBDebugger::FindDebuggerWithID(int id) {1306  LLDB_INSTRUMENT_VA(id);1307 1308  // No need to lock, the debugger list is thread safe1309  SBDebugger sb_debugger;1310  DebuggerSP debugger_sp = Debugger::FindDebuggerWithID(id);1311  if (debugger_sp)1312    sb_debugger.reset(debugger_sp);1313  return sb_debugger;1314}1315 1316const char *SBDebugger::GetInstanceName() {1317  LLDB_INSTRUMENT_VA(this);1318 1319  if (!m_opaque_sp)1320    return nullptr;1321 1322  return ConstString(m_opaque_sp->GetInstanceName()).AsCString();1323}1324 1325SBError SBDebugger::SetInternalVariable(const char *var_name, const char *value,1326                                        const char *debugger_instance_name) {1327  LLDB_INSTRUMENT_VA(var_name, value, debugger_instance_name);1328 1329  SBError sb_error;1330  DebuggerSP debugger_sp(1331      Debugger::FindDebuggerWithInstanceName(debugger_instance_name));1332  Status error;1333  if (debugger_sp) {1334    ExecutionContext exe_ctx(1335        debugger_sp->GetCommandInterpreter().GetExecutionContext());1336    error = debugger_sp->SetPropertyValue(&exe_ctx, eVarSetOperationAssign,1337                                          var_name, value);1338  } else {1339    error = Status::FromErrorStringWithFormat(1340        "invalid debugger instance name '%s'", debugger_instance_name);1341  }1342  if (error.Fail())1343    sb_error.SetError(std::move(error));1344  return sb_error;1345}1346 1347SBStringList1348SBDebugger::GetInternalVariableValue(const char *var_name,1349                                     const char *debugger_instance_name) {1350  LLDB_INSTRUMENT_VA(var_name, debugger_instance_name);1351 1352  DebuggerSP debugger_sp(1353      Debugger::FindDebuggerWithInstanceName(debugger_instance_name));1354  Status error;1355  if (debugger_sp) {1356    ExecutionContext exe_ctx(1357        debugger_sp->GetCommandInterpreter().GetExecutionContext());1358    lldb::OptionValueSP value_sp(1359        debugger_sp->GetPropertyValue(&exe_ctx, var_name, error));1360    if (value_sp) {1361      StreamString value_strm;1362      value_sp->DumpValue(&exe_ctx, value_strm, OptionValue::eDumpOptionValue);1363      const std::string &value_str = std::string(value_strm.GetString());1364      if (!value_str.empty()) {1365        StringList string_list;1366        string_list.SplitIntoLines(value_str);1367        return SBStringList(&string_list);1368      }1369    }1370  }1371  return SBStringList();1372}1373 1374uint32_t SBDebugger::GetTerminalWidth() const {1375  LLDB_INSTRUMENT_VA(this);1376 1377  return (m_opaque_sp ? m_opaque_sp->GetTerminalWidth() : 0);1378}1379 1380void SBDebugger::SetTerminalWidth(uint32_t term_width) {1381  LLDB_INSTRUMENT_VA(this, term_width);1382 1383  if (m_opaque_sp)1384    m_opaque_sp->SetTerminalWidth(term_width);1385}1386 1387uint32_t SBDebugger::GetTerminalHeight() const {1388  LLDB_INSTRUMENT_VA(this);1389 1390  return (m_opaque_sp ? m_opaque_sp->GetTerminalWidth() : 0);1391}1392 1393void SBDebugger::SetTerminalHeight(uint32_t term_height) {1394  LLDB_INSTRUMENT_VA(this, term_height);1395 1396  if (m_opaque_sp)1397    m_opaque_sp->SetTerminalHeight(term_height);1398}1399 1400const char *SBDebugger::GetPrompt() const {1401  LLDB_INSTRUMENT_VA(this);1402 1403  Log *log = GetLog(LLDBLog::API);1404 1405  LLDB_LOG(log, "SBDebugger({0:x})::GetPrompt () => \"{1}\"",1406           static_cast<void *>(m_opaque_sp.get()),1407           (m_opaque_sp ? m_opaque_sp->GetPrompt() : ""));1408 1409  return (m_opaque_sp ? ConstString(m_opaque_sp->GetPrompt()).GetCString()1410                      : nullptr);1411}1412 1413void SBDebugger::SetPrompt(const char *prompt) {1414  LLDB_INSTRUMENT_VA(this, prompt);1415 1416  if (m_opaque_sp)1417    m_opaque_sp->SetPrompt(llvm::StringRef(prompt));1418}1419 1420const char *SBDebugger::GetReproducerPath() const {1421  LLDB_INSTRUMENT_VA(this);1422 1423  return "GetReproducerPath has been deprecated";1424}1425 1426ScriptLanguage SBDebugger::GetScriptLanguage() const {1427  LLDB_INSTRUMENT_VA(this);1428 1429  return (m_opaque_sp ? m_opaque_sp->GetScriptLanguage() : eScriptLanguageNone);1430}1431 1432void SBDebugger::SetScriptLanguage(ScriptLanguage script_lang) {1433  LLDB_INSTRUMENT_VA(this, script_lang);1434 1435  if (m_opaque_sp) {1436    m_opaque_sp->SetScriptLanguage(script_lang);1437  }1438}1439 1440LanguageType SBDebugger::GetREPLLanguage() const {1441  LLDB_INSTRUMENT_VA(this);1442 1443  return (m_opaque_sp ? m_opaque_sp->GetREPLLanguage() : eLanguageTypeUnknown);1444}1445 1446void SBDebugger::SetREPLLanguage(LanguageType repl_lang) {1447  LLDB_INSTRUMENT_VA(this, repl_lang);1448 1449  if (m_opaque_sp) {1450    m_opaque_sp->SetREPLLanguage(repl_lang);1451  }1452}1453 1454bool SBDebugger::SetUseExternalEditor(bool value) {1455  LLDB_INSTRUMENT_VA(this, value);1456 1457  return (m_opaque_sp ? m_opaque_sp->SetUseExternalEditor(value) : false);1458}1459 1460bool SBDebugger::GetUseExternalEditor() {1461  LLDB_INSTRUMENT_VA(this);1462 1463  return (m_opaque_sp ? m_opaque_sp->GetUseExternalEditor() : false);1464}1465 1466bool SBDebugger::SetUseColor(bool value) {1467  LLDB_INSTRUMENT_VA(this, value);1468 1469  return (m_opaque_sp ? m_opaque_sp->SetUseColor(value) : false);1470}1471 1472bool SBDebugger::GetUseColor() const {1473  LLDB_INSTRUMENT_VA(this);1474 1475  return (m_opaque_sp ? m_opaque_sp->GetUseColor() : false);1476}1477 1478bool SBDebugger::SetShowInlineDiagnostics(bool value) {1479  LLDB_INSTRUMENT_VA(this, value);1480 1481  return (m_opaque_sp ? m_opaque_sp->SetShowInlineDiagnostics(value) : false);1482}1483 1484bool SBDebugger::SetUseSourceCache(bool value) {1485  LLDB_INSTRUMENT_VA(this, value);1486 1487  return (m_opaque_sp ? m_opaque_sp->SetUseSourceCache(value) : false);1488}1489 1490bool SBDebugger::GetUseSourceCache() const {1491  LLDB_INSTRUMENT_VA(this);1492 1493  return (m_opaque_sp ? m_opaque_sp->GetUseSourceCache() : false);1494}1495 1496bool SBDebugger::GetDescription(SBStream &description) {1497  LLDB_INSTRUMENT_VA(this, description);1498 1499  Stream &strm = description.ref();1500 1501  if (m_opaque_sp) {1502    const char *name = m_opaque_sp->GetInstanceName().c_str();1503    user_id_t id = m_opaque_sp->GetID();1504    strm.Printf("Debugger (instance: \"%s\", id: %" PRIu64 ")", name, id);1505  } else1506    strm.PutCString("No value");1507 1508  return true;1509}1510 1511user_id_t SBDebugger::GetID() {1512  LLDB_INSTRUMENT_VA(this);1513 1514  return (m_opaque_sp ? m_opaque_sp->GetID() : LLDB_INVALID_UID);1515}1516 1517SBError SBDebugger::SetCurrentPlatform(const char *platform_name_cstr) {1518  LLDB_INSTRUMENT_VA(this, platform_name_cstr);1519 1520  SBError sb_error;1521  if (m_opaque_sp) {1522    if (platform_name_cstr && platform_name_cstr[0]) {1523      PlatformList &platforms = m_opaque_sp->GetPlatformList();1524      if (PlatformSP platform_sp = platforms.GetOrCreate(platform_name_cstr))1525        platforms.SetSelectedPlatform(platform_sp);1526      else1527        sb_error.ref() = Status::FromErrorString("platform not found");1528    } else {1529      sb_error.ref() = Status::FromErrorString("invalid platform name");1530    }1531  } else {1532    sb_error.ref() = Status::FromErrorString("invalid debugger");1533  }1534  return sb_error;1535}1536 1537bool SBDebugger::SetCurrentPlatformSDKRoot(const char *sysroot) {1538  LLDB_INSTRUMENT_VA(this, sysroot);1539 1540  if (SBPlatform platform = GetSelectedPlatform()) {1541    platform.SetSDKRoot(sysroot);1542    return true;1543  }1544  return false;1545}1546 1547bool SBDebugger::GetCloseInputOnEOF() const {1548  LLDB_INSTRUMENT_VA(this);1549 1550  return false;1551}1552 1553void SBDebugger::SetCloseInputOnEOF(bool b) {1554  LLDB_INSTRUMENT_VA(this, b);1555}1556 1557SBTypeCategory SBDebugger::GetCategory(const char *category_name) {1558  LLDB_INSTRUMENT_VA(this, category_name);1559 1560  if (!category_name || *category_name == 0)1561    return SBTypeCategory();1562 1563  TypeCategoryImplSP category_sp;1564 1565  if (DataVisualization::Categories::GetCategory(ConstString(category_name),1566                                                 category_sp, false)) {1567    return SBTypeCategory(category_sp);1568  } else {1569    return SBTypeCategory();1570  }1571}1572 1573SBTypeCategory SBDebugger::GetCategory(lldb::LanguageType lang_type) {1574  LLDB_INSTRUMENT_VA(this, lang_type);1575 1576  TypeCategoryImplSP category_sp;1577  if (DataVisualization::Categories::GetCategory(lang_type, category_sp)) {1578    return SBTypeCategory(category_sp);1579  } else {1580    return SBTypeCategory();1581  }1582}1583 1584SBTypeCategory SBDebugger::CreateCategory(const char *category_name) {1585  LLDB_INSTRUMENT_VA(this, category_name);1586 1587  if (!category_name || *category_name == 0)1588    return SBTypeCategory();1589 1590  TypeCategoryImplSP category_sp;1591 1592  if (DataVisualization::Categories::GetCategory(ConstString(category_name),1593                                                 category_sp, true)) {1594    return SBTypeCategory(category_sp);1595  } else {1596    return SBTypeCategory();1597  }1598}1599 1600bool SBDebugger::DeleteCategory(const char *category_name) {1601  LLDB_INSTRUMENT_VA(this, category_name);1602 1603  if (!category_name || *category_name == 0)1604    return false;1605 1606  return DataVisualization::Categories::Delete(ConstString(category_name));1607}1608 1609uint32_t SBDebugger::GetNumCategories() {1610  LLDB_INSTRUMENT_VA(this);1611 1612  return DataVisualization::Categories::GetCount();1613}1614 1615SBTypeCategory SBDebugger::GetCategoryAtIndex(uint32_t index) {1616  LLDB_INSTRUMENT_VA(this, index);1617 1618  return SBTypeCategory(1619      DataVisualization::Categories::GetCategoryAtIndex(index));1620}1621 1622SBTypeCategory SBDebugger::GetDefaultCategory() {1623  LLDB_INSTRUMENT_VA(this);1624 1625  return GetCategory("default");1626}1627 1628SBTypeFormat SBDebugger::GetFormatForType(SBTypeNameSpecifier type_name) {1629  LLDB_INSTRUMENT_VA(this, type_name);1630 1631  SBTypeCategory default_category_sb = GetDefaultCategory();1632  if (default_category_sb.GetEnabled())1633    return default_category_sb.GetFormatForType(type_name);1634  return SBTypeFormat();1635}1636 1637SBTypeSummary SBDebugger::GetSummaryForType(SBTypeNameSpecifier type_name) {1638  LLDB_INSTRUMENT_VA(this, type_name);1639 1640  if (!type_name.IsValid())1641    return SBTypeSummary();1642  return SBTypeSummary(DataVisualization::GetSummaryForType(type_name.GetSP()));1643}1644 1645SBTypeFilter SBDebugger::GetFilterForType(SBTypeNameSpecifier type_name) {1646  LLDB_INSTRUMENT_VA(this, type_name);1647 1648  if (!type_name.IsValid())1649    return SBTypeFilter();1650  return SBTypeFilter(DataVisualization::GetFilterForType(type_name.GetSP()));1651}1652 1653SBTypeSynthetic SBDebugger::GetSyntheticForType(SBTypeNameSpecifier type_name) {1654  LLDB_INSTRUMENT_VA(this, type_name);1655 1656  if (!type_name.IsValid())1657    return SBTypeSynthetic();1658  return SBTypeSynthetic(1659      DataVisualization::GetSyntheticForType(type_name.GetSP()));1660}1661 1662void SBDebugger::ResetStatistics() {1663  LLDB_INSTRUMENT_VA(this);1664  if (m_opaque_sp)1665    DebuggerStats::ResetStatistics(*m_opaque_sp, nullptr);1666}1667 1668static llvm::ArrayRef<const char *> GetCategoryArray(const char **categories) {1669  if (categories == nullptr)1670    return {};1671  size_t len = 0;1672  while (categories[len] != nullptr)1673    ++len;1674  return llvm::ArrayRef(categories, len);1675}1676 1677bool SBDebugger::EnableLog(const char *channel, const char **categories) {1678  LLDB_INSTRUMENT_VA(this, channel, categories);1679 1680  if (m_opaque_sp) {1681    uint32_t log_options =1682        LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;1683    std::string error;1684    llvm::raw_string_ostream error_stream(error);1685    return m_opaque_sp->EnableLog(channel, GetCategoryArray(categories), "",1686                                  log_options, /*buffer_size=*/0,1687                                  eLogHandlerStream, error_stream);1688  } else1689    return false;1690}1691 1692void SBDebugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,1693                                    void *baton) {1694  LLDB_INSTRUMENT_VA(this, log_callback, baton);1695 1696  if (m_opaque_sp) {1697    return m_opaque_sp->SetLoggingCallback(log_callback, baton);1698  }1699}1700 1701void SBDebugger::SetDestroyCallback(1702    lldb::SBDebuggerDestroyCallback destroy_callback, void *baton) {1703  LLDB_INSTRUMENT_VA(this, destroy_callback, baton);1704  if (m_opaque_sp) {1705    return m_opaque_sp->SetDestroyCallback(1706        destroy_callback, baton);1707  }1708}1709 1710lldb::callback_token_t1711SBDebugger::AddDestroyCallback(lldb::SBDebuggerDestroyCallback destroy_callback,1712                               void *baton) {1713  LLDB_INSTRUMENT_VA(this, destroy_callback, baton);1714 1715  if (m_opaque_sp)1716    return m_opaque_sp->AddDestroyCallback(destroy_callback, baton);1717 1718  return LLDB_INVALID_CALLBACK_TOKEN;1719}1720 1721bool SBDebugger::RemoveDestroyCallback(lldb::callback_token_t token) {1722  LLDB_INSTRUMENT_VA(this, token);1723 1724  if (m_opaque_sp)1725    return m_opaque_sp->RemoveDestroyCallback(token);1726 1727  return false;1728}1729 1730SBTrace1731SBDebugger::LoadTraceFromFile(SBError &error,1732                              const SBFileSpec &trace_description_file) {1733  LLDB_INSTRUMENT_VA(this, error, trace_description_file);1734  return SBTrace::LoadTraceFromFile(error, *this, trace_description_file);1735}1736 1737void SBDebugger::RequestInterrupt() {1738  LLDB_INSTRUMENT_VA(this);1739 1740  if (m_opaque_sp)1741    m_opaque_sp->RequestInterrupt();1742}1743void SBDebugger::CancelInterruptRequest()  {1744  LLDB_INSTRUMENT_VA(this);1745 1746  if (m_opaque_sp)1747    m_opaque_sp->CancelInterruptRequest();1748}1749 1750bool SBDebugger::InterruptRequested()   {1751  LLDB_INSTRUMENT_VA(this);1752 1753  if (m_opaque_sp)1754    return m_opaque_sp->InterruptRequested();1755  return false;1756}1757 1758bool SBDebugger::SupportsLanguage(lldb::LanguageType language) {1759  return TypeSystem::SupportsLanguageStatic(language);1760}1761