brintos

brintos / llvm-project-archived public Read only

0
0
Text · 79.1 KiB · 578a7bd Raw
2438 lines · cpp
1//===-- SBTarget.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/SBTarget.h"10#include "lldb/API/SBBreakpoint.h"11#include "lldb/API/SBDebugger.h"12#include "lldb/API/SBEnvironment.h"13#include "lldb/API/SBEvent.h"14#include "lldb/API/SBExpressionOptions.h"15#include "lldb/API/SBFileSpec.h"16#include "lldb/API/SBListener.h"17#include "lldb/API/SBModule.h"18#include "lldb/API/SBModuleSpec.h"19#include "lldb/API/SBMutex.h"20#include "lldb/API/SBProcess.h"21#include "lldb/API/SBSourceManager.h"22#include "lldb/API/SBStream.h"23#include "lldb/API/SBStringList.h"24#include "lldb/API/SBStructuredData.h"25#include "lldb/API/SBSymbolContextList.h"26#include "lldb/API/SBTrace.h"27#include "lldb/Breakpoint/BreakpointID.h"28#include "lldb/Breakpoint/BreakpointIDList.h"29#include "lldb/Breakpoint/BreakpointList.h"30#include "lldb/Breakpoint/BreakpointLocation.h"31#include "lldb/Core/Address.h"32#include "lldb/Core/AddressResolver.h"33#include "lldb/Core/Debugger.h"34#include "lldb/Core/Disassembler.h"35#include "lldb/Core/Module.h"36#include "lldb/Core/ModuleSpec.h"37#include "lldb/Core/PluginManager.h"38#include "lldb/Core/SearchFilter.h"39#include "lldb/Core/Section.h"40#include "lldb/Core/StructuredDataImpl.h"41#include "lldb/Host/Host.h"42#include "lldb/Symbol/DeclVendor.h"43#include "lldb/Symbol/ObjectFile.h"44#include "lldb/Symbol/SymbolFile.h"45#include "lldb/Symbol/SymbolVendor.h"46#include "lldb/Symbol/TypeSystem.h"47#include "lldb/Symbol/VariableList.h"48#include "lldb/Target/ABI.h"49#include "lldb/Target/Language.h"50#include "lldb/Target/LanguageRuntime.h"51#include "lldb/Target/Process.h"52#include "lldb/Target/StackFrame.h"53#include "lldb/Target/Target.h"54#include "lldb/Target/TargetList.h"55#include "lldb/Utility/ArchSpec.h"56#include "lldb/Utility/Args.h"57#include "lldb/Utility/FileSpec.h"58#include "lldb/Utility/Instrumentation.h"59#include "lldb/Utility/LLDBLog.h"60#include "lldb/Utility/ProcessInfo.h"61#include "lldb/Utility/RegularExpression.h"62#include "lldb/ValueObject/ValueObjectConstResult.h"63#include "lldb/ValueObject/ValueObjectList.h"64#include "lldb/ValueObject/ValueObjectVariable.h"65#include "lldb/lldb-public.h"66 67#include "Commands/CommandObjectBreakpoint.h"68#include "lldb/Interpreter/CommandReturnObject.h"69#include "llvm/Support/PrettyStackTrace.h"70#include "llvm/Support/Regex.h"71 72using namespace lldb;73using namespace lldb_private;74 75#define DEFAULT_DISASM_BYTE_SIZE 3276 77static Status AttachToProcess(ProcessAttachInfo &attach_info, Target &target) {78  std::lock_guard<std::recursive_mutex> guard(target.GetAPIMutex());79 80  auto process_sp = target.GetProcessSP();81  if (process_sp) {82    const auto state = process_sp->GetState();83    if (process_sp->IsAlive() && state == eStateConnected) {84      // If we are already connected, then we have already specified the85      // listener, so if a valid listener is supplied, we need to error out to86      // let the client know.87      if (attach_info.GetListener())88        return Status::FromErrorString(89            "process is connected and already has a listener, pass "90            "empty listener");91    }92  }93 94  return target.Attach(attach_info, nullptr);95}96 97// SBTarget constructor98SBTarget::SBTarget() { LLDB_INSTRUMENT_VA(this); }99 100SBTarget::SBTarget(const SBTarget &rhs) : m_opaque_sp(rhs.m_opaque_sp) {101  LLDB_INSTRUMENT_VA(this, rhs);102}103 104SBTarget::SBTarget(const TargetSP &target_sp) : m_opaque_sp(target_sp) {105  LLDB_INSTRUMENT_VA(this, target_sp);106}107 108const SBTarget &SBTarget::operator=(const SBTarget &rhs) {109  LLDB_INSTRUMENT_VA(this, rhs);110 111  if (this != &rhs)112    m_opaque_sp = rhs.m_opaque_sp;113  return *this;114}115 116// Destructor117SBTarget::~SBTarget() = default;118 119bool SBTarget::EventIsTargetEvent(const SBEvent &event) {120  LLDB_INSTRUMENT_VA(event);121 122  return Target::TargetEventData::GetEventDataFromEvent(event.get()) != nullptr;123}124 125SBTarget SBTarget::GetTargetFromEvent(const SBEvent &event) {126  LLDB_INSTRUMENT_VA(event);127 128  return Target::TargetEventData::GetTargetFromEvent(event.get());129}130 131SBTarget SBTarget::GetCreatedTargetFromEvent(const SBEvent &event) {132  LLDB_INSTRUMENT_VA(event);133 134  return Target::TargetEventData::GetCreatedTargetFromEvent(event.get());135}136 137uint32_t SBTarget::GetNumModulesFromEvent(const SBEvent &event) {138  LLDB_INSTRUMENT_VA(event);139 140  const ModuleList module_list =141      Target::TargetEventData::GetModuleListFromEvent(event.get());142  return module_list.GetSize();143}144 145SBModule SBTarget::GetModuleAtIndexFromEvent(const uint32_t idx,146                                             const SBEvent &event) {147  LLDB_INSTRUMENT_VA(idx, event);148 149  const ModuleList module_list =150      Target::TargetEventData::GetModuleListFromEvent(event.get());151  return SBModule(module_list.GetModuleAtIndex(idx));152}153 154const char *SBTarget::GetBroadcasterClassName() {155  LLDB_INSTRUMENT();156 157  return ConstString(Target::GetStaticBroadcasterClass()).AsCString();158}159 160bool SBTarget::IsValid() const {161  LLDB_INSTRUMENT_VA(this);162  return this->operator bool();163}164SBTarget::operator bool() const {165  LLDB_INSTRUMENT_VA(this);166 167  return m_opaque_sp.get() != nullptr && m_opaque_sp->IsValid();168}169 170SBProcess SBTarget::GetProcess() {171  LLDB_INSTRUMENT_VA(this);172 173  SBProcess sb_process;174  ProcessSP process_sp;175  if (TargetSP target_sp = GetSP()) {176    process_sp = target_sp->GetProcessSP();177    sb_process.SetSP(process_sp);178  }179 180  return sb_process;181}182 183SBPlatform SBTarget::GetPlatform() {184  LLDB_INSTRUMENT_VA(this);185 186  if (TargetSP target_sp = GetSP()) {187    SBPlatform platform;188    platform.m_opaque_sp = target_sp->GetPlatform();189    return platform;190  }191  return SBPlatform();192}193 194SBDebugger SBTarget::GetDebugger() const {195  LLDB_INSTRUMENT_VA(this);196 197  SBDebugger debugger;198  if (TargetSP target_sp = GetSP())199    debugger.reset(target_sp->GetDebugger().shared_from_this());200  return debugger;201}202 203SBStructuredData SBTarget::GetStatistics() {204  LLDB_INSTRUMENT_VA(this);205  SBStatisticsOptions options;206  return GetStatistics(options);207}208 209SBStructuredData SBTarget::GetStatistics(SBStatisticsOptions options) {210  LLDB_INSTRUMENT_VA(this);211 212  SBStructuredData data;213  if (TargetSP target_sp = GetSP()) {214    std::string json_str =215        llvm::formatv("{0:2}", DebuggerStats::ReportStatistics(216                                   target_sp->GetDebugger(), target_sp.get(),217                                   options.ref()))218            .str();219    data.m_impl_up->SetObjectSP(StructuredData::ParseJSON(json_str));220    return data;221  }222  return data;223}224 225void SBTarget::ResetStatistics() {226  LLDB_INSTRUMENT_VA(this);227 228  if (TargetSP target_sp = GetSP())229    DebuggerStats::ResetStatistics(target_sp->GetDebugger(), target_sp.get());230}231 232void SBTarget::SetCollectingStats(bool v) {233  LLDB_INSTRUMENT_VA(this, v);234 235  if (TargetSP target_sp = GetSP())236    DebuggerStats::SetCollectingStats(v);237}238 239bool SBTarget::GetCollectingStats() {240  LLDB_INSTRUMENT_VA(this);241 242  if (TargetSP target_sp = GetSP())243    return DebuggerStats::GetCollectingStats();244  return false;245}246 247SBProcess SBTarget::LoadCore(const char *core_file) {248  LLDB_INSTRUMENT_VA(this, core_file);249 250  lldb::SBError error; // Ignored251  return LoadCore(core_file, error);252}253 254SBProcess SBTarget::LoadCore(const char *core_file, lldb::SBError &error) {255  LLDB_INSTRUMENT_VA(this, core_file, error);256 257  SBProcess sb_process;258  if (TargetSP target_sp = GetSP()) {259    FileSpec filespec(core_file);260    FileSystem::Instance().Resolve(filespec);261    ProcessSP process_sp(target_sp->CreateProcess(262        target_sp->GetDebugger().GetListener(), "", &filespec, false));263    if (process_sp) {264      ElapsedTime load_core_time(target_sp->GetStatistics().GetLoadCoreTime());265      error.SetError(process_sp->LoadCore());266      if (error.Success())267        sb_process.SetSP(process_sp);268    } else {269      error.SetErrorString("Failed to create the process");270    }271  } else {272    error.SetErrorString("SBTarget is invalid");273  }274  return sb_process;275}276 277SBProcess SBTarget::LaunchSimple(char const **argv, char const **envp,278                                 const char *working_directory) {279  LLDB_INSTRUMENT_VA(this, argv, envp, working_directory);280 281  TargetSP target_sp = GetSP();282  if (!target_sp)283    return SBProcess();284 285  SBLaunchInfo launch_info = GetLaunchInfo();286 287  if (Module *exe_module = target_sp->GetExecutableModulePointer())288    launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(),289                                  /*add_as_first_arg*/ true);290  if (argv)291    launch_info.SetArguments(argv, /*append*/ true);292  if (envp)293    launch_info.SetEnvironmentEntries(envp, /*append*/ false);294  if (working_directory)295    launch_info.SetWorkingDirectory(working_directory);296 297  SBError error;298  return Launch(launch_info, error);299}300 301SBError SBTarget::Install() {302  LLDB_INSTRUMENT_VA(this);303 304  SBError sb_error;305  if (TargetSP target_sp = GetSP()) {306    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());307    sb_error.ref() = target_sp->Install(nullptr);308  }309  return sb_error;310}311 312SBProcess SBTarget::Launch(SBListener &listener, char const **argv,313                           char const **envp, const char *stdin_path,314                           const char *stdout_path, const char *stderr_path,315                           const char *working_directory,316                           uint32_t launch_flags, // See LaunchFlags317                           bool stop_at_entry, lldb::SBError &error) {318  LLDB_INSTRUMENT_VA(this, listener, argv, envp, stdin_path, stdout_path,319                     stderr_path, working_directory, launch_flags,320                     stop_at_entry, error);321 322  SBProcess sb_process;323  ProcessSP process_sp;324  if (TargetSP target_sp = GetSP()) {325    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());326 327    if (stop_at_entry)328      launch_flags |= eLaunchFlagStopAtEntry;329 330    if (getenv("LLDB_LAUNCH_FLAG_DISABLE_ASLR"))331      launch_flags |= eLaunchFlagDisableASLR;332 333    StateType state = eStateInvalid;334    process_sp = target_sp->GetProcessSP();335    if (process_sp) {336      state = process_sp->GetState();337 338      if (process_sp->IsAlive() && state != eStateConnected) {339        if (state == eStateAttaching)340          error.SetErrorString("process attach is in progress");341        else342          error.SetErrorString("a process is already being debugged");343        return sb_process;344      }345    }346 347    if (state == eStateConnected) {348      // If we are already connected, then we have already specified the349      // listener, so if a valid listener is supplied, we need to error out to350      // let the client know.351      if (listener.IsValid()) {352        error.SetErrorString("process is connected and already has a listener, "353                             "pass empty listener");354        return sb_process;355      }356    }357 358    if (getenv("LLDB_LAUNCH_FLAG_DISABLE_STDIO"))359      launch_flags |= eLaunchFlagDisableSTDIO;360 361    ProcessLaunchInfo launch_info(FileSpec(stdin_path), FileSpec(stdout_path),362                                  FileSpec(stderr_path),363                                  FileSpec(working_directory), launch_flags);364 365    Module *exe_module = target_sp->GetExecutableModulePointer();366    if (exe_module)367      launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true);368    if (argv) {369      launch_info.GetArguments().AppendArguments(argv);370    } else {371      auto default_launch_info = target_sp->GetProcessLaunchInfo();372      launch_info.GetArguments().AppendArguments(373          default_launch_info.GetArguments());374    }375    if (envp) {376      launch_info.GetEnvironment() = Environment(envp);377    } else {378      auto default_launch_info = target_sp->GetProcessLaunchInfo();379      launch_info.GetEnvironment() = default_launch_info.GetEnvironment();380    }381 382    if (listener.IsValid())383      launch_info.SetListener(listener.GetSP());384 385    error.SetError(target_sp->Launch(launch_info, nullptr));386 387    sb_process.SetSP(target_sp->GetProcessSP());388  } else {389    error.SetErrorString("SBTarget is invalid");390  }391 392  return sb_process;393}394 395SBProcess SBTarget::Launch(SBLaunchInfo &sb_launch_info, SBError &error) {396  LLDB_INSTRUMENT_VA(this, sb_launch_info, error);397 398  SBProcess sb_process;399  if (TargetSP target_sp = GetSP()) {400    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());401    StateType state = eStateInvalid;402    {403      ProcessSP process_sp = target_sp->GetProcessSP();404      if (process_sp) {405        state = process_sp->GetState();406 407        if (process_sp->IsAlive() && state != eStateConnected) {408          if (state == eStateAttaching)409            error.SetErrorString("process attach is in progress");410          else411            error.SetErrorString("a process is already being debugged");412          return sb_process;413        }414      }415    }416 417    lldb_private::ProcessLaunchInfo launch_info = sb_launch_info.ref();418 419    if (!launch_info.GetExecutableFile()) {420      Module *exe_module = target_sp->GetExecutableModulePointer();421      if (exe_module)422        launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true);423    }424 425    const ArchSpec &arch_spec = target_sp->GetArchitecture();426    if (arch_spec.IsValid())427      launch_info.GetArchitecture() = arch_spec;428 429    error.SetError(target_sp->Launch(launch_info, nullptr));430    sb_launch_info.set_ref(launch_info);431    sb_process.SetSP(target_sp->GetProcessSP());432  } else {433    error.SetErrorString("SBTarget is invalid");434  }435 436  return sb_process;437}438 439lldb::SBProcess SBTarget::Attach(SBAttachInfo &sb_attach_info, SBError &error) {440  LLDB_INSTRUMENT_VA(this, sb_attach_info, error);441 442  SBProcess sb_process;443  if (TargetSP target_sp = GetSP()) {444    ProcessAttachInfo &attach_info = sb_attach_info.ref();445    if (attach_info.ProcessIDIsValid() && !attach_info.UserIDIsValid() &&446        !attach_info.IsScriptedProcess()) {447      PlatformSP platform_sp = target_sp->GetPlatform();448      // See if we can pre-verify if a process exists or not449      if (platform_sp && platform_sp->IsConnected()) {450        lldb::pid_t attach_pid = attach_info.GetProcessID();451        ProcessInstanceInfo instance_info;452        if (platform_sp->GetProcessInfo(attach_pid, instance_info)) {453          attach_info.SetUserID(instance_info.GetEffectiveUserID());454        } else {455          error.ref() = Status::FromErrorStringWithFormat(456              "no process found with process ID %" PRIu64, attach_pid);457          return sb_process;458        }459      }460    }461    error.SetError(AttachToProcess(attach_info, *target_sp));462    if (error.Success())463      sb_process.SetSP(target_sp->GetProcessSP());464  } else {465    error.SetErrorString("SBTarget is invalid");466  }467 468  return sb_process;469}470 471lldb::SBProcess SBTarget::AttachToProcessWithID(472    SBListener &listener,473    lldb::pid_t pid, // The process ID to attach to474    SBError &error   // An error explaining what went wrong if attach fails475) {476  LLDB_INSTRUMENT_VA(this, listener, pid, error);477 478  SBProcess sb_process;479  if (TargetSP target_sp = GetSP()) {480    ProcessAttachInfo attach_info;481    attach_info.SetProcessID(pid);482    if (listener.IsValid())483      attach_info.SetListener(listener.GetSP());484 485    ProcessInstanceInfo instance_info;486    if (target_sp->GetPlatform()->GetProcessInfo(pid, instance_info))487      attach_info.SetUserID(instance_info.GetEffectiveUserID());488 489    error.SetError(AttachToProcess(attach_info, *target_sp));490    if (error.Success())491      sb_process.SetSP(target_sp->GetProcessSP());492  } else493    error.SetErrorString("SBTarget is invalid");494 495  return sb_process;496}497 498lldb::SBProcess SBTarget::AttachToProcessWithName(499    SBListener &listener,500    const char *name, // basename of process to attach to501    bool wait_for, // if true wait for a new instance of "name" to be launched502    SBError &error // An error explaining what went wrong if attach fails503) {504  LLDB_INSTRUMENT_VA(this, listener, name, wait_for, error);505 506  SBProcess sb_process;507 508  if (!name) {509    error.SetErrorString("invalid name");510    return sb_process;511  }512 513  if (TargetSP target_sp = GetSP()) {514    ProcessAttachInfo attach_info;515    attach_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);516    attach_info.SetWaitForLaunch(wait_for);517    if (listener.IsValid())518      attach_info.SetListener(listener.GetSP());519 520    error.SetError(AttachToProcess(attach_info, *target_sp));521    if (error.Success())522      sb_process.SetSP(target_sp->GetProcessSP());523  } else {524    error.SetErrorString("SBTarget is invalid");525  }526 527  return sb_process;528}529 530lldb::SBProcess SBTarget::ConnectRemote(SBListener &listener, const char *url,531                                        const char *plugin_name,532                                        SBError &error) {533  LLDB_INSTRUMENT_VA(this, listener, url, plugin_name, error);534 535  SBProcess sb_process;536  ProcessSP process_sp;537  if (TargetSP target_sp = GetSP()) {538    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());539    if (listener.IsValid())540      process_sp =541          target_sp->CreateProcess(listener.m_opaque_sp, plugin_name, nullptr,542                                   true);543    else544      process_sp = target_sp->CreateProcess(545          target_sp->GetDebugger().GetListener(), plugin_name, nullptr, true);546 547    if (process_sp) {548      sb_process.SetSP(process_sp);549      error.SetError(process_sp->ConnectRemote(url));550    } else {551      error.SetErrorString("unable to create lldb_private::Process");552    }553  } else {554    error.SetErrorString("SBTarget is invalid");555  }556 557  return sb_process;558}559 560SBFileSpec SBTarget::GetExecutable() {561  LLDB_INSTRUMENT_VA(this);562 563  SBFileSpec exe_file_spec;564  if (TargetSP target_sp = GetSP()) {565    Module *exe_module = target_sp->GetExecutableModulePointer();566    if (exe_module)567      exe_file_spec.SetFileSpec(exe_module->GetFileSpec());568  }569 570  return exe_file_spec;571}572 573bool SBTarget::operator==(const SBTarget &rhs) const {574  LLDB_INSTRUMENT_VA(this, rhs);575 576  return m_opaque_sp.get() == rhs.m_opaque_sp.get();577}578 579bool SBTarget::operator!=(const SBTarget &rhs) const {580  LLDB_INSTRUMENT_VA(this, rhs);581 582  return m_opaque_sp.get() != rhs.m_opaque_sp.get();583}584 585lldb::TargetSP SBTarget::GetSP() const { return m_opaque_sp; }586 587void SBTarget::SetSP(const lldb::TargetSP &target_sp) {588  m_opaque_sp = target_sp;589}590 591lldb::SBAddress SBTarget::ResolveLoadAddress(lldb::addr_t vm_addr) {592  LLDB_INSTRUMENT_VA(this, vm_addr);593 594  lldb::SBAddress sb_addr;595  Address &addr = sb_addr.ref();596  if (TargetSP target_sp = GetSP()) {597    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());598    if (target_sp->ResolveLoadAddress(vm_addr, addr))599      return sb_addr;600  }601 602  // We have a load address that isn't in a section, just return an address603  // with the offset filled in (the address) and the section set to NULL604  addr.SetRawAddress(vm_addr);605  return sb_addr;606}607 608lldb::SBAddress SBTarget::ResolveFileAddress(lldb::addr_t file_addr) {609  LLDB_INSTRUMENT_VA(this, file_addr);610 611  lldb::SBAddress sb_addr;612  Address &addr = sb_addr.ref();613  if (TargetSP target_sp = GetSP()) {614    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());615    if (target_sp->ResolveFileAddress(file_addr, addr))616      return sb_addr;617  }618 619  addr.SetRawAddress(file_addr);620  return sb_addr;621}622 623lldb::SBAddress SBTarget::ResolvePastLoadAddress(uint32_t stop_id,624                                                 lldb::addr_t vm_addr) {625  LLDB_INSTRUMENT_VA(this, stop_id, vm_addr);626 627  lldb::SBAddress sb_addr;628  Address &addr = sb_addr.ref();629  if (TargetSP target_sp = GetSP()) {630    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());631    if (target_sp->ResolveLoadAddress(vm_addr, addr))632      return sb_addr;633  }634 635  // We have a load address that isn't in a section, just return an address636  // with the offset filled in (the address) and the section set to NULL637  addr.SetRawAddress(vm_addr);638  return sb_addr;639}640 641SBSymbolContext642SBTarget::ResolveSymbolContextForAddress(const SBAddress &addr,643                                         uint32_t resolve_scope) {644  LLDB_INSTRUMENT_VA(this, addr, resolve_scope);645 646  SBSymbolContext sb_sc;647  SymbolContextItem scope = static_cast<SymbolContextItem>(resolve_scope);648  if (addr.IsValid()) {649    if (TargetSP target_sp = GetSP()) {650      lldb_private::SymbolContext &sc = sb_sc.ref();651      sc.target_sp = target_sp;652      target_sp->GetImages().ResolveSymbolContextForAddress(addr.ref(), scope,653                                                            sc);654    }655  }656  return sb_sc;657}658 659size_t SBTarget::ReadMemory(const SBAddress addr, void *buf, size_t size,660                            lldb::SBError &error) {661  LLDB_INSTRUMENT_VA(this, addr, buf, size, error);662 663  size_t bytes_read = 0;664  if (TargetSP target_sp = GetSP()) {665    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());666    bytes_read =667        target_sp->ReadMemory(addr.ref(), buf, size, error.ref(), true);668  } else {669    error.SetErrorString("invalid target");670  }671 672  return bytes_read;673}674 675SBBreakpoint SBTarget::BreakpointCreateByLocation(const char *file,676                                                  uint32_t line) {677  LLDB_INSTRUMENT_VA(this, file, line);678 679  return SBBreakpoint(680      BreakpointCreateByLocation(SBFileSpec(file, false), line));681}682 683SBBreakpoint684SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec,685                                     uint32_t line) {686  LLDB_INSTRUMENT_VA(this, sb_file_spec, line);687 688  return BreakpointCreateByLocation(sb_file_spec, line, 0);689}690 691SBBreakpoint692SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec,693                                     uint32_t line, lldb::addr_t offset) {694  LLDB_INSTRUMENT_VA(this, sb_file_spec, line, offset);695 696  SBFileSpecList empty_list;697  return BreakpointCreateByLocation(sb_file_spec, line, offset, empty_list);698}699 700SBBreakpoint701SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec,702                                     uint32_t line, lldb::addr_t offset,703                                     SBFileSpecList &sb_module_list) {704  LLDB_INSTRUMENT_VA(this, sb_file_spec, line, offset, sb_module_list);705 706  return BreakpointCreateByLocation(sb_file_spec, line, 0, offset,707                                    sb_module_list);708}709 710SBBreakpoint SBTarget::BreakpointCreateByLocation(711    const SBFileSpec &sb_file_spec, uint32_t line, uint32_t column,712    lldb::addr_t offset, SBFileSpecList &sb_module_list) {713  LLDB_INSTRUMENT_VA(this, sb_file_spec, line, column, offset, sb_module_list);714 715  SBBreakpoint sb_bp;716  if (TargetSP target_sp = GetSP(); target_sp && line != 0) {717    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());718 719    const LazyBool check_inlines = eLazyBoolCalculate;720    const LazyBool skip_prologue = eLazyBoolCalculate;721    const bool internal = false;722    const bool hardware = false;723    const LazyBool move_to_nearest_code = eLazyBoolCalculate;724    const FileSpecList *module_list = nullptr;725    if (sb_module_list.GetSize() > 0) {726      module_list = sb_module_list.get();727    }728    sb_bp = target_sp->CreateBreakpoint(729        module_list, *sb_file_spec, line, column, offset, check_inlines,730        skip_prologue, internal, hardware, move_to_nearest_code);731  }732 733  return sb_bp;734}735 736SBBreakpoint SBTarget::BreakpointCreateByLocation(737    const SBFileSpec &sb_file_spec, uint32_t line, uint32_t column,738    lldb::addr_t offset, SBFileSpecList &sb_module_list,739    bool move_to_nearest_code) {740  LLDB_INSTRUMENT_VA(this, sb_file_spec, line, column, offset, sb_module_list,741                     move_to_nearest_code);742 743  SBBreakpoint sb_bp;744  if (TargetSP target_sp = GetSP(); target_sp && line != 0) {745    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());746 747    const LazyBool check_inlines = eLazyBoolCalculate;748    const LazyBool skip_prologue = eLazyBoolCalculate;749    const bool internal = false;750    const bool hardware = false;751    const FileSpecList *module_list = nullptr;752    if (sb_module_list.GetSize() > 0) {753      module_list = sb_module_list.get();754    }755    sb_bp = target_sp->CreateBreakpoint(756        module_list, *sb_file_spec, line, column, offset, check_inlines,757        skip_prologue, internal, hardware,758        move_to_nearest_code ? eLazyBoolYes : eLazyBoolNo);759  }760 761  return sb_bp;762}763 764SBBreakpoint SBTarget::BreakpointCreateByName(const char *symbol_name,765                                              const char *module_name) {766  LLDB_INSTRUMENT_VA(this, symbol_name, module_name);767 768  SBBreakpoint sb_bp;769  if (TargetSP target_sp = GetSP()) {770    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());771 772    const bool internal = false;773    const bool hardware = false;774    const LazyBool skip_prologue = eLazyBoolCalculate;775    const lldb::addr_t offset = 0;776    const bool offset_is_insn_count = false;777    if (module_name && module_name[0]) {778      FileSpecList module_spec_list;779      module_spec_list.Append(FileSpec(module_name));780      sb_bp = target_sp->CreateBreakpoint(781          &module_spec_list, nullptr, symbol_name, eFunctionNameTypeAuto,782          eLanguageTypeUnknown, offset, offset_is_insn_count, skip_prologue,783          internal, hardware);784    } else {785      sb_bp = target_sp->CreateBreakpoint(786          nullptr, nullptr, symbol_name, eFunctionNameTypeAuto,787          eLanguageTypeUnknown, offset, offset_is_insn_count, skip_prologue,788          internal, hardware);789    }790  }791 792  return sb_bp;793}794 795lldb::SBBreakpoint796SBTarget::BreakpointCreateByName(const char *symbol_name,797                                 const SBFileSpecList &module_list,798                                 const SBFileSpecList &comp_unit_list) {799  LLDB_INSTRUMENT_VA(this, symbol_name, module_list, comp_unit_list);800 801  lldb::FunctionNameType name_type_mask = eFunctionNameTypeAuto;802  return BreakpointCreateByName(symbol_name, name_type_mask,803                                eLanguageTypeUnknown, module_list,804                                comp_unit_list);805}806 807lldb::SBBreakpoint SBTarget::BreakpointCreateByName(808    const char *symbol_name, uint32_t name_type_mask,809    const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) {810  LLDB_INSTRUMENT_VA(this, symbol_name, name_type_mask, module_list,811                     comp_unit_list);812 813  return BreakpointCreateByName(symbol_name, name_type_mask,814                                eLanguageTypeUnknown, module_list,815                                comp_unit_list);816}817 818lldb::SBBreakpoint SBTarget::BreakpointCreateByName(819    const char *symbol_name, uint32_t name_type_mask,820    LanguageType symbol_language, const SBFileSpecList &module_list,821    const SBFileSpecList &comp_unit_list) {822  LLDB_INSTRUMENT_VA(this, symbol_name, name_type_mask, symbol_language,823                     module_list, comp_unit_list);824  return BreakpointCreateByName(symbol_name, name_type_mask, symbol_language, 0,825                                false, module_list, comp_unit_list);826}827 828lldb::SBBreakpoint SBTarget::BreakpointCreateByName(829    const char *symbol_name, uint32_t name_type_mask,830    LanguageType symbol_language, lldb::addr_t offset,831    bool offset_is_insn_count, const SBFileSpecList &module_list,832    const SBFileSpecList &comp_unit_list) {833  LLDB_INSTRUMENT_VA(this, symbol_name, name_type_mask, symbol_language, offset,834                     offset_is_insn_count, module_list, comp_unit_list);835 836  SBBreakpoint sb_bp;837  if (TargetSP target_sp = GetSP();838      target_sp && symbol_name && symbol_name[0]) {839    const bool internal = false;840    const bool hardware = false;841    const LazyBool skip_prologue = eLazyBoolCalculate;842    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());843    FunctionNameType mask = static_cast<FunctionNameType>(name_type_mask);844    sb_bp = target_sp->CreateBreakpoint(module_list.get(), comp_unit_list.get(),845                                        symbol_name, mask, symbol_language,846                                        offset, offset_is_insn_count,847                                        skip_prologue, internal, hardware);848  }849 850  return sb_bp;851}852 853lldb::SBBreakpoint SBTarget::BreakpointCreateByNames(854    const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask,855    const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) {856  LLDB_INSTRUMENT_VA(this, symbol_names, num_names, name_type_mask, module_list,857                     comp_unit_list);858 859  return BreakpointCreateByNames(symbol_names, num_names, name_type_mask,860                                 eLanguageTypeUnknown, module_list,861                                 comp_unit_list);862}863 864lldb::SBBreakpoint SBTarget::BreakpointCreateByNames(865    const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask,866    LanguageType symbol_language, const SBFileSpecList &module_list,867    const SBFileSpecList &comp_unit_list) {868  LLDB_INSTRUMENT_VA(this, symbol_names, num_names, name_type_mask,869                     symbol_language, module_list, comp_unit_list);870 871  return BreakpointCreateByNames(symbol_names, num_names, name_type_mask,872                                 eLanguageTypeUnknown, 0, module_list,873                                 comp_unit_list);874}875 876lldb::SBBreakpoint SBTarget::BreakpointCreateByNames(877    const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask,878    LanguageType symbol_language, lldb::addr_t offset,879    const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) {880  LLDB_INSTRUMENT_VA(this, symbol_names, num_names, name_type_mask,881                     symbol_language, offset, module_list, comp_unit_list);882 883  SBBreakpoint sb_bp;884  if (TargetSP target_sp = GetSP(); target_sp && num_names > 0) {885    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());886    const bool internal = false;887    const bool hardware = false;888    FunctionNameType mask = static_cast<FunctionNameType>(name_type_mask);889    const LazyBool skip_prologue = eLazyBoolCalculate;890    sb_bp = target_sp->CreateBreakpoint(891        module_list.get(), comp_unit_list.get(), symbol_names, num_names, mask,892        symbol_language, offset, skip_prologue, internal, hardware);893  }894 895  return sb_bp;896}897 898SBBreakpoint SBTarget::BreakpointCreateByRegex(const char *symbol_name_regex,899                                               const char *module_name) {900  LLDB_INSTRUMENT_VA(this, symbol_name_regex, module_name);901 902  SBFileSpecList module_spec_list;903  SBFileSpecList comp_unit_list;904  if (module_name && module_name[0]) {905    module_spec_list.Append(FileSpec(module_name));906  }907  return BreakpointCreateByRegex(symbol_name_regex, eLanguageTypeUnknown,908                                 module_spec_list, comp_unit_list);909}910 911lldb::SBBreakpoint912SBTarget::BreakpointCreateByRegex(const char *symbol_name_regex,913                                  const SBFileSpecList &module_list,914                                  const SBFileSpecList &comp_unit_list) {915  LLDB_INSTRUMENT_VA(this, symbol_name_regex, module_list, comp_unit_list);916 917  return BreakpointCreateByRegex(symbol_name_regex, eLanguageTypeUnknown,918                                 module_list, comp_unit_list);919}920 921lldb::SBBreakpoint SBTarget::BreakpointCreateByRegex(922    const char *symbol_name_regex, LanguageType symbol_language,923    const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) {924  LLDB_INSTRUMENT_VA(this, symbol_name_regex, symbol_language, module_list,925                     comp_unit_list);926 927  SBBreakpoint sb_bp;928  if (TargetSP target_sp = GetSP();929      target_sp && symbol_name_regex && symbol_name_regex[0]) {930    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());931    RegularExpression regexp((llvm::StringRef(symbol_name_regex)));932    const bool internal = false;933    const bool hardware = false;934    const LazyBool skip_prologue = eLazyBoolCalculate;935 936    sb_bp = target_sp->CreateFuncRegexBreakpoint(937        module_list.get(), comp_unit_list.get(), std::move(regexp),938        symbol_language, skip_prologue, internal, hardware);939  }940 941  return sb_bp;942}943 944SBBreakpoint SBTarget::BreakpointCreateByAddress(addr_t address) {945  LLDB_INSTRUMENT_VA(this, address);946 947  SBBreakpoint sb_bp;948  if (TargetSP target_sp = GetSP()) {949    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());950    const bool hardware = false;951    sb_bp = target_sp->CreateBreakpoint(address, false, hardware);952  }953 954  return sb_bp;955}956 957SBBreakpoint SBTarget::BreakpointCreateBySBAddress(SBAddress &sb_address) {958  LLDB_INSTRUMENT_VA(this, sb_address);959 960  SBBreakpoint sb_bp;961  if (!sb_address.IsValid()) {962    return sb_bp;963  }964 965  if (TargetSP target_sp = GetSP()) {966    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());967    const bool hardware = false;968    sb_bp = target_sp->CreateBreakpoint(sb_address.ref(), false, hardware);969  }970 971  return sb_bp;972}973 974lldb::SBBreakpoint975SBTarget::BreakpointCreateBySourceRegex(const char *source_regex,976                                        const lldb::SBFileSpec &source_file,977                                        const char *module_name) {978  LLDB_INSTRUMENT_VA(this, source_regex, source_file, module_name);979 980  SBFileSpecList module_spec_list;981 982  if (module_name && module_name[0]) {983    module_spec_list.Append(FileSpec(module_name));984  }985 986  SBFileSpecList source_file_list;987  if (source_file.IsValid()) {988    source_file_list.Append(source_file);989  }990 991  return BreakpointCreateBySourceRegex(source_regex, module_spec_list,992                                       source_file_list);993}994 995lldb::SBBreakpoint SBTarget::BreakpointCreateBySourceRegex(996    const char *source_regex, const SBFileSpecList &module_list,997    const lldb::SBFileSpecList &source_file_list) {998  LLDB_INSTRUMENT_VA(this, source_regex, module_list, source_file_list);999 1000  return BreakpointCreateBySourceRegex(source_regex, module_list,1001                                       source_file_list, SBStringList());1002}1003 1004lldb::SBBreakpoint SBTarget::BreakpointCreateBySourceRegex(1005    const char *source_regex, const SBFileSpecList &module_list,1006    const lldb::SBFileSpecList &source_file_list,1007    const SBStringList &func_names) {1008  LLDB_INSTRUMENT_VA(this, source_regex, module_list, source_file_list,1009                     func_names);1010 1011  SBBreakpoint sb_bp;1012  if (TargetSP target_sp = GetSP();1013      target_sp && source_regex && source_regex[0]) {1014    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1015    const bool hardware = false;1016    const LazyBool move_to_nearest_code = eLazyBoolCalculate;1017    RegularExpression regexp((llvm::StringRef(source_regex)));1018    std::unordered_set<std::string> func_names_set;1019    for (size_t i = 0; i < func_names.GetSize(); i++) {1020      func_names_set.insert(func_names.GetStringAtIndex(i));1021    }1022 1023    sb_bp = target_sp->CreateSourceRegexBreakpoint(1024        module_list.get(), source_file_list.get(), func_names_set,1025        std::move(regexp), false, hardware, move_to_nearest_code);1026  }1027 1028  return sb_bp;1029}1030 1031lldb::SBBreakpoint1032SBTarget::BreakpointCreateForException(lldb::LanguageType language,1033                                       bool catch_bp, bool throw_bp) {1034  LLDB_INSTRUMENT_VA(this, language, catch_bp, throw_bp);1035 1036  SBBreakpoint sb_bp;1037  if (TargetSP target_sp = GetSP()) {1038    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1039    const bool hardware = false;1040    sb_bp = target_sp->CreateExceptionBreakpoint(language, catch_bp, throw_bp,1041                                                  hardware);1042  }1043 1044  return sb_bp;1045}1046 1047lldb::SBBreakpoint SBTarget::BreakpointCreateFromScript(1048    const char *class_name, SBStructuredData &extra_args,1049    const SBFileSpecList &module_list, const SBFileSpecList &file_list,1050    bool request_hardware) {1051  LLDB_INSTRUMENT_VA(this, class_name, extra_args, module_list, file_list,1052                     request_hardware);1053 1054  SBBreakpoint sb_bp;1055  if (TargetSP target_sp = GetSP()) {1056    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1057    Status error;1058 1059    StructuredData::ObjectSP obj_sp = extra_args.m_impl_up->GetObjectSP();1060    sb_bp =1061        target_sp->CreateScriptedBreakpoint(class_name,1062                                            module_list.get(),1063                                            file_list.get(),1064                                            false, /* internal */1065                                            request_hardware,1066                                            obj_sp,1067                                            &error);1068  }1069 1070  return sb_bp;1071}1072 1073uint32_t SBTarget::GetNumBreakpoints() const {1074  LLDB_INSTRUMENT_VA(this);1075 1076  if (TargetSP target_sp = GetSP()) {1077    // The breakpoint list is thread safe, no need to lock1078    return target_sp->GetBreakpointList().GetSize();1079  }1080  return 0;1081}1082 1083SBBreakpoint SBTarget::GetBreakpointAtIndex(uint32_t idx) const {1084  LLDB_INSTRUMENT_VA(this, idx);1085 1086  SBBreakpoint sb_breakpoint;1087  if (TargetSP target_sp = GetSP()) {1088    // The breakpoint list is thread safe, no need to lock1089    sb_breakpoint = target_sp->GetBreakpointList().GetBreakpointAtIndex(idx);1090  }1091  return sb_breakpoint;1092}1093 1094bool SBTarget::BreakpointDelete(break_id_t bp_id) {1095  LLDB_INSTRUMENT_VA(this, bp_id);1096 1097  bool result = false;1098  if (TargetSP target_sp = GetSP()) {1099    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1100    result = target_sp->RemoveBreakpointByID(bp_id);1101  }1102 1103  return result;1104}1105 1106SBBreakpoint SBTarget::FindBreakpointByID(break_id_t bp_id) {1107  LLDB_INSTRUMENT_VA(this, bp_id);1108 1109  SBBreakpoint sb_breakpoint;1110  if (TargetSP target_sp = GetSP();1111      target_sp && bp_id != LLDB_INVALID_BREAK_ID) {1112    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1113    sb_breakpoint = target_sp->GetBreakpointByID(bp_id);1114  }1115 1116  return sb_breakpoint;1117}1118 1119bool SBTarget::FindBreakpointsByName(const char *name,1120                                     SBBreakpointList &bkpts) {1121  LLDB_INSTRUMENT_VA(this, name, bkpts);1122 1123  if (TargetSP target_sp = GetSP()) {1124    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1125    llvm::Expected<std::vector<BreakpointSP>> expected_vector =1126        target_sp->GetBreakpointList().FindBreakpointsByName(name);1127    if (!expected_vector) {1128      LLDB_LOG_ERROR(GetLog(LLDBLog::Breakpoints), expected_vector.takeError(),1129                     "invalid breakpoint name: {0}");1130      return false;1131    }1132    for (BreakpointSP bkpt_sp : *expected_vector) {1133      bkpts.AppendByID(bkpt_sp->GetID());1134    }1135  }1136  return true;1137}1138 1139void SBTarget::GetBreakpointNames(SBStringList &names) {1140  LLDB_INSTRUMENT_VA(this, names);1141 1142  names.Clear();1143 1144  if (TargetSP target_sp = GetSP()) {1145    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1146 1147    std::vector<std::string> name_vec;1148    target_sp->GetBreakpointNames(name_vec);1149    for (const auto &name : name_vec)1150      names.AppendString(name.c_str());1151  }1152}1153 1154void SBTarget::DeleteBreakpointName(const char *name) {1155  LLDB_INSTRUMENT_VA(this, name);1156 1157  if (TargetSP target_sp = GetSP()) {1158    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1159    target_sp->DeleteBreakpointName(ConstString(name));1160  }1161}1162 1163bool SBTarget::EnableAllBreakpoints() {1164  LLDB_INSTRUMENT_VA(this);1165 1166  if (TargetSP target_sp = GetSP()) {1167    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1168    target_sp->EnableAllowedBreakpoints();1169    return true;1170  }1171  return false;1172}1173 1174bool SBTarget::DisableAllBreakpoints() {1175  LLDB_INSTRUMENT_VA(this);1176 1177  if (TargetSP target_sp = GetSP()) {1178    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1179    target_sp->DisableAllowedBreakpoints();1180    return true;1181  }1182  return false;1183}1184 1185bool SBTarget::DeleteAllBreakpoints() {1186  LLDB_INSTRUMENT_VA(this);1187 1188  if (TargetSP target_sp = GetSP()) {1189    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1190    target_sp->RemoveAllowedBreakpoints();1191    return true;1192  }1193  return false;1194}1195 1196lldb::SBError SBTarget::BreakpointsCreateFromFile(SBFileSpec &source_file,1197                                                  SBBreakpointList &new_bps) {1198  LLDB_INSTRUMENT_VA(this, source_file, new_bps);1199 1200  SBStringList empty_name_list;1201  return BreakpointsCreateFromFile(source_file, empty_name_list, new_bps);1202}1203 1204lldb::SBError SBTarget::BreakpointsCreateFromFile(SBFileSpec &source_file,1205                                                  SBStringList &matching_names,1206                                                  SBBreakpointList &new_bps) {1207  LLDB_INSTRUMENT_VA(this, source_file, matching_names, new_bps);1208 1209  SBError sberr;1210  if (TargetSP target_sp = GetSP()) {1211    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1212 1213    BreakpointIDList bp_ids;1214 1215    std::vector<std::string> name_vector;1216    size_t num_names = matching_names.GetSize();1217    for (size_t i = 0; i < num_names; i++)1218      name_vector.push_back(matching_names.GetStringAtIndex(i));1219 1220    sberr.ref() = target_sp->CreateBreakpointsFromFile(source_file.ref(),1221                                                       name_vector, bp_ids);1222    if (sberr.Fail())1223      return sberr;1224 1225    size_t num_bkpts = bp_ids.GetSize();1226    for (size_t i = 0; i < num_bkpts; i++) {1227      BreakpointID bp_id = bp_ids.GetBreakpointIDAtIndex(i);1228      new_bps.AppendByID(bp_id.GetBreakpointID());1229    }1230  } else {1231    sberr.SetErrorString(1232        "BreakpointCreateFromFile called with invalid target.");1233  }1234  return sberr;1235}1236 1237lldb::SBError SBTarget::BreakpointsWriteToFile(SBFileSpec &dest_file) {1238  LLDB_INSTRUMENT_VA(this, dest_file);1239 1240  SBError sberr;1241  if (TargetSP target_sp = GetSP()) {1242    SBBreakpointList bkpt_list(*this);1243    return BreakpointsWriteToFile(dest_file, bkpt_list);1244  }1245  sberr.SetErrorString("BreakpointWriteToFile called with invalid target.");1246  return sberr;1247}1248 1249lldb::SBError SBTarget::BreakpointsWriteToFile(SBFileSpec &dest_file,1250                                               SBBreakpointList &bkpt_list,1251                                               bool append) {1252  LLDB_INSTRUMENT_VA(this, dest_file, bkpt_list, append);1253 1254  SBError sberr;1255  if (TargetSP target_sp = GetSP()) {1256    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1257    BreakpointIDList bp_id_list;1258    bkpt_list.CopyToBreakpointIDList(bp_id_list);1259    sberr.ref() = target_sp->SerializeBreakpointsToFile(dest_file.ref(),1260                                                        bp_id_list, append);1261  } else {1262    sberr.SetErrorString("BreakpointWriteToFile called with invalid target.");1263  }1264  return sberr;1265}1266 1267uint32_t SBTarget::GetNumWatchpoints() const {1268  LLDB_INSTRUMENT_VA(this);1269 1270  if (TargetSP target_sp = GetSP()) {1271    // The watchpoint list is thread safe, no need to lock1272    return target_sp->GetWatchpointList().GetSize();1273  }1274  return 0;1275}1276 1277SBWatchpoint SBTarget::GetWatchpointAtIndex(uint32_t idx) const {1278  LLDB_INSTRUMENT_VA(this, idx);1279 1280  SBWatchpoint sb_watchpoint;1281  if (TargetSP target_sp = GetSP()) {1282    // The watchpoint list is thread safe, no need to lock1283    sb_watchpoint.SetSP(target_sp->GetWatchpointList().GetByIndex(idx));1284  }1285  return sb_watchpoint;1286}1287 1288bool SBTarget::DeleteWatchpoint(watch_id_t wp_id) {1289  LLDB_INSTRUMENT_VA(this, wp_id);1290 1291  bool result = false;1292  if (TargetSP target_sp = GetSP()) {1293    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1294    std::unique_lock<std::recursive_mutex> lock;1295    target_sp->GetWatchpointList().GetListMutex(lock);1296    result = target_sp->RemoveWatchpointByID(wp_id);1297  }1298 1299  return result;1300}1301 1302SBWatchpoint SBTarget::FindWatchpointByID(lldb::watch_id_t wp_id) {1303  LLDB_INSTRUMENT_VA(this, wp_id);1304 1305  SBWatchpoint sb_watchpoint;1306  lldb::WatchpointSP watchpoint_sp;1307  if (TargetSP target_sp = GetSP();1308      target_sp && wp_id != LLDB_INVALID_WATCH_ID) {1309    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1310    std::unique_lock<std::recursive_mutex> lock;1311    target_sp->GetWatchpointList().GetListMutex(lock);1312    watchpoint_sp = target_sp->GetWatchpointList().FindByID(wp_id);1313    sb_watchpoint.SetSP(watchpoint_sp);1314  }1315 1316  return sb_watchpoint;1317}1318 1319lldb::SBWatchpoint SBTarget::WatchAddress(lldb::addr_t addr, size_t size,1320                                          bool read, bool modify,1321                                          SBError &error) {1322  LLDB_INSTRUMENT_VA(this, addr, size, read, write, error);1323 1324  SBWatchpointOptions options;1325  options.SetWatchpointTypeRead(read);1326  if (modify)1327    options.SetWatchpointTypeWrite(eWatchpointWriteTypeOnModify);1328  return WatchpointCreateByAddress(addr, size, options, error);1329}1330 1331lldb::SBWatchpoint1332SBTarget::WatchpointCreateByAddress(lldb::addr_t addr, size_t size,1333                                    SBWatchpointOptions options,1334                                    SBError &error) {1335  LLDB_INSTRUMENT_VA(this, addr, size, options, error);1336 1337  SBWatchpoint sb_watchpoint;1338  lldb::WatchpointSP watchpoint_sp;1339  uint32_t watch_type = 0;1340  if (options.GetWatchpointTypeRead())1341    watch_type |= LLDB_WATCH_TYPE_READ;1342  if (options.GetWatchpointTypeWrite() == eWatchpointWriteTypeAlways)1343    watch_type |= LLDB_WATCH_TYPE_WRITE;1344  if (options.GetWatchpointTypeWrite() == eWatchpointWriteTypeOnModify)1345    watch_type |= LLDB_WATCH_TYPE_MODIFY;1346  if (watch_type == 0) {1347    error.SetErrorString("Can't create a watchpoint that is neither read nor "1348                         "write nor modify.");1349    return sb_watchpoint;1350  }1351 1352  if (TargetSP target_sp = GetSP();1353      target_sp && addr != LLDB_INVALID_ADDRESS && size > 0) {1354    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1355    // Target::CreateWatchpoint() is thread safe.1356    Status cw_error;1357    // This API doesn't take in a type, so we can't figure out what it is.1358    CompilerType *type = nullptr;1359    watchpoint_sp =1360        target_sp->CreateWatchpoint(addr, size, type, watch_type, cw_error);1361    error.SetError(std::move(cw_error));1362    sb_watchpoint.SetSP(watchpoint_sp);1363  }1364 1365  return sb_watchpoint;1366}1367 1368bool SBTarget::EnableAllWatchpoints() {1369  LLDB_INSTRUMENT_VA(this);1370 1371  if (TargetSP target_sp = GetSP()) {1372    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1373    std::unique_lock<std::recursive_mutex> lock;1374    target_sp->GetWatchpointList().GetListMutex(lock);1375    target_sp->EnableAllWatchpoints();1376    return true;1377  }1378  return false;1379}1380 1381bool SBTarget::DisableAllWatchpoints() {1382  LLDB_INSTRUMENT_VA(this);1383 1384  if (TargetSP target_sp = GetSP()) {1385    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1386    std::unique_lock<std::recursive_mutex> lock;1387    target_sp->GetWatchpointList().GetListMutex(lock);1388    target_sp->DisableAllWatchpoints();1389    return true;1390  }1391  return false;1392}1393 1394SBValue SBTarget::CreateValueFromAddress(const char *name, SBAddress addr,1395                                         SBType type) {1396  LLDB_INSTRUMENT_VA(this, name, addr, type);1397 1398  SBValue sb_value;1399  lldb::ValueObjectSP new_value_sp;1400  if (IsValid() && name && *name && addr.IsValid() && type.IsValid()) {1401    lldb::addr_t load_addr(addr.GetLoadAddress(*this));1402    ExecutionContext exe_ctx(1403        ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false)));1404    CompilerType ast_type(type.GetSP()->GetCompilerType(true));1405    new_value_sp = ValueObject::CreateValueObjectFromAddress(name, load_addr,1406                                                             exe_ctx, ast_type);1407  }1408  sb_value.SetSP(new_value_sp);1409  return sb_value;1410}1411 1412lldb::SBValue SBTarget::CreateValueFromData(const char *name, lldb::SBData data,1413                                            lldb::SBType type) {1414  LLDB_INSTRUMENT_VA(this, name, data, type);1415 1416  SBValue sb_value;1417  lldb::ValueObjectSP new_value_sp;1418  if (IsValid() && name && *name && data.IsValid() && type.IsValid()) {1419    DataExtractorSP extractor(*data);1420    ExecutionContext exe_ctx(1421        ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false)));1422    CompilerType ast_type(type.GetSP()->GetCompilerType(true));1423    new_value_sp = ValueObject::CreateValueObjectFromData(name, *extractor,1424                                                          exe_ctx, ast_type);1425  }1426  sb_value.SetSP(new_value_sp);1427  return sb_value;1428}1429 1430lldb::SBValue SBTarget::CreateValueFromExpression(const char *name,1431                                                  const char *expr) {1432  LLDB_INSTRUMENT_VA(this, name, expr);1433 1434  SBValue sb_value;1435  lldb::ValueObjectSP new_value_sp;1436  if (IsValid() && name && *name && expr && *expr) {1437    ExecutionContext exe_ctx(1438        ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false)));1439    new_value_sp =1440        ValueObject::CreateValueObjectFromExpression(name, expr, exe_ctx);1441  }1442  sb_value.SetSP(new_value_sp);1443  return sb_value;1444}1445 1446bool SBTarget::DeleteAllWatchpoints() {1447  LLDB_INSTRUMENT_VA(this);1448 1449  if (TargetSP target_sp = GetSP()) {1450    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());1451    std::unique_lock<std::recursive_mutex> lock;1452    target_sp->GetWatchpointList().GetListMutex(lock);1453    target_sp->RemoveAllWatchpoints();1454    return true;1455  }1456  return false;1457}1458 1459void SBTarget::AppendImageSearchPath(const char *from, const char *to,1460                                     lldb::SBError &error) {1461  LLDB_INSTRUMENT_VA(this, from, to, error);1462 1463  if (TargetSP target_sp = GetSP()) {1464    llvm::StringRef srFrom = from, srTo = to;1465    if (srFrom.empty())1466      return error.SetErrorString("<from> path can't be empty");1467    if (srTo.empty())1468      return error.SetErrorString("<to> path can't be empty");1469 1470    target_sp->GetImageSearchPathList().Append(srFrom, srTo, true);1471  } else {1472    error.SetErrorString("invalid target");1473  }1474}1475 1476lldb::SBModule SBTarget::AddModule(const char *path, const char *triple,1477                                   const char *uuid_cstr) {1478  LLDB_INSTRUMENT_VA(this, path, triple, uuid_cstr);1479 1480  return AddModule(path, triple, uuid_cstr, nullptr);1481}1482 1483lldb::SBModule SBTarget::AddModule(const char *path, const char *triple,1484                                   const char *uuid_cstr, const char *symfile) {1485  LLDB_INSTRUMENT_VA(this, path, triple, uuid_cstr, symfile);1486 1487  if (TargetSP target_sp = GetSP()) {1488    ModuleSpec module_spec;1489    if (path)1490      module_spec.GetFileSpec().SetFile(path, FileSpec::Style::native);1491 1492    if (uuid_cstr)1493      module_spec.GetUUID().SetFromStringRef(uuid_cstr);1494 1495    if (triple)1496      module_spec.GetArchitecture() = Platform::GetAugmentedArchSpec(1497          target_sp->GetPlatform().get(), triple);1498    else1499      module_spec.GetArchitecture() = target_sp->GetArchitecture();1500 1501    if (symfile)1502      module_spec.GetSymbolFileSpec().SetFile(symfile, FileSpec::Style::native);1503 1504    SBModuleSpec sb_modulespec(module_spec);1505 1506    return AddModule(sb_modulespec);1507  }1508  return SBModule();1509}1510 1511lldb::SBModule SBTarget::AddModule(const SBModuleSpec &module_spec) {1512  LLDB_INSTRUMENT_VA(this, module_spec);1513 1514  lldb::SBModule sb_module;1515  if (TargetSP target_sp = GetSP()) {1516    sb_module.SetSP(target_sp->GetOrCreateModule(*module_spec.m_opaque_up,1517                                                 true /* notify */));1518    if (!sb_module.IsValid() && module_spec.m_opaque_up->GetUUID().IsValid()) {1519      Status error;1520      if (PluginManager::DownloadObjectAndSymbolFile(*module_spec.m_opaque_up,1521                                                     error,1522                                                     /* force_lookup */ true)) {1523        if (FileSystem::Instance().Exists(1524                module_spec.m_opaque_up->GetFileSpec())) {1525          sb_module.SetSP(target_sp->GetOrCreateModule(*module_spec.m_opaque_up,1526                                                       true /* notify */));1527        }1528      }1529    }1530 1531    // If the target hasn't initialized any architecture yet, use the1532    // binary's architecture.1533    if (sb_module.IsValid() && !target_sp->GetArchitecture().IsValid() &&1534        sb_module.GetSP()->GetArchitecture().IsValid())1535      target_sp->SetArchitecture(sb_module.GetSP()->GetArchitecture());1536  }1537  return sb_module;1538}1539 1540bool SBTarget::AddModule(lldb::SBModule &module) {1541  LLDB_INSTRUMENT_VA(this, module);1542 1543  if (TargetSP target_sp = GetSP()) {1544    target_sp->GetImages().AppendIfNeeded(module.GetSP());1545    return true;1546  }1547  return false;1548}1549 1550uint32_t SBTarget::GetNumModules() const {1551  LLDB_INSTRUMENT_VA(this);1552 1553  uint32_t num = 0;1554  if (TargetSP target_sp = GetSP()) {1555    // The module list is thread safe, no need to lock1556    num = target_sp->GetImages().GetSize();1557  }1558 1559  return num;1560}1561 1562void SBTarget::Clear() {1563  LLDB_INSTRUMENT_VA(this);1564 1565  m_opaque_sp.reset();1566}1567 1568SBModule SBTarget::FindModule(const SBFileSpec &sb_file_spec) {1569  LLDB_INSTRUMENT_VA(this, sb_file_spec);1570 1571  SBModule sb_module;1572  if (TargetSP target_sp = GetSP(); target_sp && sb_file_spec.IsValid()) {1573    ModuleSpec module_spec(*sb_file_spec);1574    // The module list is thread safe, no need to lock1575    sb_module.SetSP(target_sp->GetImages().FindFirstModule(module_spec));1576  }1577  return sb_module;1578}1579 1580SBModule SBTarget::FindModule(const SBModuleSpec &sb_module_spec) {1581  LLDB_INSTRUMENT_VA(this, sb_module_spec);1582 1583  SBModule sb_module;1584  if (TargetSP target_sp = GetSP(); target_sp && sb_module_spec.IsValid()) {1585    // The module list is thread safe, no need to lock.1586    sb_module.SetSP(1587        target_sp->GetImages().FindFirstModule(*sb_module_spec.m_opaque_up));1588  }1589  return sb_module;1590}1591 1592SBSymbolContextList SBTarget::FindCompileUnits(const SBFileSpec &sb_file_spec) {1593  LLDB_INSTRUMENT_VA(this, sb_file_spec);1594 1595  SBSymbolContextList sb_sc_list;1596  if (TargetSP target_sp = GetSP(); target_sp && sb_file_spec.IsValid())1597    target_sp->GetImages().FindCompileUnits(*sb_file_spec, *sb_sc_list);1598  return sb_sc_list;1599}1600 1601lldb::ByteOrder SBTarget::GetByteOrder() {1602  LLDB_INSTRUMENT_VA(this);1603 1604  if (TargetSP target_sp = GetSP())1605    return target_sp->GetArchitecture().GetByteOrder();1606  return eByteOrderInvalid;1607}1608 1609const char *SBTarget::GetTriple() {1610  LLDB_INSTRUMENT_VA(this);1611 1612  if (TargetSP target_sp = GetSP()) {1613    std::string triple(target_sp->GetArchitecture().GetTriple().str());1614    // Unique the string so we don't run into ownership issues since the const1615    // strings put the string into the string pool once and the strings never1616    // comes out1617    ConstString const_triple(triple.c_str());1618    return const_triple.GetCString();1619  }1620  return nullptr;1621}1622 1623const char *SBTarget::GetArchName() {1624  LLDB_INSTRUMENT_VA(this);1625 1626  if (TargetSP target_sp = GetSP()) {1627    llvm::StringRef arch_name =1628        target_sp->GetArchitecture().GetTriple().getArchName();1629    ConstString const_arch_name(arch_name);1630 1631    return const_arch_name.GetCString();1632  }1633  return nullptr;1634}1635 1636const char *SBTarget::GetABIName() {1637  LLDB_INSTRUMENT_VA(this);1638 1639  if (TargetSP target_sp = GetSP()) {1640    std::string abi_name(target_sp->GetABIName().str());1641    ConstString const_name(abi_name.c_str());1642    return const_name.GetCString();1643  }1644  return nullptr;1645}1646 1647const char *SBTarget::GetLabel() const {1648  LLDB_INSTRUMENT_VA(this);1649 1650  if (TargetSP target_sp = GetSP())1651    return ConstString(target_sp->GetLabel().data()).AsCString();1652  return nullptr;1653}1654 1655lldb::user_id_t SBTarget::GetGloballyUniqueID() const {1656  LLDB_INSTRUMENT_VA(this);1657 1658  if (TargetSP target_sp = GetSP())1659    return target_sp->GetGloballyUniqueID();1660  return LLDB_INVALID_GLOBALLY_UNIQUE_TARGET_ID;1661}1662 1663const char *SBTarget::GetTargetSessionName() const {1664  LLDB_INSTRUMENT_VA(this);1665 1666  if (TargetSP target_sp = GetSP())1667    return ConstString(target_sp->GetTargetSessionName()).AsCString();1668  return nullptr;1669}1670 1671SBError SBTarget::SetLabel(const char *label) {1672  LLDB_INSTRUMENT_VA(this, label);1673 1674  if (TargetSP target_sp = GetSP())1675    return Status::FromError(target_sp->SetLabel(label));1676  return Status::FromErrorString("Couldn't get internal target object.");1677}1678 1679uint32_t SBTarget::GetMinimumOpcodeByteSize() const {1680  LLDB_INSTRUMENT_VA(this);1681 1682  if (TargetSP target_sp = GetSP())1683    return target_sp->GetArchitecture().GetMinimumOpcodeByteSize();1684  return 0;1685}1686 1687uint32_t SBTarget::GetMaximumOpcodeByteSize() const {1688  LLDB_INSTRUMENT_VA(this);1689 1690  TargetSP target_sp(GetSP());1691  if (target_sp)1692    return target_sp->GetArchitecture().GetMaximumOpcodeByteSize();1693 1694  return 0;1695}1696 1697uint32_t SBTarget::GetDataByteSize() {1698  LLDB_INSTRUMENT_VA(this);1699 1700  if (TargetSP target_sp = GetSP())1701    return target_sp->GetArchitecture().GetDataByteSize();1702  return 0;1703}1704 1705uint32_t SBTarget::GetCodeByteSize() {1706  LLDB_INSTRUMENT_VA(this);1707 1708  if (TargetSP target_sp = GetSP())1709    return target_sp->GetArchitecture().GetCodeByteSize();1710  return 0;1711}1712 1713uint32_t SBTarget::GetMaximumNumberOfChildrenToDisplay() const {1714  LLDB_INSTRUMENT_VA(this);1715 1716  if (TargetSP target_sp = GetSP())1717    return target_sp->GetMaximumNumberOfChildrenToDisplay();1718  return 0;1719}1720 1721uint32_t SBTarget::GetAddressByteSize() {1722  LLDB_INSTRUMENT_VA(this);1723 1724  if (TargetSP target_sp = GetSP())1725    return target_sp->GetArchitecture().GetAddressByteSize();1726  return sizeof(void *);1727}1728 1729SBModule SBTarget::GetModuleAtIndex(uint32_t idx) {1730  LLDB_INSTRUMENT_VA(this, idx);1731 1732  SBModule sb_module;1733  ModuleSP module_sp;1734  if (TargetSP target_sp = GetSP()) {1735    // The module list is thread safe, no need to lock1736    module_sp = target_sp->GetImages().GetModuleAtIndex(idx);1737    sb_module.SetSP(module_sp);1738  }1739 1740  return sb_module;1741}1742 1743bool SBTarget::RemoveModule(lldb::SBModule module) {1744  LLDB_INSTRUMENT_VA(this, module);1745 1746  if (TargetSP target_sp = GetSP())1747    return target_sp->GetImages().Remove(module.GetSP());1748  return false;1749}1750 1751SBBroadcaster SBTarget::GetBroadcaster() const {1752  LLDB_INSTRUMENT_VA(this);1753 1754  if (TargetSP target_sp = GetSP()) {1755    SBBroadcaster broadcaster(target_sp.get(), false);1756    return broadcaster;1757  }1758  return SBBroadcaster();1759}1760 1761bool SBTarget::GetDescription(SBStream &description,1762                              lldb::DescriptionLevel description_level) {1763  LLDB_INSTRUMENT_VA(this, description, description_level);1764 1765  Stream &strm = description.ref();1766 1767  if (TargetSP target_sp = GetSP()) {1768    target_sp->Dump(&strm, description_level);1769  } else1770    strm.PutCString("No value");1771 1772  return true;1773}1774 1775lldb::SBSymbolContextList SBTarget::FindFunctions(const char *name,1776                                                  uint32_t name_type_mask) {1777  LLDB_INSTRUMENT_VA(this, name, name_type_mask);1778 1779  lldb::SBSymbolContextList sb_sc_list;1780  if (!name || !name[0])1781    return sb_sc_list;1782 1783  if (TargetSP target_sp = GetSP()) {1784    ModuleFunctionSearchOptions function_options;1785    function_options.include_symbols = true;1786    function_options.include_inlines = true;1787 1788    FunctionNameType mask = static_cast<FunctionNameType>(name_type_mask);1789    target_sp->GetImages().FindFunctions(ConstString(name), mask,1790                                         function_options, *sb_sc_list);1791  }1792  return sb_sc_list;1793}1794 1795lldb::SBSymbolContextList SBTarget::FindGlobalFunctions(const char *name,1796                                                        uint32_t max_matches,1797                                                        MatchType matchtype) {1798  LLDB_INSTRUMENT_VA(this, name, max_matches, matchtype);1799 1800  lldb::SBSymbolContextList sb_sc_list;1801  if (name && name[0]) {1802    llvm::StringRef name_ref(name);1803    if (TargetSP target_sp = GetSP()) {1804      ModuleFunctionSearchOptions function_options;1805      function_options.include_symbols = true;1806      function_options.include_inlines = true;1807 1808      std::string regexstr;1809      switch (matchtype) {1810      case eMatchTypeRegex:1811        target_sp->GetImages().FindFunctions(RegularExpression(name_ref),1812                                             function_options, *sb_sc_list);1813        break;1814      case eMatchTypeRegexInsensitive:1815        target_sp->GetImages().FindFunctions(1816            RegularExpression(name_ref, llvm::Regex::RegexFlags::IgnoreCase),1817            function_options, *sb_sc_list);1818        break;1819      case eMatchTypeStartsWith:1820        regexstr = llvm::Regex::escape(name) + ".*";1821        target_sp->GetImages().FindFunctions(RegularExpression(regexstr),1822                                             function_options, *sb_sc_list);1823        break;1824      default:1825        target_sp->GetImages().FindFunctions(ConstString(name),1826                                             eFunctionNameTypeAny,1827                                             function_options, *sb_sc_list);1828        break;1829      }1830    }1831  }1832  return sb_sc_list;1833}1834 1835lldb::SBType SBTarget::FindFirstType(const char *typename_cstr) {1836  LLDB_INSTRUMENT_VA(this, typename_cstr);1837 1838  if (TargetSP target_sp = GetSP();1839      target_sp && typename_cstr && typename_cstr[0]) {1840    ConstString const_typename(typename_cstr);1841    TypeQuery query(const_typename.GetStringRef(),1842                    TypeQueryOptions::e_find_one);1843    TypeResults results;1844    target_sp->GetImages().FindTypes(/*search_first=*/nullptr, query, results);1845    if (TypeSP type_sp = results.GetFirstType())1846      return SBType(type_sp);1847    // Didn't find the type in the symbols; Try the loaded language runtimes.1848    if (auto process_sp = target_sp->GetProcessSP()) {1849      for (auto *runtime : process_sp->GetLanguageRuntimes()) {1850        if (auto vendor = runtime->GetDeclVendor()) {1851          auto types = vendor->FindTypes(const_typename, /*max_matches*/ 1);1852          if (!types.empty())1853            return SBType(types.front());1854        }1855      }1856    }1857 1858    // No matches, search for basic typename matches.1859    for (auto type_system_sp : target_sp->GetScratchTypeSystems())1860      if (auto type = type_system_sp->GetBuiltinTypeByName(const_typename))1861        return SBType(type);1862  }1863 1864  return SBType();1865}1866 1867SBType SBTarget::GetBasicType(lldb::BasicType type) {1868  LLDB_INSTRUMENT_VA(this, type);1869 1870  if (TargetSP target_sp = GetSP()) {1871    for (auto type_system_sp : target_sp->GetScratchTypeSystems())1872      if (auto compiler_type = type_system_sp->GetBasicTypeFromAST(type))1873        return SBType(compiler_type);1874  }1875  return SBType();1876}1877 1878lldb::SBTypeList SBTarget::FindTypes(const char *typename_cstr) {1879  LLDB_INSTRUMENT_VA(this, typename_cstr);1880 1881  SBTypeList sb_type_list;1882  if (TargetSP target_sp = GetSP();1883      target_sp && typename_cstr && typename_cstr[0]) {1884    ModuleList &images = target_sp->GetImages();1885    ConstString const_typename(typename_cstr);1886    TypeQuery query(typename_cstr);1887    TypeResults results;1888    images.FindTypes(nullptr, query, results);1889    for (const TypeSP &type_sp : results.GetTypeMap().Types())1890      sb_type_list.Append(SBType(type_sp));1891 1892    // Try the loaded language runtimes1893    if (ProcessSP process_sp = target_sp->GetProcessSP()) {1894      for (auto *runtime : process_sp->GetLanguageRuntimes()) {1895        if (auto *vendor = runtime->GetDeclVendor()) {1896          auto types =1897              vendor->FindTypes(const_typename, /*max_matches*/ UINT32_MAX);1898          for (auto type : types)1899            sb_type_list.Append(SBType(type));1900        }1901      }1902    }1903 1904    if (sb_type_list.GetSize() == 0) {1905      // No matches, search for basic typename matches1906      for (auto type_system_sp : target_sp->GetScratchTypeSystems())1907        if (auto compiler_type =1908                type_system_sp->GetBuiltinTypeByName(const_typename))1909          sb_type_list.Append(SBType(compiler_type));1910    }1911  }1912  return sb_type_list;1913}1914 1915SBValueList SBTarget::FindGlobalVariables(const char *name,1916                                          uint32_t max_matches) {1917  LLDB_INSTRUMENT_VA(this, name, max_matches);1918 1919  SBValueList sb_value_list;1920 1921  if (TargetSP target_sp = GetSP(); target_sp && name) {1922    VariableList variable_list;1923    target_sp->GetImages().FindGlobalVariables(ConstString(name), max_matches,1924                                               variable_list);1925    if (!variable_list.Empty()) {1926      ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get();1927      if (exe_scope == nullptr)1928        exe_scope = target_sp.get();1929      for (const VariableSP &var_sp : variable_list) {1930        lldb::ValueObjectSP valobj_sp(1931            ValueObjectVariable::Create(exe_scope, var_sp));1932        if (valobj_sp)1933          sb_value_list.Append(SBValue(valobj_sp));1934      }1935    }1936  }1937 1938  return sb_value_list;1939}1940 1941SBValueList SBTarget::FindGlobalVariables(const char *name,1942                                          uint32_t max_matches,1943                                          MatchType matchtype) {1944  LLDB_INSTRUMENT_VA(this, name, max_matches, matchtype);1945 1946  SBValueList sb_value_list;1947 1948  if (TargetSP target_sp = GetSP(); target_sp && name) {1949    llvm::StringRef name_ref(name);1950    VariableList variable_list;1951 1952    std::string regexstr;1953    switch (matchtype) {1954    case eMatchTypeNormal:1955      target_sp->GetImages().FindGlobalVariables(ConstString(name), max_matches,1956                                                 variable_list);1957      break;1958    case eMatchTypeRegex:1959      target_sp->GetImages().FindGlobalVariables(RegularExpression(name_ref),1960                                                 max_matches, variable_list);1961      break;1962    case eMatchTypeRegexInsensitive:1963      target_sp->GetImages().FindGlobalVariables(1964          RegularExpression(name_ref, llvm::Regex::IgnoreCase), max_matches,1965          variable_list);1966      break;1967    case eMatchTypeStartsWith:1968      regexstr = "^" + llvm::Regex::escape(name) + ".*";1969      target_sp->GetImages().FindGlobalVariables(RegularExpression(regexstr),1970                                                 max_matches, variable_list);1971      break;1972    }1973    if (!variable_list.Empty()) {1974      ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get();1975      if (exe_scope == nullptr)1976        exe_scope = target_sp.get();1977      for (const VariableSP &var_sp : variable_list) {1978        lldb::ValueObjectSP valobj_sp(1979            ValueObjectVariable::Create(exe_scope, var_sp));1980        if (valobj_sp)1981          sb_value_list.Append(SBValue(valobj_sp));1982      }1983    }1984  }1985 1986  return sb_value_list;1987}1988 1989lldb::SBValue SBTarget::FindFirstGlobalVariable(const char *name) {1990  LLDB_INSTRUMENT_VA(this, name);1991 1992  SBValueList sb_value_list(FindGlobalVariables(name, 1));1993  if (sb_value_list.IsValid() && sb_value_list.GetSize() > 0)1994    return sb_value_list.GetValueAtIndex(0);1995  return SBValue();1996}1997 1998SBSourceManager SBTarget::GetSourceManager() {1999  LLDB_INSTRUMENT_VA(this);2000 2001  SBSourceManager source_manager(*this);2002  return source_manager;2003}2004 2005lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr,2006                                                   uint32_t count) {2007  LLDB_INSTRUMENT_VA(this, base_addr, count);2008 2009  return ReadInstructions(base_addr, count, nullptr);2010}2011 2012lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr,2013                                                   uint32_t count,2014                                                   const char *flavor_string) {2015  LLDB_INSTRUMENT_VA(this, base_addr, count, flavor_string);2016 2017  SBInstructionList sb_instructions;2018 2019  if (TargetSP target_sp = GetSP()) {2020    if (Address *addr_ptr = base_addr.get()) {2021      if (llvm::Expected<DisassemblerSP> disassembler =2022              target_sp->ReadInstructions(*addr_ptr, count, flavor_string)) {2023        sb_instructions.SetDisassembler(*disassembler);2024      }2025    }2026  }2027 2028  return sb_instructions;2029}2030 2031lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress start_addr,2032                                                   lldb::SBAddress end_addr,2033                                                   const char *flavor_string) {2034  LLDB_INSTRUMENT_VA(this, start_addr, end_addr, flavor_string);2035 2036  SBInstructionList sb_instructions;2037 2038  if (TargetSP target_sp = GetSP()) {2039    lldb::addr_t start_load_addr = start_addr.GetLoadAddress(*this);2040    lldb::addr_t end_load_addr = end_addr.GetLoadAddress(*this);2041    if (end_load_addr > start_load_addr) {2042      lldb::addr_t size = end_load_addr - start_load_addr;2043 2044      AddressRange range(start_load_addr, size);2045      const bool force_live_memory = true;2046      sb_instructions.SetDisassembler(Disassembler::DisassembleRange(2047          target_sp->GetArchitecture(), nullptr, flavor_string,2048          target_sp->GetDisassemblyCPU(), target_sp->GetDisassemblyFeatures(),2049          *target_sp, range, force_live_memory));2050    }2051  }2052  return sb_instructions;2053}2054 2055lldb::SBInstructionList SBTarget::GetInstructions(lldb::SBAddress base_addr,2056                                                  const void *buf,2057                                                  size_t size) {2058  LLDB_INSTRUMENT_VA(this, base_addr, buf, size);2059 2060  return GetInstructionsWithFlavor(base_addr, nullptr, buf, size);2061}2062 2063lldb::SBInstructionList2064SBTarget::GetInstructionsWithFlavor(lldb::SBAddress base_addr,2065                                    const char *flavor_string, const void *buf,2066                                    size_t size) {2067  LLDB_INSTRUMENT_VA(this, base_addr, flavor_string, buf, size);2068 2069  SBInstructionList sb_instructions;2070 2071  if (TargetSP target_sp = GetSP()) {2072    Address addr;2073 2074    if (base_addr.get())2075      addr = *base_addr.get();2076 2077    constexpr bool data_from_file = true;2078    if (!flavor_string || flavor_string[0] == '\0') {2079      // FIXME - we don't have the mechanism in place to do per-architecture2080      // settings.  But since we know that for now we only support flavors on2081      // x86 & x86_64,2082      const llvm::Triple::ArchType arch =2083          target_sp->GetArchitecture().GetTriple().getArch();2084      if (arch == llvm::Triple::x86 || arch == llvm::Triple::x86_64)2085        flavor_string = target_sp->GetDisassemblyFlavor();2086    }2087 2088    sb_instructions.SetDisassembler(Disassembler::DisassembleBytes(2089        target_sp->GetArchitecture(), nullptr, flavor_string,2090        target_sp->GetDisassemblyCPU(), target_sp->GetDisassemblyFeatures(),2091        addr, buf, size, UINT32_MAX, data_from_file));2092  }2093 2094  return sb_instructions;2095}2096 2097lldb::SBInstructionList SBTarget::GetInstructions(lldb::addr_t base_addr,2098                                                  const void *buf,2099                                                  size_t size) {2100  LLDB_INSTRUMENT_VA(this, base_addr, buf, size);2101 2102  return GetInstructionsWithFlavor(ResolveLoadAddress(base_addr), nullptr, buf,2103                                   size);2104}2105 2106lldb::SBInstructionList2107SBTarget::GetInstructionsWithFlavor(lldb::addr_t base_addr,2108                                    const char *flavor_string, const void *buf,2109                                    size_t size) {2110  LLDB_INSTRUMENT_VA(this, base_addr, flavor_string, buf, size);2111 2112  return GetInstructionsWithFlavor(ResolveLoadAddress(base_addr), flavor_string,2113                                   buf, size);2114}2115 2116SBError SBTarget::SetSectionLoadAddress(lldb::SBSection section,2117                                        lldb::addr_t section_base_addr) {2118  LLDB_INSTRUMENT_VA(this, section, section_base_addr);2119 2120  SBError sb_error;2121  if (TargetSP target_sp = GetSP()) {2122    if (!section.IsValid()) {2123      sb_error.SetErrorStringWithFormat("invalid section");2124    } else {2125      SectionSP section_sp(section.GetSP());2126      if (section_sp) {2127        if (section_sp->IsThreadSpecific()) {2128          sb_error.SetErrorString(2129              "thread specific sections are not yet supported");2130        } else {2131          ProcessSP process_sp(target_sp->GetProcessSP());2132          if (target_sp->SetSectionLoadAddress(section_sp, section_base_addr)) {2133            ModuleSP module_sp(section_sp->GetModule());2134            if (module_sp) {2135              ModuleList module_list;2136              module_list.Append(module_sp);2137              target_sp->ModulesDidLoad(module_list);2138            }2139            // Flush info in the process (stack frames, etc)2140            if (process_sp)2141              process_sp->Flush();2142          }2143        }2144      }2145    }2146  } else {2147    sb_error.SetErrorString("invalid target");2148  }2149  return sb_error;2150}2151 2152SBError SBTarget::ClearSectionLoadAddress(lldb::SBSection section) {2153  LLDB_INSTRUMENT_VA(this, section);2154 2155  SBError sb_error;2156 2157  if (TargetSP target_sp = GetSP()) {2158    if (!section.IsValid()) {2159      sb_error.SetErrorStringWithFormat("invalid section");2160    } else {2161      SectionSP section_sp(section.GetSP());2162      if (section_sp) {2163        ProcessSP process_sp(target_sp->GetProcessSP());2164        if (target_sp->SetSectionUnloaded(section_sp)) {2165          ModuleSP module_sp(section_sp->GetModule());2166          if (module_sp) {2167            ModuleList module_list;2168            module_list.Append(module_sp);2169            target_sp->ModulesDidUnload(module_list, false);2170          }2171          // Flush info in the process (stack frames, etc)2172          if (process_sp)2173            process_sp->Flush();2174        }2175      } else {2176        sb_error.SetErrorStringWithFormat("invalid section");2177      }2178    }2179  } else {2180    sb_error.SetErrorStringWithFormat("invalid target");2181  }2182  return sb_error;2183}2184 2185SBError SBTarget::SetModuleLoadAddress(lldb::SBModule module,2186                                       int64_t slide_offset) {2187  LLDB_INSTRUMENT_VA(this, module, slide_offset);2188 2189  if (slide_offset < 0) {2190    SBError sb_error;2191    sb_error.SetErrorStringWithFormat("slide must be positive");2192    return sb_error;2193  }2194 2195  return SetModuleLoadAddress(module, static_cast<uint64_t>(slide_offset));2196}2197 2198SBError SBTarget::SetModuleLoadAddress(lldb::SBModule module,2199                                               uint64_t slide_offset) {2200 2201  SBError sb_error;2202 2203  if (TargetSP target_sp = GetSP()) {2204    ModuleSP module_sp(module.GetSP());2205    if (module_sp) {2206      bool changed = false;2207      if (module_sp->SetLoadAddress(*target_sp, slide_offset, true, changed)) {2208        // The load was successful, make sure that at least some sections2209        // changed before we notify that our module was loaded.2210        if (changed) {2211          ModuleList module_list;2212          module_list.Append(module_sp);2213          target_sp->ModulesDidLoad(module_list);2214          // Flush info in the process (stack frames, etc)2215          ProcessSP process_sp(target_sp->GetProcessSP());2216          if (process_sp)2217            process_sp->Flush();2218        }2219      }2220    } else {2221      sb_error.SetErrorStringWithFormat("invalid module");2222    }2223 2224  } else {2225    sb_error.SetErrorStringWithFormat("invalid target");2226  }2227  return sb_error;2228}2229 2230SBError SBTarget::ClearModuleLoadAddress(lldb::SBModule module) {2231  LLDB_INSTRUMENT_VA(this, module);2232 2233  SBError sb_error;2234 2235  char path[PATH_MAX];2236  if (TargetSP target_sp = GetSP()) {2237    ModuleSP module_sp(module.GetSP());2238    if (module_sp) {2239      ObjectFile *objfile = module_sp->GetObjectFile();2240      if (objfile) {2241        SectionList *section_list = objfile->GetSectionList();2242        if (section_list) {2243          ProcessSP process_sp(target_sp->GetProcessSP());2244 2245          bool changed = false;2246          const size_t num_sections = section_list->GetSize();2247          for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {2248            SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));2249            if (section_sp)2250              changed |= target_sp->SetSectionUnloaded(section_sp);2251          }2252          if (changed) {2253            ModuleList module_list;2254            module_list.Append(module_sp);2255            target_sp->ModulesDidUnload(module_list, false);2256            // Flush info in the process (stack frames, etc)2257            ProcessSP process_sp(target_sp->GetProcessSP());2258            if (process_sp)2259              process_sp->Flush();2260          }2261        } else {2262          module_sp->GetFileSpec().GetPath(path, sizeof(path));2263          sb_error.SetErrorStringWithFormat("no sections in object file '%s'",2264                                            path);2265        }2266      } else {2267        module_sp->GetFileSpec().GetPath(path, sizeof(path));2268        sb_error.SetErrorStringWithFormat("no object file for module '%s'",2269                                          path);2270      }2271    } else {2272      sb_error.SetErrorStringWithFormat("invalid module");2273    }2274  } else {2275    sb_error.SetErrorStringWithFormat("invalid target");2276  }2277  return sb_error;2278}2279 2280lldb::SBSymbolContextList SBTarget::FindSymbols(const char *name,2281                                                lldb::SymbolType symbol_type) {2282  LLDB_INSTRUMENT_VA(this, name, symbol_type);2283 2284  SBSymbolContextList sb_sc_list;2285  if (name && name[0]) {2286    if (TargetSP target_sp = GetSP()) {2287      target_sp->GetImages().FindSymbolsWithNameAndType(2288          ConstString(name), symbol_type, *sb_sc_list);2289    }2290  }2291  return sb_sc_list;2292}2293 2294lldb::SBValue SBTarget::EvaluateExpression(const char *expr) {2295  LLDB_INSTRUMENT_VA(this, expr);2296 2297  if (TargetSP target_sp = GetSP()) {2298    SBExpressionOptions options;2299    lldb::DynamicValueType fetch_dynamic_value =2300        target_sp->GetPreferDynamicValue();2301    options.SetFetchDynamicValue(fetch_dynamic_value);2302    options.SetUnwindOnError(true);2303    return EvaluateExpression(expr, options);2304  }2305  return SBValue();2306}2307 2308lldb::SBValue SBTarget::EvaluateExpression(const char *expr,2309                                           const SBExpressionOptions &options) {2310  LLDB_INSTRUMENT_VA(this, expr, options);2311 2312  Log *expr_log = GetLog(LLDBLog::Expressions);2313  SBValue expr_result;2314  ValueObjectSP expr_value_sp;2315  if (TargetSP target_sp = GetSP()) {2316    StackFrame *frame = nullptr;2317    if (expr == nullptr || expr[0] == '\0')2318      return expr_result;2319 2320    std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());2321    ExecutionContext exe_ctx(m_opaque_sp.get());2322 2323    frame = exe_ctx.GetFramePtr();2324    Target *target = exe_ctx.GetTargetPtr();2325    Process *process = exe_ctx.GetProcessPtr();2326 2327    if (target) {2328      // If we have a process, make sure to lock the runlock:2329      if (process) {2330        Process::StopLocker stop_locker;2331        if (stop_locker.TryLock(&process->GetRunLock())) {2332          target->EvaluateExpression(expr, frame, expr_value_sp, options.ref());2333        } else {2334          Status error;2335          error = Status::FromErrorString("can't evaluate expressions when the "2336                                          "process is running.");2337          expr_value_sp =2338              ValueObjectConstResult::Create(nullptr, std::move(error));2339        }2340      } else {2341        target->EvaluateExpression(expr, frame, expr_value_sp, options.ref());2342      }2343 2344      expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue());2345    }2346  }2347  LLDB_LOGF(expr_log,2348            "** [SBTarget::EvaluateExpression] Expression result is "2349            "%s, summary %s **",2350            expr_result.GetValue(), expr_result.GetSummary());2351  return expr_result;2352}2353 2354lldb::addr_t SBTarget::GetStackRedZoneSize() {2355  LLDB_INSTRUMENT_VA(this);2356 2357  if (TargetSP target_sp = GetSP()) {2358    ABISP abi_sp;2359    ProcessSP process_sp(target_sp->GetProcessSP());2360    if (process_sp)2361      abi_sp = process_sp->GetABI();2362    else2363      abi_sp = ABI::FindPlugin(ProcessSP(), target_sp->GetArchitecture());2364    if (abi_sp)2365      return abi_sp->GetRedZoneSize();2366  }2367  return 0;2368}2369 2370bool SBTarget::IsLoaded(const SBModule &module) const {2371  LLDB_INSTRUMENT_VA(this, module);2372 2373  if (TargetSP target_sp = GetSP()) {2374    ModuleSP module_sp(module.GetSP());2375    if (module_sp)2376      return module_sp->IsLoadedInTarget(target_sp.get());2377  }2378  return false;2379}2380 2381lldb::SBLaunchInfo SBTarget::GetLaunchInfo() const {2382  LLDB_INSTRUMENT_VA(this);2383 2384  lldb::SBLaunchInfo launch_info(nullptr);2385  if (TargetSP target_sp = GetSP())2386    launch_info.set_ref(m_opaque_sp->GetProcessLaunchInfo());2387  return launch_info;2388}2389 2390void SBTarget::SetLaunchInfo(const lldb::SBLaunchInfo &launch_info) {2391  LLDB_INSTRUMENT_VA(this, launch_info);2392 2393  if (TargetSP target_sp = GetSP())2394    m_opaque_sp->SetProcessLaunchInfo(launch_info.ref());2395}2396 2397SBEnvironment SBTarget::GetEnvironment() {2398  LLDB_INSTRUMENT_VA(this);2399 2400  if (TargetSP target_sp = GetSP())2401    return SBEnvironment(target_sp->GetEnvironment());2402 2403  return SBEnvironment();2404}2405 2406lldb::SBTrace SBTarget::GetTrace() {2407  LLDB_INSTRUMENT_VA(this);2408 2409  if (TargetSP target_sp = GetSP())2410    return SBTrace(target_sp->GetTrace());2411 2412  return SBTrace();2413}2414 2415lldb::SBTrace SBTarget::CreateTrace(lldb::SBError &error) {2416  LLDB_INSTRUMENT_VA(this, error);2417 2418  error.Clear();2419  if (TargetSP target_sp = GetSP()) {2420    if (llvm::Expected<lldb::TraceSP> trace_sp = target_sp->CreateTrace()) {2421      return SBTrace(*trace_sp);2422    } else {2423      error.SetErrorString(llvm::toString(trace_sp.takeError()).c_str());2424    }2425  } else {2426    error.SetErrorString("missing target");2427  }2428  return SBTrace();2429}2430 2431lldb::SBMutex SBTarget::GetAPIMutex() const {2432  LLDB_INSTRUMENT_VA(this);2433 2434  if (TargetSP target_sp = GetSP())2435    return lldb::SBMutex(target_sp);2436  return lldb::SBMutex();2437}2438