diff options
Diffstat (limited to 'contrib/llvm-project/lldb/source/API')
84 files changed, 28511 insertions, 0 deletions
diff --git a/contrib/llvm-project/lldb/source/API/SBAddress.cpp b/contrib/llvm-project/lldb/source/API/SBAddress.cpp new file mode 100644 index 000000000000..e519f0bcc83c --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBAddress.cpp @@ -0,0 +1,268 @@ +//===-- SBAddress.cpp -----------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBAddress.h" +#include "Utils.h" +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBSection.h" +#include "lldb/API/SBStream.h" +#include "lldb/Core/Address.h" +#include "lldb/Core/Module.h" +#include "lldb/Symbol/LineEntry.h" +#include "lldb/Target/Target.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/StreamString.h" + +using namespace lldb; +using namespace lldb_private; + +SBAddress::SBAddress() : m_opaque_up(new Address()) { + LLDB_INSTRUMENT_VA(this); +} + +SBAddress::SBAddress(const Address &address) + : m_opaque_up(std::make_unique<Address>(address)) {} + +SBAddress::SBAddress(const SBAddress &rhs) : m_opaque_up(new Address()) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBAddress::SBAddress(lldb::SBSection section, lldb::addr_t offset) + : m_opaque_up(new Address(section.GetSP(), offset)) { + LLDB_INSTRUMENT_VA(this, section, offset); +} + +// Create an address by resolving a load address using the supplied target +SBAddress::SBAddress(lldb::addr_t load_addr, lldb::SBTarget &target) + : m_opaque_up(new Address()) { + LLDB_INSTRUMENT_VA(this, load_addr, target); + + SetLoadAddress(load_addr, target); +} + +SBAddress::~SBAddress() = default; + +const SBAddress &SBAddress::operator=(const SBAddress &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +bool lldb::operator==(const SBAddress &lhs, const SBAddress &rhs) { + if (lhs.IsValid() && rhs.IsValid()) + return lhs.ref() == rhs.ref(); + return false; +} + +bool SBAddress::operator!=(const SBAddress &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return !(*this == rhs); +} + +bool SBAddress::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBAddress::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up != nullptr && m_opaque_up->IsValid(); +} + +void SBAddress::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_up = std::make_unique<Address>(); +} + +void SBAddress::SetAddress(lldb::SBSection section, lldb::addr_t offset) { + LLDB_INSTRUMENT_VA(this, section, offset); + + Address &addr = ref(); + addr.SetSection(section.GetSP()); + addr.SetOffset(offset); +} + +void SBAddress::SetAddress(const Address &address) { ref() = address; } + +lldb::addr_t SBAddress::GetFileAddress() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up->IsValid()) + return m_opaque_up->GetFileAddress(); + else + return LLDB_INVALID_ADDRESS; +} + +lldb::addr_t SBAddress::GetLoadAddress(const SBTarget &target) const { + LLDB_INSTRUMENT_VA(this, target); + + lldb::addr_t addr = LLDB_INVALID_ADDRESS; + TargetSP target_sp(target.GetSP()); + if (target_sp) { + if (m_opaque_up->IsValid()) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + addr = m_opaque_up->GetLoadAddress(target_sp.get()); + } + } + + return addr; +} + +void SBAddress::SetLoadAddress(lldb::addr_t load_addr, lldb::SBTarget &target) { + LLDB_INSTRUMENT_VA(this, load_addr, target); + + // Create the address object if we don't already have one + ref(); + if (target.IsValid()) + *this = target.ResolveLoadAddress(load_addr); + else + m_opaque_up->Clear(); + + // Check if we weren't were able to resolve a section offset address. If we + // weren't it is ok, the load address might be a location on the stack or + // heap, so we should just have an address with no section and a valid offset + if (!m_opaque_up->IsValid()) + m_opaque_up->SetOffset(load_addr); +} + +bool SBAddress::OffsetAddress(addr_t offset) { + LLDB_INSTRUMENT_VA(this, offset); + + if (m_opaque_up->IsValid()) { + addr_t addr_offset = m_opaque_up->GetOffset(); + if (addr_offset != LLDB_INVALID_ADDRESS) { + m_opaque_up->SetOffset(addr_offset + offset); + return true; + } + } + return false; +} + +lldb::SBSection SBAddress::GetSection() { + LLDB_INSTRUMENT_VA(this); + + lldb::SBSection sb_section; + if (m_opaque_up->IsValid()) + sb_section.SetSP(m_opaque_up->GetSection()); + return sb_section; +} + +lldb::addr_t SBAddress::GetOffset() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up->IsValid()) + return m_opaque_up->GetOffset(); + return 0; +} + +Address *SBAddress::operator->() { return m_opaque_up.get(); } + +const Address *SBAddress::operator->() const { return m_opaque_up.get(); } + +Address &SBAddress::ref() { + if (m_opaque_up == nullptr) + m_opaque_up = std::make_unique<Address>(); + return *m_opaque_up; +} + +const Address &SBAddress::ref() const { + // This object should already have checked with "IsValid()" prior to calling + // this function. In case you didn't we will assert and die to let you know. + assert(m_opaque_up.get()); + return *m_opaque_up; +} + +Address *SBAddress::get() { return m_opaque_up.get(); } + +bool SBAddress::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + // Call "ref()" on the stream to make sure it creates a backing stream in + // case there isn't one already... + Stream &strm = description.ref(); + if (m_opaque_up->IsValid()) { + m_opaque_up->Dump(&strm, nullptr, Address::DumpStyleResolvedDescription, + Address::DumpStyleModuleWithFileAddress, 4); + } else + strm.PutCString("No value"); + + return true; +} + +SBModule SBAddress::GetModule() { + LLDB_INSTRUMENT_VA(this); + + SBModule sb_module; + if (m_opaque_up->IsValid()) + sb_module.SetSP(m_opaque_up->GetModule()); + return sb_module; +} + +SBSymbolContext SBAddress::GetSymbolContext(uint32_t resolve_scope) { + LLDB_INSTRUMENT_VA(this, resolve_scope); + + SBSymbolContext sb_sc; + SymbolContextItem scope = static_cast<SymbolContextItem>(resolve_scope); + if (m_opaque_up->IsValid()) + m_opaque_up->CalculateSymbolContext(&sb_sc.ref(), scope); + return sb_sc; +} + +SBCompileUnit SBAddress::GetCompileUnit() { + LLDB_INSTRUMENT_VA(this); + + SBCompileUnit sb_comp_unit; + if (m_opaque_up->IsValid()) + sb_comp_unit.reset(m_opaque_up->CalculateSymbolContextCompileUnit()); + return sb_comp_unit; +} + +SBFunction SBAddress::GetFunction() { + LLDB_INSTRUMENT_VA(this); + + SBFunction sb_function; + if (m_opaque_up->IsValid()) + sb_function.reset(m_opaque_up->CalculateSymbolContextFunction()); + return sb_function; +} + +SBBlock SBAddress::GetBlock() { + LLDB_INSTRUMENT_VA(this); + + SBBlock sb_block; + if (m_opaque_up->IsValid()) + sb_block.SetPtr(m_opaque_up->CalculateSymbolContextBlock()); + return sb_block; +} + +SBSymbol SBAddress::GetSymbol() { + LLDB_INSTRUMENT_VA(this); + + SBSymbol sb_symbol; + if (m_opaque_up->IsValid()) + sb_symbol.reset(m_opaque_up->CalculateSymbolContextSymbol()); + return sb_symbol; +} + +SBLineEntry SBAddress::GetLineEntry() { + LLDB_INSTRUMENT_VA(this); + + SBLineEntry sb_line_entry; + if (m_opaque_up->IsValid()) { + LineEntry line_entry; + if (m_opaque_up->CalculateSymbolContextLineEntry(line_entry)) + sb_line_entry.SetLineEntry(line_entry); + } + return sb_line_entry; +} diff --git a/contrib/llvm-project/lldb/source/API/SBAddressRange.cpp b/contrib/llvm-project/lldb/source/API/SBAddressRange.cpp new file mode 100644 index 000000000000..5834ebe5e63c --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBAddressRange.cpp @@ -0,0 +1,96 @@ +//===-- SBAddressRange.cpp ------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBAddressRange.h" +#include "Utils.h" +#include "lldb/API/SBAddress.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBTarget.h" +#include "lldb/Core/AddressRange.h" +#include "lldb/Core/Section.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Stream.h" +#include <cstddef> +#include <memory> + +using namespace lldb; +using namespace lldb_private; + +SBAddressRange::SBAddressRange() + : m_opaque_up(std::make_unique<AddressRange>()) { + LLDB_INSTRUMENT_VA(this); +} + +SBAddressRange::SBAddressRange(const SBAddressRange &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBAddressRange::SBAddressRange(lldb::SBAddress addr, lldb::addr_t byte_size) + : m_opaque_up(std::make_unique<AddressRange>(addr.ref(), byte_size)) { + LLDB_INSTRUMENT_VA(this, addr, byte_size); +} + +SBAddressRange::~SBAddressRange() = default; + +const SBAddressRange &SBAddressRange::operator=(const SBAddressRange &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +bool SBAddressRange::operator==(const SBAddressRange &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + return ref().operator==(rhs.ref()); +} + +bool SBAddressRange::operator!=(const SBAddressRange &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + return !(*this == rhs); +} + +void SBAddressRange::Clear() { + LLDB_INSTRUMENT_VA(this); + + ref().Clear(); +} + +bool SBAddressRange::IsValid() const { + LLDB_INSTRUMENT_VA(this); + + return ref().IsValid(); +} + +lldb::SBAddress SBAddressRange::GetBaseAddress() const { + LLDB_INSTRUMENT_VA(this); + + return lldb::SBAddress(ref().GetBaseAddress()); +} + +lldb::addr_t SBAddressRange::GetByteSize() const { + LLDB_INSTRUMENT_VA(this); + + return ref().GetByteSize(); +} + +bool SBAddressRange::GetDescription(SBStream &description, + const SBTarget target) { + LLDB_INSTRUMENT_VA(this, description, target); + + return ref().GetDescription(&description.ref(), target.GetSP().get()); +} + +lldb_private::AddressRange &SBAddressRange::ref() const { + assert(m_opaque_up && "opaque pointer must always be valid"); + return *m_opaque_up; +} diff --git a/contrib/llvm-project/lldb/source/API/SBAddressRangeList.cpp b/contrib/llvm-project/lldb/source/API/SBAddressRangeList.cpp new file mode 100644 index 000000000000..957155d5125e --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBAddressRangeList.cpp @@ -0,0 +1,99 @@ +//===-- SBAddressRangeList.cpp --------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBAddressRangeList.h" +#include "Utils.h" +#include "lldb/API/SBAddressRange.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBTarget.h" +#include "lldb/Core/AddressRangeListImpl.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Stream.h" + +#include <memory> + +using namespace lldb; +using namespace lldb_private; + +SBAddressRangeList::SBAddressRangeList() + : m_opaque_up(std::make_unique<AddressRangeListImpl>()) { + LLDB_INSTRUMENT_VA(this); +} + +SBAddressRangeList::SBAddressRangeList(const SBAddressRangeList &rhs) + : m_opaque_up(std::make_unique<AddressRangeListImpl>(*rhs.m_opaque_up)) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBAddressRangeList::~SBAddressRangeList() = default; + +const SBAddressRangeList & +SBAddressRangeList::operator=(const SBAddressRangeList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + ref() = rhs.ref(); + return *this; +} + +uint32_t SBAddressRangeList::GetSize() const { + LLDB_INSTRUMENT_VA(this); + + return ref().GetSize(); +} + +SBAddressRange SBAddressRangeList::GetAddressRangeAtIndex(uint64_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBAddressRange sb_addr_range; + (*sb_addr_range.m_opaque_up) = ref().GetAddressRangeAtIndex(idx); + return sb_addr_range; +} + +void SBAddressRangeList::Clear() { + LLDB_INSTRUMENT_VA(this); + + ref().Clear(); +} + +void SBAddressRangeList::Append(const SBAddressRange &sb_addr_range) { + LLDB_INSTRUMENT_VA(this, sb_addr_range); + + ref().Append(*sb_addr_range.m_opaque_up); +} + +void SBAddressRangeList::Append(const SBAddressRangeList &sb_addr_range_list) { + LLDB_INSTRUMENT_VA(this, sb_addr_range_list); + + ref().Append(*sb_addr_range_list.m_opaque_up); +} + +bool SBAddressRangeList::GetDescription(SBStream &description, + const SBTarget &target) { + LLDB_INSTRUMENT_VA(this, description, target); + + const uint32_t num_ranges = GetSize(); + bool is_first = true; + Stream &stream = description.ref(); + stream << "["; + for (uint32_t i = 0; i < num_ranges; ++i) { + if (is_first) { + is_first = false; + } else { + stream.Printf(", "); + } + GetAddressRangeAtIndex(i).GetDescription(description, target); + } + stream << "]"; + return true; +} + +lldb_private::AddressRangeListImpl &SBAddressRangeList::ref() const { + assert(m_opaque_up && "opaque pointer must always be valid"); + return *m_opaque_up; +} diff --git a/contrib/llvm-project/lldb/source/API/SBAttachInfo.cpp b/contrib/llvm-project/lldb/source/API/SBAttachInfo.cpp new file mode 100644 index 000000000000..a9f712c79c7f --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBAttachInfo.cpp @@ -0,0 +1,340 @@ +//===-- SBAttachInfo.cpp --------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBAttachInfo.h" +#include "Utils.h" +#include "lldb/API/SBFileSpec.h" +#include "lldb/API/SBListener.h" +#include "lldb/API/SBStructuredData.h" +#include "lldb/Target/Process.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/ScriptedMetadata.h" + +using namespace lldb; +using namespace lldb_private; + +SBAttachInfo::SBAttachInfo() : m_opaque_sp(new ProcessAttachInfo()) { + LLDB_INSTRUMENT_VA(this); +} + +SBAttachInfo::SBAttachInfo(lldb::pid_t pid) + : m_opaque_sp(new ProcessAttachInfo()) { + LLDB_INSTRUMENT_VA(this, pid); + + m_opaque_sp->SetProcessID(pid); +} + +SBAttachInfo::SBAttachInfo(const char *path, bool wait_for) + : m_opaque_sp(new ProcessAttachInfo()) { + LLDB_INSTRUMENT_VA(this, path, wait_for); + + if (path && path[0]) + m_opaque_sp->GetExecutableFile().SetFile(path, FileSpec::Style::native); + m_opaque_sp->SetWaitForLaunch(wait_for); +} + +SBAttachInfo::SBAttachInfo(const char *path, bool wait_for, bool async) + : m_opaque_sp(new ProcessAttachInfo()) { + LLDB_INSTRUMENT_VA(this, path, wait_for, async); + + if (path && path[0]) + m_opaque_sp->GetExecutableFile().SetFile(path, FileSpec::Style::native); + m_opaque_sp->SetWaitForLaunch(wait_for); + m_opaque_sp->SetAsync(async); +} + +SBAttachInfo::SBAttachInfo(const SBAttachInfo &rhs) + : m_opaque_sp(new ProcessAttachInfo()) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_sp = clone(rhs.m_opaque_sp); +} + +SBAttachInfo::~SBAttachInfo() = default; + +lldb_private::ProcessAttachInfo &SBAttachInfo::ref() { return *m_opaque_sp; } + +SBAttachInfo &SBAttachInfo::operator=(const SBAttachInfo &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_sp = clone(rhs.m_opaque_sp); + return *this; +} + +lldb::pid_t SBAttachInfo::GetProcessID() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetProcessID(); +} + +void SBAttachInfo::SetProcessID(lldb::pid_t pid) { + LLDB_INSTRUMENT_VA(this, pid); + + m_opaque_sp->SetProcessID(pid); +} + +uint32_t SBAttachInfo::GetResumeCount() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetResumeCount(); +} + +void SBAttachInfo::SetResumeCount(uint32_t c) { + LLDB_INSTRUMENT_VA(this, c); + + m_opaque_sp->SetResumeCount(c); +} + +const char *SBAttachInfo::GetProcessPluginName() { + LLDB_INSTRUMENT_VA(this); + + return ConstString(m_opaque_sp->GetProcessPluginName()).GetCString(); +} + +void SBAttachInfo::SetProcessPluginName(const char *plugin_name) { + LLDB_INSTRUMENT_VA(this, plugin_name); + + return m_opaque_sp->SetProcessPluginName(plugin_name); +} + +void SBAttachInfo::SetExecutable(const char *path) { + LLDB_INSTRUMENT_VA(this, path); + + if (path && path[0]) + m_opaque_sp->GetExecutableFile().SetFile(path, FileSpec::Style::native); + else + m_opaque_sp->GetExecutableFile().Clear(); +} + +void SBAttachInfo::SetExecutable(SBFileSpec exe_file) { + LLDB_INSTRUMENT_VA(this, exe_file); + + if (exe_file.IsValid()) + m_opaque_sp->GetExecutableFile() = exe_file.ref(); + else + m_opaque_sp->GetExecutableFile().Clear(); +} + +bool SBAttachInfo::GetWaitForLaunch() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetWaitForLaunch(); +} + +void SBAttachInfo::SetWaitForLaunch(bool b) { + LLDB_INSTRUMENT_VA(this, b); + + m_opaque_sp->SetWaitForLaunch(b); +} + +void SBAttachInfo::SetWaitForLaunch(bool b, bool async) { + LLDB_INSTRUMENT_VA(this, b, async); + + m_opaque_sp->SetWaitForLaunch(b); + m_opaque_sp->SetAsync(async); +} + +bool SBAttachInfo::GetIgnoreExisting() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetIgnoreExisting(); +} + +void SBAttachInfo::SetIgnoreExisting(bool b) { + LLDB_INSTRUMENT_VA(this, b); + + m_opaque_sp->SetIgnoreExisting(b); +} + +uint32_t SBAttachInfo::GetUserID() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetUserID(); +} + +uint32_t SBAttachInfo::GetGroupID() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetGroupID(); +} + +bool SBAttachInfo::UserIDIsValid() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->UserIDIsValid(); +} + +bool SBAttachInfo::GroupIDIsValid() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GroupIDIsValid(); +} + +void SBAttachInfo::SetUserID(uint32_t uid) { + LLDB_INSTRUMENT_VA(this, uid); + + m_opaque_sp->SetUserID(uid); +} + +void SBAttachInfo::SetGroupID(uint32_t gid) { + LLDB_INSTRUMENT_VA(this, gid); + + m_opaque_sp->SetGroupID(gid); +} + +uint32_t SBAttachInfo::GetEffectiveUserID() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetEffectiveUserID(); +} + +uint32_t SBAttachInfo::GetEffectiveGroupID() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetEffectiveGroupID(); +} + +bool SBAttachInfo::EffectiveUserIDIsValid() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->EffectiveUserIDIsValid(); +} + +bool SBAttachInfo::EffectiveGroupIDIsValid() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->EffectiveGroupIDIsValid(); +} + +void SBAttachInfo::SetEffectiveUserID(uint32_t uid) { + LLDB_INSTRUMENT_VA(this, uid); + + m_opaque_sp->SetEffectiveUserID(uid); +} + +void SBAttachInfo::SetEffectiveGroupID(uint32_t gid) { + LLDB_INSTRUMENT_VA(this, gid); + + m_opaque_sp->SetEffectiveGroupID(gid); +} + +lldb::pid_t SBAttachInfo::GetParentProcessID() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetParentProcessID(); +} + +void SBAttachInfo::SetParentProcessID(lldb::pid_t pid) { + LLDB_INSTRUMENT_VA(this, pid); + + m_opaque_sp->SetParentProcessID(pid); +} + +bool SBAttachInfo::ParentProcessIDIsValid() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->ParentProcessIDIsValid(); +} + +SBListener SBAttachInfo::GetListener() { + LLDB_INSTRUMENT_VA(this); + + return SBListener(m_opaque_sp->GetListener()); +} + +void SBAttachInfo::SetListener(SBListener &listener) { + LLDB_INSTRUMENT_VA(this, listener); + + m_opaque_sp->SetListener(listener.GetSP()); +} + +SBListener SBAttachInfo::GetShadowListener() { + LLDB_INSTRUMENT_VA(this); + + lldb::ListenerSP shadow_sp = m_opaque_sp->GetShadowListener(); + if (!shadow_sp) + return SBListener(); + return SBListener(shadow_sp); +} + +void SBAttachInfo::SetShadowListener(SBListener &listener) { + LLDB_INSTRUMENT_VA(this, listener); + + m_opaque_sp->SetShadowListener(listener.GetSP()); +} + +const char *SBAttachInfo::GetScriptedProcessClassName() const { + LLDB_INSTRUMENT_VA(this); + + ScriptedMetadataSP metadata_sp = m_opaque_sp->GetScriptedMetadata(); + + if (!metadata_sp || !*metadata_sp) + return nullptr; + + // Constify this string so that it is saved in the string pool. Otherwise it + // would be freed when this function goes out of scope. + ConstString class_name(metadata_sp->GetClassName().data()); + return class_name.AsCString(); +} + +void SBAttachInfo::SetScriptedProcessClassName(const char *class_name) { + LLDB_INSTRUMENT_VA(this, class_name); + + ScriptedMetadataSP metadata_sp = m_opaque_sp->GetScriptedMetadata(); + + if (!metadata_sp) + metadata_sp = std::make_shared<ScriptedMetadata>(class_name, nullptr); + else + metadata_sp = std::make_shared<ScriptedMetadata>(class_name, + metadata_sp->GetArgsSP()); + + m_opaque_sp->SetScriptedMetadata(metadata_sp); +} + +lldb::SBStructuredData SBAttachInfo::GetScriptedProcessDictionary() const { + LLDB_INSTRUMENT_VA(this); + + ScriptedMetadataSP metadata_sp = m_opaque_sp->GetScriptedMetadata(); + + SBStructuredData data; + if (!metadata_sp) + return data; + + lldb_private::StructuredData::DictionarySP dict_sp = metadata_sp->GetArgsSP(); + data.m_impl_up->SetObjectSP(dict_sp); + + return data; +} + +void SBAttachInfo::SetScriptedProcessDictionary(lldb::SBStructuredData dict) { + LLDB_INSTRUMENT_VA(this, dict); + + if (!dict.IsValid() || !dict.m_impl_up) + return; + + StructuredData::ObjectSP obj_sp = dict.m_impl_up->GetObjectSP(); + + if (!obj_sp) + return; + + StructuredData::DictionarySP dict_sp = + std::make_shared<StructuredData::Dictionary>(obj_sp); + if (!dict_sp || dict_sp->GetType() == lldb::eStructuredDataTypeInvalid) + return; + + ScriptedMetadataSP metadata_sp = m_opaque_sp->GetScriptedMetadata(); + + if (!metadata_sp) + metadata_sp = std::make_shared<ScriptedMetadata>("", dict_sp); + else + metadata_sp = std::make_shared<ScriptedMetadata>( + metadata_sp->GetClassName(), dict_sp); + + m_opaque_sp->SetScriptedMetadata(metadata_sp); +} diff --git a/contrib/llvm-project/lldb/source/API/SBBlock.cpp b/contrib/llvm-project/lldb/source/API/SBBlock.cpp new file mode 100644 index 000000000000..2577b14920f0 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBBlock.cpp @@ -0,0 +1,344 @@ +//===-- SBBlock.cpp -------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBBlock.h" +#include "lldb/API/SBAddress.h" +#include "lldb/API/SBFileSpec.h" +#include "lldb/API/SBFrame.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBValue.h" +#include "lldb/Core/AddressRange.h" +#include "lldb/Core/AddressRangeListImpl.h" +#include "lldb/Core/ValueObjectVariable.h" +#include "lldb/Symbol/Block.h" +#include "lldb/Symbol/Function.h" +#include "lldb/Symbol/SymbolContext.h" +#include "lldb/Symbol/VariableList.h" +#include "lldb/Target/StackFrame.h" +#include "lldb/Target/Target.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +SBBlock::SBBlock() { LLDB_INSTRUMENT_VA(this); } + +SBBlock::SBBlock(lldb_private::Block *lldb_object_ptr) + : m_opaque_ptr(lldb_object_ptr) {} + +SBBlock::SBBlock(const SBBlock &rhs) : m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const SBBlock &SBBlock::operator=(const SBBlock &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_ptr = rhs.m_opaque_ptr; + return *this; +} + +SBBlock::~SBBlock() { m_opaque_ptr = nullptr; } + +bool SBBlock::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBBlock::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_ptr != nullptr; +} + +bool SBBlock::IsInlined() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return m_opaque_ptr->GetInlinedFunctionInfo() != nullptr; + return false; +} + +const char *SBBlock::GetInlinedName() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) { + const InlineFunctionInfo *inlined_info = + m_opaque_ptr->GetInlinedFunctionInfo(); + if (inlined_info) { + return inlined_info->GetName().AsCString(nullptr); + } + } + return nullptr; +} + +SBFileSpec SBBlock::GetInlinedCallSiteFile() const { + LLDB_INSTRUMENT_VA(this); + + SBFileSpec sb_file; + if (m_opaque_ptr) { + const InlineFunctionInfo *inlined_info = + m_opaque_ptr->GetInlinedFunctionInfo(); + if (inlined_info) + sb_file.SetFileSpec(inlined_info->GetCallSite().GetFile()); + } + return sb_file; +} + +uint32_t SBBlock::GetInlinedCallSiteLine() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) { + const InlineFunctionInfo *inlined_info = + m_opaque_ptr->GetInlinedFunctionInfo(); + if (inlined_info) + return inlined_info->GetCallSite().GetLine(); + } + return 0; +} + +uint32_t SBBlock::GetInlinedCallSiteColumn() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) { + const InlineFunctionInfo *inlined_info = + m_opaque_ptr->GetInlinedFunctionInfo(); + if (inlined_info) + return inlined_info->GetCallSite().GetColumn(); + } + return 0; +} + +void SBBlock::AppendVariables(bool can_create, bool get_parent_variables, + lldb_private::VariableList *var_list) { + if (IsValid()) { + bool show_inline = true; + m_opaque_ptr->AppendVariables(can_create, get_parent_variables, show_inline, + [](Variable *) { return true; }, var_list); + } +} + +SBBlock SBBlock::GetParent() { + LLDB_INSTRUMENT_VA(this); + + SBBlock sb_block; + if (m_opaque_ptr) + sb_block.m_opaque_ptr = m_opaque_ptr->GetParent(); + return sb_block; +} + +lldb::SBBlock SBBlock::GetContainingInlinedBlock() { + LLDB_INSTRUMENT_VA(this); + + SBBlock sb_block; + if (m_opaque_ptr) + sb_block.m_opaque_ptr = m_opaque_ptr->GetContainingInlinedBlock(); + return sb_block; +} + +SBBlock SBBlock::GetSibling() { + LLDB_INSTRUMENT_VA(this); + + SBBlock sb_block; + if (m_opaque_ptr) + sb_block.m_opaque_ptr = m_opaque_ptr->GetSibling(); + return sb_block; +} + +SBBlock SBBlock::GetFirstChild() { + LLDB_INSTRUMENT_VA(this); + + SBBlock sb_block; + if (m_opaque_ptr) + sb_block.m_opaque_ptr = m_opaque_ptr->GetFirstChild(); + return sb_block; +} + +lldb_private::Block *SBBlock::GetPtr() { return m_opaque_ptr; } + +void SBBlock::SetPtr(lldb_private::Block *block) { m_opaque_ptr = block; } + +bool SBBlock::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + if (m_opaque_ptr) { + lldb::user_id_t id = m_opaque_ptr->GetID(); + strm.Printf("Block: {id: %" PRIu64 "} ", id); + if (IsInlined()) { + strm.Printf(" (inlined, '%s') ", GetInlinedName()); + } + lldb_private::SymbolContext sc; + m_opaque_ptr->CalculateSymbolContext(&sc); + if (sc.function) { + m_opaque_ptr->DumpAddressRanges( + &strm, + sc.function->GetAddressRange().GetBaseAddress().GetFileAddress()); + } + } else + strm.PutCString("No value"); + + return true; +} + +uint32_t SBBlock::GetNumRanges() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return m_opaque_ptr->GetNumRanges(); + return 0; +} + +lldb::SBAddress SBBlock::GetRangeStartAddress(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + lldb::SBAddress sb_addr; + if (m_opaque_ptr) { + AddressRange range; + if (m_opaque_ptr->GetRangeAtIndex(idx, range)) { + sb_addr.ref() = range.GetBaseAddress(); + } + } + return sb_addr; +} + +lldb::SBAddress SBBlock::GetRangeEndAddress(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + lldb::SBAddress sb_addr; + if (m_opaque_ptr) { + AddressRange range; + if (m_opaque_ptr->GetRangeAtIndex(idx, range)) { + sb_addr.ref() = range.GetBaseAddress(); + sb_addr.ref().Slide(range.GetByteSize()); + } + } + return sb_addr; +} + +lldb::SBAddressRangeList SBBlock::GetRanges() { + LLDB_INSTRUMENT_VA(this); + + lldb::SBAddressRangeList sb_ranges; + if (m_opaque_ptr) + sb_ranges.m_opaque_up->ref() = m_opaque_ptr->GetRanges(); + return sb_ranges; +} + +uint32_t SBBlock::GetRangeIndexForBlockAddress(lldb::SBAddress block_addr) { + LLDB_INSTRUMENT_VA(this, block_addr); + + if (m_opaque_ptr && block_addr.IsValid()) { + return m_opaque_ptr->GetRangeIndexContainingAddress(block_addr.ref()); + } + + return UINT32_MAX; +} + +lldb::SBValueList SBBlock::GetVariables(lldb::SBFrame &frame, bool arguments, + bool locals, bool statics, + lldb::DynamicValueType use_dynamic) { + LLDB_INSTRUMENT_VA(this, frame, arguments, locals, statics, use_dynamic); + + Block *block = GetPtr(); + SBValueList value_list; + if (block) { + StackFrameSP frame_sp(frame.GetFrameSP()); + VariableListSP variable_list_sp(block->GetBlockVariableList(true)); + + if (variable_list_sp) { + const size_t num_variables = variable_list_sp->GetSize(); + if (num_variables) { + for (size_t i = 0; i < num_variables; ++i) { + VariableSP variable_sp(variable_list_sp->GetVariableAtIndex(i)); + if (variable_sp) { + bool add_variable = false; + switch (variable_sp->GetScope()) { + case eValueTypeVariableGlobal: + case eValueTypeVariableStatic: + case eValueTypeVariableThreadLocal: + add_variable = statics; + break; + + case eValueTypeVariableArgument: + add_variable = arguments; + break; + + case eValueTypeVariableLocal: + add_variable = locals; + break; + + default: + break; + } + if (add_variable) { + if (frame_sp) { + lldb::ValueObjectSP valobj_sp( + frame_sp->GetValueObjectForFrameVariable(variable_sp, + eNoDynamicValues)); + SBValue value_sb; + value_sb.SetSP(valobj_sp, use_dynamic); + value_list.Append(value_sb); + } + } + } + } + } + } + } + return value_list; +} + +lldb::SBValueList SBBlock::GetVariables(lldb::SBTarget &target, bool arguments, + bool locals, bool statics) { + LLDB_INSTRUMENT_VA(this, target, arguments, locals, statics); + + Block *block = GetPtr(); + + SBValueList value_list; + if (block) { + TargetSP target_sp(target.GetSP()); + + VariableListSP variable_list_sp(block->GetBlockVariableList(true)); + + if (variable_list_sp) { + const size_t num_variables = variable_list_sp->GetSize(); + if (num_variables) { + for (size_t i = 0; i < num_variables; ++i) { + VariableSP variable_sp(variable_list_sp->GetVariableAtIndex(i)); + if (variable_sp) { + bool add_variable = false; + switch (variable_sp->GetScope()) { + case eValueTypeVariableGlobal: + case eValueTypeVariableStatic: + case eValueTypeVariableThreadLocal: + add_variable = statics; + break; + + case eValueTypeVariableArgument: + add_variable = arguments; + break; + + case eValueTypeVariableLocal: + add_variable = locals; + break; + + default: + break; + } + if (add_variable) { + if (target_sp) + value_list.Append( + ValueObjectVariable::Create(target_sp.get(), variable_sp)); + } + } + } + } + } + } + return value_list; +} diff --git a/contrib/llvm-project/lldb/source/API/SBBreakpoint.cpp b/contrib/llvm-project/lldb/source/API/SBBreakpoint.cpp new file mode 100644 index 000000000000..3d908047f945 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBBreakpoint.cpp @@ -0,0 +1,942 @@ +//===-- SBBreakpoint.cpp --------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBBreakpoint.h" +#include "lldb/API/SBBreakpointLocation.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStringList.h" +#include "lldb/API/SBStructuredData.h" +#include "lldb/API/SBThread.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/Breakpoint/Breakpoint.h" +#include "lldb/Breakpoint/BreakpointIDList.h" +#include "lldb/Breakpoint/BreakpointLocation.h" +#include "lldb/Breakpoint/BreakpointResolver.h" +#include "lldb/Breakpoint/BreakpointResolverScripted.h" +#include "lldb/Breakpoint/StoppointCallbackContext.h" +#include "lldb/Core/Address.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Core/StructuredDataImpl.h" +#include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Interpreter/ScriptInterpreter.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/SectionLoadList.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" +#include "lldb/Target/ThreadSpec.h" +#include "lldb/Utility/Stream.h" + +#include "SBBreakpointOptionCommon.h" + +#include "lldb/lldb-enumerations.h" + +#include "llvm/ADT/STLExtras.h" + +using namespace lldb; +using namespace lldb_private; + +SBBreakpoint::SBBreakpoint() { LLDB_INSTRUMENT_VA(this); } + +SBBreakpoint::SBBreakpoint(const SBBreakpoint &rhs) + : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBBreakpoint::SBBreakpoint(const lldb::BreakpointSP &bp_sp) + : m_opaque_wp(bp_sp) { + LLDB_INSTRUMENT_VA(this, bp_sp); +} + +SBBreakpoint::~SBBreakpoint() = default; + +const SBBreakpoint &SBBreakpoint::operator=(const SBBreakpoint &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_wp = rhs.m_opaque_wp; + return *this; +} + +bool SBBreakpoint::operator==(const lldb::SBBreakpoint &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_wp.lock() == rhs.m_opaque_wp.lock(); +} + +bool SBBreakpoint::operator!=(const lldb::SBBreakpoint &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_wp.lock() != rhs.m_opaque_wp.lock(); +} + +SBTarget SBBreakpoint::GetTarget() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) + return SBTarget(bkpt_sp->GetTargetSP()); + + return SBTarget(); +} + +break_id_t SBBreakpoint::GetID() const { + LLDB_INSTRUMENT_VA(this); + + break_id_t break_id = LLDB_INVALID_BREAK_ID; + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) + break_id = bkpt_sp->GetID(); + + return break_id; +} + +bool SBBreakpoint::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBBreakpoint::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointSP bkpt_sp = GetSP(); + if (!bkpt_sp) + return false; + else if (bkpt_sp->GetTarget().GetBreakpointByID(bkpt_sp->GetID())) + return true; + else + return false; +} + +void SBBreakpoint::ClearAllBreakpointSites() { + LLDB_INSTRUMENT_VA(this); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + bkpt_sp->ClearAllBreakpointSites(); + } +} + +SBBreakpointLocation SBBreakpoint::FindLocationByAddress(addr_t vm_addr) { + LLDB_INSTRUMENT_VA(this, vm_addr); + + SBBreakpointLocation sb_bp_location; + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + if (vm_addr != LLDB_INVALID_ADDRESS) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + Address address; + Target &target = bkpt_sp->GetTarget(); + if (!target.GetSectionLoadList().ResolveLoadAddress(vm_addr, address)) { + address.SetRawAddress(vm_addr); + } + sb_bp_location.SetLocation(bkpt_sp->FindLocationByAddress(address)); + } + } + return sb_bp_location; +} + +break_id_t SBBreakpoint::FindLocationIDByAddress(addr_t vm_addr) { + LLDB_INSTRUMENT_VA(this, vm_addr); + + break_id_t break_id = LLDB_INVALID_BREAK_ID; + BreakpointSP bkpt_sp = GetSP(); + + if (bkpt_sp && vm_addr != LLDB_INVALID_ADDRESS) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + Address address; + Target &target = bkpt_sp->GetTarget(); + if (!target.GetSectionLoadList().ResolveLoadAddress(vm_addr, address)) { + address.SetRawAddress(vm_addr); + } + break_id = bkpt_sp->FindLocationIDByAddress(address); + } + + return break_id; +} + +SBBreakpointLocation SBBreakpoint::FindLocationByID(break_id_t bp_loc_id) { + LLDB_INSTRUMENT_VA(this, bp_loc_id); + + SBBreakpointLocation sb_bp_location; + BreakpointSP bkpt_sp = GetSP(); + + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + sb_bp_location.SetLocation(bkpt_sp->FindLocationByID(bp_loc_id)); + } + + return sb_bp_location; +} + +SBBreakpointLocation SBBreakpoint::GetLocationAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + SBBreakpointLocation sb_bp_location; + BreakpointSP bkpt_sp = GetSP(); + + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + sb_bp_location.SetLocation(bkpt_sp->GetLocationAtIndex(index)); + } + + return sb_bp_location; +} + +void SBBreakpoint::SetEnabled(bool enable) { + LLDB_INSTRUMENT_VA(this, enable); + + BreakpointSP bkpt_sp = GetSP(); + + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + bkpt_sp->SetEnabled(enable); + } +} + +bool SBBreakpoint::IsEnabled() { + LLDB_INSTRUMENT_VA(this); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + return bkpt_sp->IsEnabled(); + } else + return false; +} + +void SBBreakpoint::SetOneShot(bool one_shot) { + LLDB_INSTRUMENT_VA(this, one_shot); + + BreakpointSP bkpt_sp = GetSP(); + + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + bkpt_sp->SetOneShot(one_shot); + } +} + +bool SBBreakpoint::IsOneShot() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + return bkpt_sp->IsOneShot(); + } else + return false; +} + +bool SBBreakpoint::IsInternal() { + LLDB_INSTRUMENT_VA(this); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + return bkpt_sp->IsInternal(); + } else + return false; +} + +void SBBreakpoint::SetIgnoreCount(uint32_t count) { + LLDB_INSTRUMENT_VA(this, count); + + BreakpointSP bkpt_sp = GetSP(); + + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + bkpt_sp->SetIgnoreCount(count); + } +} + +void SBBreakpoint::SetCondition(const char *condition) { + LLDB_INSTRUMENT_VA(this, condition); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + bkpt_sp->SetCondition(condition); + } +} + +const char *SBBreakpoint::GetCondition() { + LLDB_INSTRUMENT_VA(this); + + BreakpointSP bkpt_sp = GetSP(); + if (!bkpt_sp) + return nullptr; + + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + return ConstString(bkpt_sp->GetConditionText()).GetCString(); +} + +void SBBreakpoint::SetAutoContinue(bool auto_continue) { + LLDB_INSTRUMENT_VA(this, auto_continue); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + bkpt_sp->SetAutoContinue(auto_continue); + } +} + +bool SBBreakpoint::GetAutoContinue() { + LLDB_INSTRUMENT_VA(this); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + return bkpt_sp->IsAutoContinue(); + } + return false; +} + +uint32_t SBBreakpoint::GetHitCount() const { + LLDB_INSTRUMENT_VA(this); + + uint32_t count = 0; + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + count = bkpt_sp->GetHitCount(); + } + + return count; +} + +uint32_t SBBreakpoint::GetIgnoreCount() const { + LLDB_INSTRUMENT_VA(this); + + uint32_t count = 0; + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + count = bkpt_sp->GetIgnoreCount(); + } + + return count; +} + +void SBBreakpoint::SetThreadID(tid_t tid) { + LLDB_INSTRUMENT_VA(this, tid); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + bkpt_sp->SetThreadID(tid); + } +} + +tid_t SBBreakpoint::GetThreadID() { + LLDB_INSTRUMENT_VA(this); + + tid_t tid = LLDB_INVALID_THREAD_ID; + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + tid = bkpt_sp->GetThreadID(); + } + + return tid; +} + +void SBBreakpoint::SetThreadIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + bkpt_sp->GetOptions().GetThreadSpec()->SetIndex(index); + } +} + +uint32_t SBBreakpoint::GetThreadIndex() const { + LLDB_INSTRUMENT_VA(this); + + uint32_t thread_idx = UINT32_MAX; + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + const ThreadSpec *thread_spec = + bkpt_sp->GetOptions().GetThreadSpecNoCreate(); + if (thread_spec != nullptr) + thread_idx = thread_spec->GetIndex(); + } + + return thread_idx; +} + +void SBBreakpoint::SetThreadName(const char *thread_name) { + LLDB_INSTRUMENT_VA(this, thread_name); + + BreakpointSP bkpt_sp = GetSP(); + + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + bkpt_sp->GetOptions().GetThreadSpec()->SetName(thread_name); + } +} + +const char *SBBreakpoint::GetThreadName() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointSP bkpt_sp = GetSP(); + if (!bkpt_sp) + return nullptr; + + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + if (const ThreadSpec *thread_spec = + bkpt_sp->GetOptions().GetThreadSpecNoCreate()) + return ConstString(thread_spec->GetName()).GetCString(); + + return nullptr; +} + +void SBBreakpoint::SetQueueName(const char *queue_name) { + LLDB_INSTRUMENT_VA(this, queue_name); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + bkpt_sp->GetOptions().GetThreadSpec()->SetQueueName(queue_name); + } +} + +const char *SBBreakpoint::GetQueueName() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointSP bkpt_sp = GetSP(); + if (!bkpt_sp) + return nullptr; + + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + if (const ThreadSpec *thread_spec = + bkpt_sp->GetOptions().GetThreadSpecNoCreate()) + return ConstString(thread_spec->GetQueueName()).GetCString(); + + return nullptr; +} + +size_t SBBreakpoint::GetNumResolvedLocations() const { + LLDB_INSTRUMENT_VA(this); + + size_t num_resolved = 0; + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + num_resolved = bkpt_sp->GetNumResolvedLocations(); + } + return num_resolved; +} + +size_t SBBreakpoint::GetNumLocations() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointSP bkpt_sp = GetSP(); + size_t num_locs = 0; + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + num_locs = bkpt_sp->GetNumLocations(); + } + return num_locs; +} + +void SBBreakpoint::SetCommandLineCommands(SBStringList &commands) { + LLDB_INSTRUMENT_VA(this, commands); + + BreakpointSP bkpt_sp = GetSP(); + if (!bkpt_sp) + return; + if (commands.GetSize() == 0) + return; + + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + std::unique_ptr<BreakpointOptions::CommandData> cmd_data_up( + new BreakpointOptions::CommandData(*commands, eScriptLanguageNone)); + + bkpt_sp->GetOptions().SetCommandDataCallback(cmd_data_up); +} + +bool SBBreakpoint::GetCommandLineCommands(SBStringList &commands) { + LLDB_INSTRUMENT_VA(this, commands); + + BreakpointSP bkpt_sp = GetSP(); + if (!bkpt_sp) + return false; + StringList command_list; + bool has_commands = + bkpt_sp->GetOptions().GetCommandLineCallbacks(command_list); + if (has_commands) + commands.AppendList(command_list); + return has_commands; +} + +bool SBBreakpoint::GetDescription(SBStream &s) { + LLDB_INSTRUMENT_VA(this, s); + + return GetDescription(s, true); +} + +bool SBBreakpoint::GetDescription(SBStream &s, bool include_locations) { + LLDB_INSTRUMENT_VA(this, s, include_locations); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + s.Printf("SBBreakpoint: id = %i, ", bkpt_sp->GetID()); + bkpt_sp->GetResolverDescription(s.get()); + bkpt_sp->GetFilterDescription(s.get()); + if (include_locations) { + const size_t num_locations = bkpt_sp->GetNumLocations(); + s.Printf(", locations = %" PRIu64, (uint64_t)num_locations); + } + return true; + } + s.Printf("No value"); + return false; +} + +SBError SBBreakpoint::AddLocation(SBAddress &address) { + LLDB_INSTRUMENT_VA(this, address); + + BreakpointSP bkpt_sp = GetSP(); + SBError error; + + if (!address.IsValid()) { + error.SetErrorString("Can't add an invalid address."); + return error; + } + + if (!bkpt_sp) { + error.SetErrorString("No breakpoint to add a location to."); + return error; + } + + if (!llvm::isa<BreakpointResolverScripted>(bkpt_sp->GetResolver().get())) { + error.SetErrorString("Only a scripted resolver can add locations."); + return error; + } + + if (bkpt_sp->GetSearchFilter()->AddressPasses(address.ref())) + bkpt_sp->AddLocation(address.ref()); + else { + StreamString s; + address.get()->Dump(&s, &bkpt_sp->GetTarget(), + Address::DumpStyleModuleWithFileAddress); + error.SetErrorStringWithFormat("Address: %s didn't pass the filter.", + s.GetData()); + } + return error; +} + +SBStructuredData SBBreakpoint::SerializeToStructuredData() { + LLDB_INSTRUMENT_VA(this); + + SBStructuredData data; + BreakpointSP bkpt_sp = GetSP(); + + if (!bkpt_sp) + return data; + + StructuredData::ObjectSP bkpt_dict = bkpt_sp->SerializeToStructuredData(); + data.m_impl_up->SetObjectSP(bkpt_dict); + return data; +} + +void SBBreakpoint::SetCallback(SBBreakpointHitCallback callback, void *baton) { + LLDB_INSTRUMENT_VA(this, callback, baton); + + BreakpointSP bkpt_sp = GetSP(); + + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + BatonSP baton_sp(new SBBreakpointCallbackBaton(callback, baton)); + bkpt_sp->SetCallback(SBBreakpointCallbackBaton + ::PrivateBreakpointHitCallback, baton_sp, + false); + } +} + +void SBBreakpoint::SetScriptCallbackFunction( + const char *callback_function_name) { + LLDB_INSTRUMENT_VA(this, callback_function_name); + SBStructuredData empty_args; + SetScriptCallbackFunction(callback_function_name, empty_args); +} + +SBError SBBreakpoint::SetScriptCallbackFunction( + const char *callback_function_name, + SBStructuredData &extra_args) { + LLDB_INSTRUMENT_VA(this, callback_function_name, extra_args); + SBError sb_error; + BreakpointSP bkpt_sp = GetSP(); + + if (bkpt_sp) { + Status error; + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + BreakpointOptions &bp_options = bkpt_sp->GetOptions(); + error = bkpt_sp->GetTarget() + .GetDebugger() + .GetScriptInterpreter() + ->SetBreakpointCommandCallbackFunction(bp_options, + callback_function_name, + extra_args.m_impl_up + ->GetObjectSP()); + sb_error.SetError(error); + } else + sb_error.SetErrorString("invalid breakpoint"); + + return sb_error; +} + +SBError SBBreakpoint::SetScriptCallbackBody(const char *callback_body_text) { + LLDB_INSTRUMENT_VA(this, callback_body_text); + + BreakpointSP bkpt_sp = GetSP(); + + SBError sb_error; + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + BreakpointOptions &bp_options = bkpt_sp->GetOptions(); + Status error = + bkpt_sp->GetTarget() + .GetDebugger() + .GetScriptInterpreter() + ->SetBreakpointCommandCallback(bp_options, callback_body_text, + /*is_callback=*/false); + sb_error.SetError(error); + } else + sb_error.SetErrorString("invalid breakpoint"); + + return sb_error; +} + +bool SBBreakpoint::AddName(const char *new_name) { + LLDB_INSTRUMENT_VA(this, new_name); + + SBError status = AddNameWithErrorHandling(new_name); + return status.Success(); +} + +SBError SBBreakpoint::AddNameWithErrorHandling(const char *new_name) { + LLDB_INSTRUMENT_VA(this, new_name); + + BreakpointSP bkpt_sp = GetSP(); + + SBError status; + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + Status error; + bkpt_sp->GetTarget().AddNameToBreakpoint(bkpt_sp, new_name, error); + status.SetError(error); + } else { + status.SetErrorString("invalid breakpoint"); + } + + return status; +} + +void SBBreakpoint::RemoveName(const char *name_to_remove) { + LLDB_INSTRUMENT_VA(this, name_to_remove); + + BreakpointSP bkpt_sp = GetSP(); + + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + bkpt_sp->GetTarget().RemoveNameFromBreakpoint(bkpt_sp, + ConstString(name_to_remove)); + } +} + +bool SBBreakpoint::MatchesName(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + + BreakpointSP bkpt_sp = GetSP(); + + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + return bkpt_sp->MatchesName(name); + } + + return false; +} + +void SBBreakpoint::GetNames(SBStringList &names) { + LLDB_INSTRUMENT_VA(this, names); + + BreakpointSP bkpt_sp = GetSP(); + + if (bkpt_sp) { + std::lock_guard<std::recursive_mutex> guard( + bkpt_sp->GetTarget().GetAPIMutex()); + std::vector<std::string> names_vec; + bkpt_sp->GetNames(names_vec); + for (const std::string &name : names_vec) { + names.AppendString(name.c_str()); + } + } +} + +bool SBBreakpoint::EventIsBreakpointEvent(const lldb::SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return Breakpoint::BreakpointEventData::GetEventDataFromEvent(event.get()) != + nullptr; +} + +BreakpointEventType +SBBreakpoint::GetBreakpointEventTypeFromEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + if (event.IsValid()) + return Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent( + event.GetSP()); + return eBreakpointEventTypeInvalidType; +} + +SBBreakpoint SBBreakpoint::GetBreakpointFromEvent(const lldb::SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + if (event.IsValid()) + return SBBreakpoint( + Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event.GetSP())); + return SBBreakpoint(); +} + +SBBreakpointLocation +SBBreakpoint::GetBreakpointLocationAtIndexFromEvent(const lldb::SBEvent &event, + uint32_t loc_idx) { + LLDB_INSTRUMENT_VA(event, loc_idx); + + SBBreakpointLocation sb_breakpoint_loc; + if (event.IsValid()) + sb_breakpoint_loc.SetLocation( + Breakpoint::BreakpointEventData::GetBreakpointLocationAtIndexFromEvent( + event.GetSP(), loc_idx)); + return sb_breakpoint_loc; +} + +uint32_t +SBBreakpoint::GetNumBreakpointLocationsFromEvent(const lldb::SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + uint32_t num_locations = 0; + if (event.IsValid()) + num_locations = + (Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent( + event.GetSP())); + return num_locations; +} + +bool SBBreakpoint::IsHardware() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointSP bkpt_sp = GetSP(); + if (bkpt_sp) + return bkpt_sp->IsHardware(); + return false; +} + +BreakpointSP SBBreakpoint::GetSP() const { return m_opaque_wp.lock(); } + +// This is simple collection of breakpoint id's and their target. +class SBBreakpointListImpl { +public: + SBBreakpointListImpl(lldb::TargetSP target_sp) { + if (target_sp && target_sp->IsValid()) + m_target_wp = target_sp; + } + + ~SBBreakpointListImpl() = default; + + size_t GetSize() { return m_break_ids.size(); } + + BreakpointSP GetBreakpointAtIndex(size_t idx) { + if (idx >= m_break_ids.size()) + return BreakpointSP(); + TargetSP target_sp = m_target_wp.lock(); + if (!target_sp) + return BreakpointSP(); + lldb::break_id_t bp_id = m_break_ids[idx]; + return target_sp->GetBreakpointList().FindBreakpointByID(bp_id); + } + + BreakpointSP FindBreakpointByID(lldb::break_id_t desired_id) { + TargetSP target_sp = m_target_wp.lock(); + if (!target_sp) + return BreakpointSP(); + + for (lldb::break_id_t &break_id : m_break_ids) { + if (break_id == desired_id) + return target_sp->GetBreakpointList().FindBreakpointByID(break_id); + } + return BreakpointSP(); + } + + bool Append(BreakpointSP bkpt) { + TargetSP target_sp = m_target_wp.lock(); + if (!target_sp || !bkpt) + return false; + if (bkpt->GetTargetSP() != target_sp) + return false; + m_break_ids.push_back(bkpt->GetID()); + return true; + } + + bool AppendIfUnique(BreakpointSP bkpt) { + TargetSP target_sp = m_target_wp.lock(); + if (!target_sp || !bkpt) + return false; + if (bkpt->GetTargetSP() != target_sp) + return false; + lldb::break_id_t bp_id = bkpt->GetID(); + if (!llvm::is_contained(m_break_ids, bp_id)) + return false; + + m_break_ids.push_back(bkpt->GetID()); + return true; + } + + bool AppendByID(lldb::break_id_t id) { + TargetSP target_sp = m_target_wp.lock(); + if (!target_sp) + return false; + if (id == LLDB_INVALID_BREAK_ID) + return false; + m_break_ids.push_back(id); + return true; + } + + void Clear() { m_break_ids.clear(); } + + void CopyToBreakpointIDList(lldb_private::BreakpointIDList &bp_list) { + for (lldb::break_id_t id : m_break_ids) { + bp_list.AddBreakpointID(BreakpointID(id)); + } + } + + TargetSP GetTarget() { return m_target_wp.lock(); } + +private: + std::vector<lldb::break_id_t> m_break_ids; + TargetWP m_target_wp; +}; + +SBBreakpointList::SBBreakpointList(SBTarget &target) + : m_opaque_sp(new SBBreakpointListImpl(target.GetSP())) { + LLDB_INSTRUMENT_VA(this, target); +} + +SBBreakpointList::~SBBreakpointList() = default; + +size_t SBBreakpointList::GetSize() const { + LLDB_INSTRUMENT_VA(this); + + if (!m_opaque_sp) + return 0; + else + return m_opaque_sp->GetSize(); +} + +SBBreakpoint SBBreakpointList::GetBreakpointAtIndex(size_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + if (!m_opaque_sp) + return SBBreakpoint(); + + BreakpointSP bkpt_sp = m_opaque_sp->GetBreakpointAtIndex(idx); + return SBBreakpoint(bkpt_sp); +} + +SBBreakpoint SBBreakpointList::FindBreakpointByID(lldb::break_id_t id) { + LLDB_INSTRUMENT_VA(this, id); + + if (!m_opaque_sp) + return SBBreakpoint(); + BreakpointSP bkpt_sp = m_opaque_sp->FindBreakpointByID(id); + return SBBreakpoint(bkpt_sp); +} + +void SBBreakpointList::Append(const SBBreakpoint &sb_bkpt) { + LLDB_INSTRUMENT_VA(this, sb_bkpt); + + if (!sb_bkpt.IsValid()) + return; + if (!m_opaque_sp) + return; + m_opaque_sp->Append(sb_bkpt.m_opaque_wp.lock()); +} + +void SBBreakpointList::AppendByID(lldb::break_id_t id) { + LLDB_INSTRUMENT_VA(this, id); + + if (!m_opaque_sp) + return; + m_opaque_sp->AppendByID(id); +} + +bool SBBreakpointList::AppendIfUnique(const SBBreakpoint &sb_bkpt) { + LLDB_INSTRUMENT_VA(this, sb_bkpt); + + if (!sb_bkpt.IsValid()) + return false; + if (!m_opaque_sp) + return false; + return m_opaque_sp->AppendIfUnique(sb_bkpt.GetSP()); +} + +void SBBreakpointList::Clear() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + m_opaque_sp->Clear(); +} + +void SBBreakpointList::CopyToBreakpointIDList( + lldb_private::BreakpointIDList &bp_id_list) { + if (m_opaque_sp) + m_opaque_sp->CopyToBreakpointIDList(bp_id_list); +} diff --git a/contrib/llvm-project/lldb/source/API/SBBreakpointLocation.cpp b/contrib/llvm-project/lldb/source/API/SBBreakpointLocation.cpp new file mode 100644 index 000000000000..75b66364d4f1 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBBreakpointLocation.cpp @@ -0,0 +1,460 @@ +//===-- SBBreakpointLocation.cpp ------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBBreakpointLocation.h" +#include "lldb/API/SBAddress.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBDefines.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStringList.h" +#include "lldb/API/SBStructuredData.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/Breakpoint/Breakpoint.h" +#include "lldb/Breakpoint/BreakpointLocation.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Core/StructuredDataImpl.h" +#include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Interpreter/ScriptInterpreter.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/ThreadSpec.h" +#include "lldb/Utility/Stream.h" +#include "lldb/lldb-defines.h" +#include "lldb/lldb-types.h" + +#include "SBBreakpointOptionCommon.h" + +using namespace lldb; +using namespace lldb_private; + +SBBreakpointLocation::SBBreakpointLocation() { LLDB_INSTRUMENT_VA(this); } + +SBBreakpointLocation::SBBreakpointLocation( + const lldb::BreakpointLocationSP &break_loc_sp) + : m_opaque_wp(break_loc_sp) { + LLDB_INSTRUMENT_VA(this, break_loc_sp); +} + +SBBreakpointLocation::SBBreakpointLocation(const SBBreakpointLocation &rhs) + : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const SBBreakpointLocation &SBBreakpointLocation:: +operator=(const SBBreakpointLocation &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_wp = rhs.m_opaque_wp; + return *this; +} + +SBBreakpointLocation::~SBBreakpointLocation() = default; + +BreakpointLocationSP SBBreakpointLocation::GetSP() const { + return m_opaque_wp.lock(); +} + +bool SBBreakpointLocation::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBBreakpointLocation::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return bool(GetSP()); +} + +SBAddress SBBreakpointLocation::GetAddress() { + LLDB_INSTRUMENT_VA(this); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + return SBAddress(loc_sp->GetAddress()); + } + + return SBAddress(); +} + +addr_t SBBreakpointLocation::GetLoadAddress() { + LLDB_INSTRUMENT_VA(this); + + addr_t ret_addr = LLDB_INVALID_ADDRESS; + BreakpointLocationSP loc_sp = GetSP(); + + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + ret_addr = loc_sp->GetLoadAddress(); + } + + return ret_addr; +} + +void SBBreakpointLocation::SetEnabled(bool enabled) { + LLDB_INSTRUMENT_VA(this, enabled); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + loc_sp->SetEnabled(enabled); + } +} + +bool SBBreakpointLocation::IsEnabled() { + LLDB_INSTRUMENT_VA(this); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + return loc_sp->IsEnabled(); + } else + return false; +} + +uint32_t SBBreakpointLocation::GetHitCount() { + LLDB_INSTRUMENT_VA(this); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + return loc_sp->GetHitCount(); + } else + return 0; +} + +uint32_t SBBreakpointLocation::GetIgnoreCount() { + LLDB_INSTRUMENT_VA(this); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + return loc_sp->GetIgnoreCount(); + } else + return 0; +} + +void SBBreakpointLocation::SetIgnoreCount(uint32_t n) { + LLDB_INSTRUMENT_VA(this, n); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + loc_sp->SetIgnoreCount(n); + } +} + +void SBBreakpointLocation::SetCondition(const char *condition) { + LLDB_INSTRUMENT_VA(this, condition); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + loc_sp->SetCondition(condition); + } +} + +const char *SBBreakpointLocation::GetCondition() { + LLDB_INSTRUMENT_VA(this); + + BreakpointLocationSP loc_sp = GetSP(); + if (!loc_sp) + return nullptr; + + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + return ConstString(loc_sp->GetConditionText()).GetCString(); +} + +void SBBreakpointLocation::SetAutoContinue(bool auto_continue) { + LLDB_INSTRUMENT_VA(this, auto_continue); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + loc_sp->SetAutoContinue(auto_continue); + } +} + +bool SBBreakpointLocation::GetAutoContinue() { + LLDB_INSTRUMENT_VA(this); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + return loc_sp->IsAutoContinue(); + } + return false; +} + +void SBBreakpointLocation::SetCallback(SBBreakpointHitCallback callback, + void *baton) { + LLDB_INSTRUMENT_VA(this, callback, baton); + + BreakpointLocationSP loc_sp = GetSP(); + + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + BatonSP baton_sp(new SBBreakpointCallbackBaton(callback, baton)); + loc_sp->SetCallback(SBBreakpointCallbackBaton::PrivateBreakpointHitCallback, + baton_sp, false); + } +} + +void SBBreakpointLocation::SetScriptCallbackFunction( + const char *callback_function_name) { + LLDB_INSTRUMENT_VA(this, callback_function_name); +} + +SBError SBBreakpointLocation::SetScriptCallbackFunction( + const char *callback_function_name, + SBStructuredData &extra_args) { + LLDB_INSTRUMENT_VA(this, callback_function_name, extra_args); + SBError sb_error; + BreakpointLocationSP loc_sp = GetSP(); + + if (loc_sp) { + Status error; + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + BreakpointOptions &bp_options = loc_sp->GetLocationOptions(); + error = loc_sp->GetBreakpoint() + .GetTarget() + .GetDebugger() + .GetScriptInterpreter() + ->SetBreakpointCommandCallbackFunction(bp_options, + callback_function_name, + extra_args.m_impl_up + ->GetObjectSP()); + sb_error.SetError(error); + } else + sb_error.SetErrorString("invalid breakpoint"); + + return sb_error; +} + +SBError +SBBreakpointLocation::SetScriptCallbackBody(const char *callback_body_text) { + LLDB_INSTRUMENT_VA(this, callback_body_text); + + BreakpointLocationSP loc_sp = GetSP(); + + SBError sb_error; + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + BreakpointOptions &bp_options = loc_sp->GetLocationOptions(); + Status error = + loc_sp->GetBreakpoint() + .GetTarget() + .GetDebugger() + .GetScriptInterpreter() + ->SetBreakpointCommandCallback(bp_options, callback_body_text, + /*is_callback=*/false); + sb_error.SetError(error); + } else + sb_error.SetErrorString("invalid breakpoint"); + + return sb_error; +} + +void SBBreakpointLocation::SetCommandLineCommands(SBStringList &commands) { + LLDB_INSTRUMENT_VA(this, commands); + + BreakpointLocationSP loc_sp = GetSP(); + if (!loc_sp) + return; + if (commands.GetSize() == 0) + return; + + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + std::unique_ptr<BreakpointOptions::CommandData> cmd_data_up( + new BreakpointOptions::CommandData(*commands, eScriptLanguageNone)); + + loc_sp->GetLocationOptions().SetCommandDataCallback(cmd_data_up); +} + +bool SBBreakpointLocation::GetCommandLineCommands(SBStringList &commands) { + LLDB_INSTRUMENT_VA(this, commands); + + BreakpointLocationSP loc_sp = GetSP(); + if (!loc_sp) + return false; + StringList command_list; + bool has_commands = + loc_sp->GetLocationOptions().GetCommandLineCallbacks(command_list); + if (has_commands) + commands.AppendList(command_list); + return has_commands; +} + +void SBBreakpointLocation::SetThreadID(tid_t thread_id) { + LLDB_INSTRUMENT_VA(this, thread_id); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + loc_sp->SetThreadID(thread_id); + } +} + +tid_t SBBreakpointLocation::GetThreadID() { + LLDB_INSTRUMENT_VA(this); + + tid_t tid = LLDB_INVALID_THREAD_ID; + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + return loc_sp->GetThreadID(); + } + return tid; +} + +void SBBreakpointLocation::SetThreadIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + loc_sp->SetThreadIndex(index); + } +} + +uint32_t SBBreakpointLocation::GetThreadIndex() const { + LLDB_INSTRUMENT_VA(this); + + uint32_t thread_idx = UINT32_MAX; + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + return loc_sp->GetThreadIndex(); + } + return thread_idx; +} + +void SBBreakpointLocation::SetThreadName(const char *thread_name) { + LLDB_INSTRUMENT_VA(this, thread_name); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + loc_sp->SetThreadName(thread_name); + } +} + +const char *SBBreakpointLocation::GetThreadName() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointLocationSP loc_sp = GetSP(); + if (!loc_sp) + return nullptr; + + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + return ConstString(loc_sp->GetThreadName()).GetCString(); +} + +void SBBreakpointLocation::SetQueueName(const char *queue_name) { + LLDB_INSTRUMENT_VA(this, queue_name); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + loc_sp->SetQueueName(queue_name); + } +} + +const char *SBBreakpointLocation::GetQueueName() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointLocationSP loc_sp = GetSP(); + if (!loc_sp) + return nullptr; + + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + return ConstString(loc_sp->GetQueueName()).GetCString(); +} + +bool SBBreakpointLocation::IsResolved() { + LLDB_INSTRUMENT_VA(this); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + return loc_sp->IsResolved(); + } + return false; +} + +void SBBreakpointLocation::SetLocation( + const lldb::BreakpointLocationSP &break_loc_sp) { + // Uninstall the callbacks? + m_opaque_wp = break_loc_sp; +} + +bool SBBreakpointLocation::GetDescription(SBStream &description, + DescriptionLevel level) { + LLDB_INSTRUMENT_VA(this, description, level); + + Stream &strm = description.ref(); + BreakpointLocationSP loc_sp = GetSP(); + + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + loc_sp->GetDescription(&strm, level); + strm.EOL(); + } else + strm.PutCString("No value"); + + return true; +} + +break_id_t SBBreakpointLocation::GetID() { + LLDB_INSTRUMENT_VA(this); + + BreakpointLocationSP loc_sp = GetSP(); + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + return loc_sp->GetID(); + } else + return LLDB_INVALID_BREAK_ID; +} + +SBBreakpoint SBBreakpointLocation::GetBreakpoint() { + LLDB_INSTRUMENT_VA(this); + + BreakpointLocationSP loc_sp = GetSP(); + + SBBreakpoint sb_bp; + if (loc_sp) { + std::lock_guard<std::recursive_mutex> guard( + loc_sp->GetTarget().GetAPIMutex()); + sb_bp = loc_sp->GetBreakpoint().shared_from_this(); + } + + return sb_bp; +} diff --git a/contrib/llvm-project/lldb/source/API/SBBreakpointName.cpp b/contrib/llvm-project/lldb/source/API/SBBreakpointName.cpp new file mode 100644 index 000000000000..7f63aaf6fa7d --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBBreakpointName.cpp @@ -0,0 +1,669 @@ +//===-- SBBreakpointName.cpp ----------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBBreakpointName.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBError.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStringList.h" +#include "lldb/API/SBStructuredData.h" +#include "lldb/API/SBTarget.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/Breakpoint/BreakpointName.h" +#include "lldb/Breakpoint/StoppointCallbackContext.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Core/StructuredDataImpl.h" +#include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Interpreter/ScriptInterpreter.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/ThreadSpec.h" +#include "lldb/Utility/Stream.h" + +#include "SBBreakpointOptionCommon.h" + +using namespace lldb; +using namespace lldb_private; + +namespace lldb +{ +class SBBreakpointNameImpl { +public: + SBBreakpointNameImpl(TargetSP target_sp, const char *name) { + if (!name || name[0] == '\0') + return; + m_name.assign(name); + + if (!target_sp) + return; + + m_target_wp = target_sp; + } + + SBBreakpointNameImpl(SBTarget &sb_target, const char *name); + bool operator==(const SBBreakpointNameImpl &rhs); + bool operator!=(const SBBreakpointNameImpl &rhs); + + // For now we take a simple approach and only keep the name, and relook up + // the location when we need it. + + TargetSP GetTarget() const { + return m_target_wp.lock(); + } + + const char *GetName() const { + return m_name.c_str(); + } + + bool IsValid() const { + return !m_name.empty() && m_target_wp.lock(); + } + + lldb_private::BreakpointName *GetBreakpointName() const; + +private: + TargetWP m_target_wp; + std::string m_name; +}; + +SBBreakpointNameImpl::SBBreakpointNameImpl(SBTarget &sb_target, + const char *name) { + if (!name || name[0] == '\0') + return; + m_name.assign(name); + + if (!sb_target.IsValid()) + return; + + TargetSP target_sp = sb_target.GetSP(); + if (!target_sp) + return; + + m_target_wp = target_sp; +} + +bool SBBreakpointNameImpl::operator==(const SBBreakpointNameImpl &rhs) { + return m_name == rhs.m_name && m_target_wp.lock() == rhs.m_target_wp.lock(); +} + +bool SBBreakpointNameImpl::operator!=(const SBBreakpointNameImpl &rhs) { + return m_name != rhs.m_name || m_target_wp.lock() != rhs.m_target_wp.lock(); +} + +lldb_private::BreakpointName *SBBreakpointNameImpl::GetBreakpointName() const { + if (!IsValid()) + return nullptr; + TargetSP target_sp = GetTarget(); + if (!target_sp) + return nullptr; + Status error; + return target_sp->FindBreakpointName(ConstString(m_name), true, error); +} + +} // namespace lldb + +SBBreakpointName::SBBreakpointName() { LLDB_INSTRUMENT_VA(this); } + +SBBreakpointName::SBBreakpointName(SBTarget &sb_target, const char *name) { + LLDB_INSTRUMENT_VA(this, sb_target, name); + + m_impl_up = std::make_unique<SBBreakpointNameImpl>(sb_target, name); + // Call FindBreakpointName here to make sure the name is valid, reset if not: + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + m_impl_up.reset(); +} + +SBBreakpointName::SBBreakpointName(SBBreakpoint &sb_bkpt, const char *name) { + LLDB_INSTRUMENT_VA(this, sb_bkpt, name); + + if (!sb_bkpt.IsValid()) { + m_impl_up.reset(); + return; + } + BreakpointSP bkpt_sp = sb_bkpt.GetSP(); + Target &target = bkpt_sp->GetTarget(); + + m_impl_up = + std::make_unique<SBBreakpointNameImpl>(target.shared_from_this(), name); + + // Call FindBreakpointName here to make sure the name is valid, reset if not: + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) { + m_impl_up.reset(); + return; + } + + // Now copy over the breakpoint's options: + target.ConfigureBreakpointName(*bp_name, bkpt_sp->GetOptions(), + BreakpointName::Permissions()); +} + +SBBreakpointName::SBBreakpointName(const SBBreakpointName &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!rhs.m_impl_up) + return; + else + m_impl_up = std::make_unique<SBBreakpointNameImpl>( + rhs.m_impl_up->GetTarget(), rhs.m_impl_up->GetName()); +} + +SBBreakpointName::~SBBreakpointName() = default; + +const SBBreakpointName &SBBreakpointName:: +operator=(const SBBreakpointName &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!rhs.m_impl_up) { + m_impl_up.reset(); + return *this; + } + + m_impl_up = std::make_unique<SBBreakpointNameImpl>(rhs.m_impl_up->GetTarget(), + rhs.m_impl_up->GetName()); + return *this; +} + +bool SBBreakpointName::operator==(const lldb::SBBreakpointName &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + return *m_impl_up == *rhs.m_impl_up; +} + +bool SBBreakpointName::operator!=(const lldb::SBBreakpointName &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + return *m_impl_up != *rhs.m_impl_up; +} + +bool SBBreakpointName::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBBreakpointName::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + if (!m_impl_up) + return false; + return m_impl_up->IsValid(); +} + +const char *SBBreakpointName::GetName() const { + LLDB_INSTRUMENT_VA(this); + + if (!m_impl_up) + return "<Invalid Breakpoint Name Object>"; + return ConstString(m_impl_up->GetName()).GetCString(); +} + +void SBBreakpointName::SetEnabled(bool enable) { + LLDB_INSTRUMENT_VA(this, enable); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + bp_name->GetOptions().SetEnabled(enable); +} + +void SBBreakpointName::UpdateName(BreakpointName &bp_name) { + if (!IsValid()) + return; + + TargetSP target_sp = m_impl_up->GetTarget(); + if (!target_sp) + return; + target_sp->ApplyNameToBreakpoints(bp_name); + +} + +bool SBBreakpointName::IsEnabled() { + LLDB_INSTRUMENT_VA(this); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return false; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + return bp_name->GetOptions().IsEnabled(); +} + +void SBBreakpointName::SetOneShot(bool one_shot) { + LLDB_INSTRUMENT_VA(this, one_shot); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + bp_name->GetOptions().SetOneShot(one_shot); + UpdateName(*bp_name); +} + +bool SBBreakpointName::IsOneShot() const { + LLDB_INSTRUMENT_VA(this); + + const BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return false; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + return bp_name->GetOptions().IsOneShot(); +} + +void SBBreakpointName::SetIgnoreCount(uint32_t count) { + LLDB_INSTRUMENT_VA(this, count); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + bp_name->GetOptions().SetIgnoreCount(count); + UpdateName(*bp_name); +} + +uint32_t SBBreakpointName::GetIgnoreCount() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return false; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + return bp_name->GetOptions().GetIgnoreCount(); +} + +void SBBreakpointName::SetCondition(const char *condition) { + LLDB_INSTRUMENT_VA(this, condition); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + bp_name->GetOptions().SetCondition(condition); + UpdateName(*bp_name); +} + +const char *SBBreakpointName::GetCondition() { + LLDB_INSTRUMENT_VA(this); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return nullptr; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + return ConstString(bp_name->GetOptions().GetConditionText()).GetCString(); +} + +void SBBreakpointName::SetAutoContinue(bool auto_continue) { + LLDB_INSTRUMENT_VA(this, auto_continue); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + bp_name->GetOptions().SetAutoContinue(auto_continue); + UpdateName(*bp_name); +} + +bool SBBreakpointName::GetAutoContinue() { + LLDB_INSTRUMENT_VA(this); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return false; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + return bp_name->GetOptions().IsAutoContinue(); +} + +void SBBreakpointName::SetThreadID(tid_t tid) { + LLDB_INSTRUMENT_VA(this, tid); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + bp_name->GetOptions().SetThreadID(tid); + UpdateName(*bp_name); +} + +tid_t SBBreakpointName::GetThreadID() { + LLDB_INSTRUMENT_VA(this); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return LLDB_INVALID_THREAD_ID; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + return bp_name->GetOptions().GetThreadSpec()->GetTID(); +} + +void SBBreakpointName::SetThreadIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + bp_name->GetOptions().GetThreadSpec()->SetIndex(index); + UpdateName(*bp_name); +} + +uint32_t SBBreakpointName::GetThreadIndex() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return LLDB_INVALID_THREAD_ID; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + return bp_name->GetOptions().GetThreadSpec()->GetIndex(); +} + +void SBBreakpointName::SetThreadName(const char *thread_name) { + LLDB_INSTRUMENT_VA(this, thread_name); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + bp_name->GetOptions().GetThreadSpec()->SetName(thread_name); + UpdateName(*bp_name); +} + +const char *SBBreakpointName::GetThreadName() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return nullptr; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + return ConstString(bp_name->GetOptions().GetThreadSpec()->GetName()) + .GetCString(); +} + +void SBBreakpointName::SetQueueName(const char *queue_name) { + LLDB_INSTRUMENT_VA(this, queue_name); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + bp_name->GetOptions().GetThreadSpec()->SetQueueName(queue_name); + UpdateName(*bp_name); +} + +const char *SBBreakpointName::GetQueueName() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return nullptr; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + return ConstString(bp_name->GetOptions().GetThreadSpec()->GetQueueName()) + .GetCString(); +} + +void SBBreakpointName::SetCommandLineCommands(SBStringList &commands) { + LLDB_INSTRUMENT_VA(this, commands); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + if (commands.GetSize() == 0) + return; + + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + std::unique_ptr<BreakpointOptions::CommandData> cmd_data_up( + new BreakpointOptions::CommandData(*commands, eScriptLanguageNone)); + + bp_name->GetOptions().SetCommandDataCallback(cmd_data_up); + UpdateName(*bp_name); +} + +bool SBBreakpointName::GetCommandLineCommands(SBStringList &commands) { + LLDB_INSTRUMENT_VA(this, commands); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return false; + + StringList command_list; + bool has_commands = + bp_name->GetOptions().GetCommandLineCallbacks(command_list); + if (has_commands) + commands.AppendList(command_list); + return has_commands; +} + +const char *SBBreakpointName::GetHelpString() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return ""; + + return ConstString(bp_name->GetHelp()).GetCString(); +} + +void SBBreakpointName::SetHelpString(const char *help_string) { + LLDB_INSTRUMENT_VA(this, help_string); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + bp_name->SetHelp(help_string); +} + +bool SBBreakpointName::GetDescription(SBStream &s) { + LLDB_INSTRUMENT_VA(this, s); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + { + s.Printf("No value"); + return false; + } + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + bp_name->GetDescription(s.get(), eDescriptionLevelFull); + return true; +} + +void SBBreakpointName::SetCallback(SBBreakpointHitCallback callback, + void *baton) { + LLDB_INSTRUMENT_VA(this, callback, baton); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + BatonSP baton_sp(new SBBreakpointCallbackBaton(callback, baton)); + bp_name->GetOptions().SetCallback(SBBreakpointCallbackBaton + ::PrivateBreakpointHitCallback, + baton_sp, + false); + UpdateName(*bp_name); +} + +void SBBreakpointName::SetScriptCallbackFunction( + const char *callback_function_name) { + LLDB_INSTRUMENT_VA(this, callback_function_name); + SBStructuredData empty_args; + SetScriptCallbackFunction(callback_function_name, empty_args); +} + +SBError SBBreakpointName::SetScriptCallbackFunction( + const char *callback_function_name, + SBStructuredData &extra_args) { + LLDB_INSTRUMENT_VA(this, callback_function_name, extra_args); + SBError sb_error; + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) { + sb_error.SetErrorString("unrecognized breakpoint name"); + return sb_error; + } + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + BreakpointOptions &bp_options = bp_name->GetOptions(); + Status error; + error = m_impl_up->GetTarget() + ->GetDebugger() + .GetScriptInterpreter() + ->SetBreakpointCommandCallbackFunction( + bp_options, callback_function_name, + extra_args.m_impl_up->GetObjectSP()); + sb_error.SetError(error); + UpdateName(*bp_name); + return sb_error; +} + +SBError +SBBreakpointName::SetScriptCallbackBody(const char *callback_body_text) { + LLDB_INSTRUMENT_VA(this, callback_body_text); + + SBError sb_error; + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return sb_error; + + std::lock_guard<std::recursive_mutex> guard( + m_impl_up->GetTarget()->GetAPIMutex()); + + BreakpointOptions &bp_options = bp_name->GetOptions(); + Status error = m_impl_up->GetTarget() + ->GetDebugger() + .GetScriptInterpreter() + ->SetBreakpointCommandCallback( + bp_options, callback_body_text, /*is_callback=*/false); + sb_error.SetError(error); + if (!sb_error.Fail()) + UpdateName(*bp_name); + + return sb_error; +} + +bool SBBreakpointName::GetAllowList() const { + LLDB_INSTRUMENT_VA(this); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return false; + return bp_name->GetPermissions().GetAllowList(); +} + +void SBBreakpointName::SetAllowList(bool value) { + LLDB_INSTRUMENT_VA(this, value); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + bp_name->GetPermissions().SetAllowList(value); +} + +bool SBBreakpointName::GetAllowDelete() { + LLDB_INSTRUMENT_VA(this); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return false; + return bp_name->GetPermissions().GetAllowDelete(); +} + +void SBBreakpointName::SetAllowDelete(bool value) { + LLDB_INSTRUMENT_VA(this, value); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + bp_name->GetPermissions().SetAllowDelete(value); +} + +bool SBBreakpointName::GetAllowDisable() { + LLDB_INSTRUMENT_VA(this); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return false; + return bp_name->GetPermissions().GetAllowDisable(); +} + +void SBBreakpointName::SetAllowDisable(bool value) { + LLDB_INSTRUMENT_VA(this, value); + + BreakpointName *bp_name = GetBreakpointName(); + if (!bp_name) + return; + bp_name->GetPermissions().SetAllowDisable(value); +} + +lldb_private::BreakpointName *SBBreakpointName::GetBreakpointName() const +{ + if (!IsValid()) + return nullptr; + return m_impl_up->GetBreakpointName(); +} diff --git a/contrib/llvm-project/lldb/source/API/SBBreakpointOptionCommon.cpp b/contrib/llvm-project/lldb/source/API/SBBreakpointOptionCommon.cpp new file mode 100644 index 000000000000..1a14bce4cd24 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBBreakpointOptionCommon.cpp @@ -0,0 +1,79 @@ +//===-- SBBreakpointOptionCommon.cpp --------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBBreakpointName.h" +#include "lldb/API/SBBreakpointLocation.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStringList.h" +#include "lldb/API/SBThread.h" + +#include "lldb/Breakpoint/BreakpointName.h" +#include "lldb/Breakpoint/StoppointCallbackContext.h" +#include "lldb/Core/Address.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Interpreter/ScriptInterpreter.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" +#include "lldb/Target/ThreadSpec.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Log.h" +#include "lldb/Utility/Stream.h" + +#include "lldb/lldb-enumerations.h" + +#include "SBBreakpointOptionCommon.h" + +#include "llvm/ADT/STLExtras.h" + +using namespace lldb; +using namespace lldb_private; + +SBBreakpointCallbackBaton::SBBreakpointCallbackBaton( + SBBreakpointHitCallback callback, void *baton) + : TypedBaton(std::make_unique<CallbackData>()) { + LLDB_INSTRUMENT_VA(this, callback, baton); + getItem()->callback = callback; + getItem()->callback_baton = baton; +} + +bool SBBreakpointCallbackBaton::PrivateBreakpointHitCallback( + void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id, + lldb::user_id_t break_loc_id) { + LLDB_INSTRUMENT_VA(baton, ctx, break_id, break_loc_id); + ExecutionContext exe_ctx(ctx->exe_ctx_ref); + BreakpointSP bp_sp( + exe_ctx.GetTargetRef().GetBreakpointList().FindBreakpointByID(break_id)); + if (baton && bp_sp) { + CallbackData *data = (CallbackData *)baton; + lldb_private::Breakpoint *bp = bp_sp.get(); + if (bp && data->callback) { + Process *process = exe_ctx.GetProcessPtr(); + if (process) { + SBProcess sb_process(process->shared_from_this()); + SBThread sb_thread; + SBBreakpointLocation sb_location; + assert(bp_sp); + sb_location.SetLocation(bp_sp->FindLocationByID(break_loc_id)); + Thread *thread = exe_ctx.GetThreadPtr(); + if (thread) + sb_thread.SetThread(thread->shared_from_this()); + + return data->callback(data->callback_baton, sb_process, sb_thread, + sb_location); + } + } + } + return true; // Return true if we should stop at this breakpoint +} + +SBBreakpointCallbackBaton::~SBBreakpointCallbackBaton() = default; diff --git a/contrib/llvm-project/lldb/source/API/SBBreakpointOptionCommon.h b/contrib/llvm-project/lldb/source/API/SBBreakpointOptionCommon.h new file mode 100644 index 000000000000..3296e26698ff --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBBreakpointOptionCommon.h @@ -0,0 +1,36 @@ +//===-- SBBreakpointOptionCommon.h ------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLDB_SOURCE_API_SBBREAKPOINTOPTIONCOMMON_H +#define LLDB_SOURCE_API_SBBREAKPOINTOPTIONCOMMON_H + +#include "lldb/API/SBDefines.h" +#include "lldb/Utility/Baton.h" + +namespace lldb +{ +struct CallbackData { + SBBreakpointHitCallback callback; + void *callback_baton; +}; + +class SBBreakpointCallbackBaton : public lldb_private::TypedBaton<CallbackData> { +public: + SBBreakpointCallbackBaton(SBBreakpointHitCallback callback, + void *baton); + + ~SBBreakpointCallbackBaton() override; + + static bool PrivateBreakpointHitCallback(void *baton, + lldb_private::StoppointCallbackContext *ctx, + lldb::user_id_t break_id, + lldb::user_id_t break_loc_id); +}; + +} // namespace lldb +#endif // LLDB_SOURCE_API_SBBREAKPOINTOPTIONCOMMON_H diff --git a/contrib/llvm-project/lldb/source/API/SBBroadcaster.cpp b/contrib/llvm-project/lldb/source/API/SBBroadcaster.cpp new file mode 100644 index 000000000000..6e34b2f71b82 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBBroadcaster.cpp @@ -0,0 +1,159 @@ +//===-- SBBroadcaster.cpp -------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/Utility/Broadcaster.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBBroadcaster.h" +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBListener.h" + +using namespace lldb; +using namespace lldb_private; + +SBBroadcaster::SBBroadcaster() { LLDB_INSTRUMENT_VA(this); } + +SBBroadcaster::SBBroadcaster(const char *name) + : m_opaque_sp(new Broadcaster(nullptr, name)) { + LLDB_INSTRUMENT_VA(this, name); + + m_opaque_ptr = m_opaque_sp.get(); +} + +SBBroadcaster::SBBroadcaster(lldb_private::Broadcaster *broadcaster, bool owns) + : m_opaque_sp(owns ? broadcaster : nullptr), m_opaque_ptr(broadcaster) {} + +SBBroadcaster::SBBroadcaster(const SBBroadcaster &rhs) + : m_opaque_sp(rhs.m_opaque_sp), m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const SBBroadcaster &SBBroadcaster::operator=(const SBBroadcaster &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + m_opaque_ptr = rhs.m_opaque_ptr; + } + return *this; +} + +SBBroadcaster::~SBBroadcaster() { reset(nullptr, false); } + +void SBBroadcaster::BroadcastEventByType(uint32_t event_type, bool unique) { + LLDB_INSTRUMENT_VA(this, event_type, unique); + + if (m_opaque_ptr == nullptr) + return; + + if (unique) + m_opaque_ptr->BroadcastEventIfUnique(event_type); + else + m_opaque_ptr->BroadcastEvent(event_type); +} + +void SBBroadcaster::BroadcastEvent(const SBEvent &event, bool unique) { + LLDB_INSTRUMENT_VA(this, event, unique); + + if (m_opaque_ptr == nullptr) + return; + + EventSP event_sp = event.GetSP(); + if (unique) + m_opaque_ptr->BroadcastEventIfUnique(event_sp); + else + m_opaque_ptr->BroadcastEvent(event_sp); +} + +void SBBroadcaster::AddInitialEventsToListener(const SBListener &listener, + uint32_t requested_events) { + LLDB_INSTRUMENT_VA(this, listener, requested_events); + + if (m_opaque_ptr) + m_opaque_ptr->AddInitialEventsToListener(listener.m_opaque_sp, + requested_events); +} + +uint32_t SBBroadcaster::AddListener(const SBListener &listener, + uint32_t event_mask) { + LLDB_INSTRUMENT_VA(this, listener, event_mask); + + if (m_opaque_ptr) + return m_opaque_ptr->AddListener(listener.m_opaque_sp, event_mask); + return 0; +} + +const char *SBBroadcaster::GetName() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return ConstString(m_opaque_ptr->GetBroadcasterName()).GetCString(); + return nullptr; +} + +bool SBBroadcaster::EventTypeHasListeners(uint32_t event_type) { + LLDB_INSTRUMENT_VA(this, event_type); + + if (m_opaque_ptr) + return m_opaque_ptr->EventTypeHasListeners(event_type); + return false; +} + +bool SBBroadcaster::RemoveListener(const SBListener &listener, + uint32_t event_mask) { + LLDB_INSTRUMENT_VA(this, listener, event_mask); + + if (m_opaque_ptr) + return m_opaque_ptr->RemoveListener(listener.m_opaque_sp, event_mask); + return false; +} + +Broadcaster *SBBroadcaster::get() const { return m_opaque_ptr; } + +void SBBroadcaster::reset(Broadcaster *broadcaster, bool owns) { + if (owns) + m_opaque_sp.reset(broadcaster); + else + m_opaque_sp.reset(); + m_opaque_ptr = broadcaster; +} + +bool SBBroadcaster::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBBroadcaster::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_ptr != nullptr; +} + +void SBBroadcaster::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_sp.reset(); + m_opaque_ptr = nullptr; +} + +bool SBBroadcaster::operator==(const SBBroadcaster &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_ptr == rhs.m_opaque_ptr; +} + +bool SBBroadcaster::operator!=(const SBBroadcaster &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_ptr != rhs.m_opaque_ptr; +} + +bool SBBroadcaster::operator<(const SBBroadcaster &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_ptr < rhs.m_opaque_ptr; +} diff --git a/contrib/llvm-project/lldb/source/API/SBCommandInterpreter.cpp b/contrib/llvm-project/lldb/source/API/SBCommandInterpreter.cpp new file mode 100644 index 000000000000..7a3547328368 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBCommandInterpreter.cpp @@ -0,0 +1,745 @@ +//===-- SBCommandInterpreter.cpp ------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/Utility/StructuredData.h" +#include "lldb/lldb-types.h" + +#include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Interpreter/CommandObjectMultiword.h" +#include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/Target/Target.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Listener.h" + +#include "lldb/API/SBBroadcaster.h" +#include "lldb/API/SBCommandInterpreter.h" +#include "lldb/API/SBCommandInterpreterRunOptions.h" +#include "lldb/API/SBCommandReturnObject.h" +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBExecutionContext.h" +#include "lldb/API/SBListener.h" +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStringList.h" +#include "lldb/API/SBTarget.h" + +#include <memory> +#include <optional> + +using namespace lldb; +using namespace lldb_private; + +namespace lldb_private { +class CommandPluginInterfaceImplementation : public CommandObjectParsed { +public: + CommandPluginInterfaceImplementation(CommandInterpreter &interpreter, + const char *name, + lldb::SBCommandPluginInterface *backend, + const char *help = nullptr, + const char *syntax = nullptr, + uint32_t flags = 0, + const char *auto_repeat_command = "") + : CommandObjectParsed(interpreter, name, help, syntax, flags), + m_backend(backend) { + m_auto_repeat_command = + auto_repeat_command == nullptr + ? std::nullopt + : std::optional<std::string>(auto_repeat_command); + // We don't know whether any given command coming from this interface takes + // arguments or not so here we're just disabling the basic args check. + CommandArgumentData none_arg{eArgTypeNone, eArgRepeatStar}; + m_arguments.push_back({none_arg}); + } + + bool IsRemovable() const override { return true; } + + /// More documentation is available in lldb::CommandObject::GetRepeatCommand, + /// but in short, if std::nullopt is returned, the previous command will be + /// repeated, and if an empty string is returned, no commands will be + /// executed. + std::optional<std::string> GetRepeatCommand(Args ¤t_command_args, + uint32_t index) override { + if (!m_auto_repeat_command) + return std::nullopt; + else + return m_auto_repeat_command; + } + +protected: + void DoExecute(Args &command, CommandReturnObject &result) override { + SBCommandReturnObject sb_return(result); + SBCommandInterpreter sb_interpreter(&m_interpreter); + SBDebugger debugger_sb(m_interpreter.GetDebugger().shared_from_this()); + m_backend->DoExecute(debugger_sb, command.GetArgumentVector(), sb_return); + } + std::shared_ptr<lldb::SBCommandPluginInterface> m_backend; + std::optional<std::string> m_auto_repeat_command; +}; +} // namespace lldb_private + +SBCommandInterpreter::SBCommandInterpreter() : m_opaque_ptr() { + LLDB_INSTRUMENT_VA(this); +} + +SBCommandInterpreter::SBCommandInterpreter(CommandInterpreter *interpreter) + : m_opaque_ptr(interpreter) { + LLDB_INSTRUMENT_VA(this, interpreter); +} + +SBCommandInterpreter::SBCommandInterpreter(const SBCommandInterpreter &rhs) + : m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBCommandInterpreter::~SBCommandInterpreter() = default; + +const SBCommandInterpreter &SBCommandInterpreter:: +operator=(const SBCommandInterpreter &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_ptr = rhs.m_opaque_ptr; + return *this; +} + +bool SBCommandInterpreter::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBCommandInterpreter::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_ptr != nullptr; +} + +bool SBCommandInterpreter::CommandExists(const char *cmd) { + LLDB_INSTRUMENT_VA(this, cmd); + + return (((cmd != nullptr) && IsValid()) ? m_opaque_ptr->CommandExists(cmd) + : false); +} + +bool SBCommandInterpreter::UserCommandExists(const char *cmd) { + LLDB_INSTRUMENT_VA(this, cmd); + + return (((cmd != nullptr) && IsValid()) ? m_opaque_ptr->UserCommandExists(cmd) + : false); +} + +bool SBCommandInterpreter::AliasExists(const char *cmd) { + LLDB_INSTRUMENT_VA(this, cmd); + + return (((cmd != nullptr) && IsValid()) ? m_opaque_ptr->AliasExists(cmd) + : false); +} + +bool SBCommandInterpreter::IsActive() { + LLDB_INSTRUMENT_VA(this); + + return (IsValid() ? m_opaque_ptr->IsActive() : false); +} + +bool SBCommandInterpreter::WasInterrupted() const { + LLDB_INSTRUMENT_VA(this); + + return (IsValid() ? m_opaque_ptr->GetDebugger().InterruptRequested() : false); +} + +bool SBCommandInterpreter::InterruptCommand() { + LLDB_INSTRUMENT_VA(this); + + return (IsValid() ? m_opaque_ptr->InterruptCommand() : false); +} + +const char *SBCommandInterpreter::GetIOHandlerControlSequence(char ch) { + LLDB_INSTRUMENT_VA(this, ch); + + if (!IsValid()) + return nullptr; + + return ConstString( + m_opaque_ptr->GetDebugger().GetTopIOHandlerControlSequence(ch)) + .GetCString(); +} + +lldb::ReturnStatus +SBCommandInterpreter::HandleCommand(const char *command_line, + SBCommandReturnObject &result, + bool add_to_history) { + LLDB_INSTRUMENT_VA(this, command_line, result, add_to_history); + + SBExecutionContext sb_exe_ctx; + return HandleCommand(command_line, sb_exe_ctx, result, add_to_history); +} + +lldb::ReturnStatus SBCommandInterpreter::HandleCommand( + const char *command_line, SBExecutionContext &override_context, + SBCommandReturnObject &result, bool add_to_history) { + LLDB_INSTRUMENT_VA(this, command_line, override_context, result, + add_to_history); + + result.Clear(); + if (command_line && IsValid()) { + result.ref().SetInteractive(false); + auto do_add_to_history = add_to_history ? eLazyBoolYes : eLazyBoolNo; + if (override_context.get()) + m_opaque_ptr->HandleCommand(command_line, do_add_to_history, + override_context.get()->Lock(true), + result.ref()); + else + m_opaque_ptr->HandleCommand(command_line, do_add_to_history, + result.ref()); + } else { + result->AppendError( + "SBCommandInterpreter or the command line is not valid"); + } + + return result.GetStatus(); +} + +void SBCommandInterpreter::HandleCommandsFromFile( + lldb::SBFileSpec &file, lldb::SBExecutionContext &override_context, + lldb::SBCommandInterpreterRunOptions &options, + lldb::SBCommandReturnObject result) { + LLDB_INSTRUMENT_VA(this, file, override_context, options, result); + + if (!IsValid()) { + result->AppendError("SBCommandInterpreter is not valid."); + return; + } + + if (!file.IsValid()) { + SBStream s; + file.GetDescription(s); + result->AppendErrorWithFormat("File is not valid: %s.", s.GetData()); + } + + FileSpec tmp_spec = file.ref(); + if (override_context.get()) + m_opaque_ptr->HandleCommandsFromFile(tmp_spec, + override_context.get()->Lock(true), + options.ref(), + result.ref()); + + else + m_opaque_ptr->HandleCommandsFromFile(tmp_spec, options.ref(), result.ref()); +} + +int SBCommandInterpreter::HandleCompletion( + const char *current_line, const char *cursor, const char *last_char, + int match_start_point, int max_return_elements, SBStringList &matches) { + LLDB_INSTRUMENT_VA(this, current_line, cursor, last_char, match_start_point, + max_return_elements, matches); + + SBStringList dummy_descriptions; + return HandleCompletionWithDescriptions( + current_line, cursor, last_char, match_start_point, max_return_elements, + matches, dummy_descriptions); +} + +int SBCommandInterpreter::HandleCompletionWithDescriptions( + const char *current_line, const char *cursor, const char *last_char, + int match_start_point, int max_return_elements, SBStringList &matches, + SBStringList &descriptions) { + LLDB_INSTRUMENT_VA(this, current_line, cursor, last_char, match_start_point, + max_return_elements, matches, descriptions); + + // Sanity check the arguments that are passed in: cursor & last_char have to + // be within the current_line. + if (current_line == nullptr || cursor == nullptr || last_char == nullptr) + return 0; + + if (cursor < current_line || last_char < current_line) + return 0; + + size_t current_line_size = strlen(current_line); + if (cursor - current_line > static_cast<ptrdiff_t>(current_line_size) || + last_char - current_line > static_cast<ptrdiff_t>(current_line_size)) + return 0; + + if (!IsValid()) + return 0; + + lldb_private::StringList lldb_matches, lldb_descriptions; + CompletionResult result; + CompletionRequest request(current_line, cursor - current_line, result); + m_opaque_ptr->HandleCompletion(request); + result.GetMatches(lldb_matches); + result.GetDescriptions(lldb_descriptions); + + // Make the result array indexed from 1 again by adding the 'common prefix' + // of all completions as element 0. This is done to emulate the old API. + if (request.GetParsedLine().GetArgumentCount() == 0) { + // If we got an empty string, insert nothing. + lldb_matches.InsertStringAtIndex(0, ""); + lldb_descriptions.InsertStringAtIndex(0, ""); + } else { + // Now figure out if there is a common substring, and if so put that in + // element 0, otherwise put an empty string in element 0. + std::string command_partial_str = request.GetCursorArgumentPrefix().str(); + + std::string common_prefix = lldb_matches.LongestCommonPrefix(); + const size_t partial_name_len = command_partial_str.size(); + common_prefix.erase(0, partial_name_len); + + // If we matched a unique single command, add a space... Only do this if + // the completer told us this was a complete word, however... + if (lldb_matches.GetSize() == 1) { + char quote_char = request.GetParsedArg().GetQuoteChar(); + common_prefix = + Args::EscapeLLDBCommandArgument(common_prefix, quote_char); + if (request.GetParsedArg().IsQuoted()) + common_prefix.push_back(quote_char); + common_prefix.push_back(' '); + } + lldb_matches.InsertStringAtIndex(0, common_prefix.c_str()); + lldb_descriptions.InsertStringAtIndex(0, ""); + } + + SBStringList temp_matches_list(&lldb_matches); + matches.AppendList(temp_matches_list); + SBStringList temp_descriptions_list(&lldb_descriptions); + descriptions.AppendList(temp_descriptions_list); + return result.GetNumberOfResults(); +} + +int SBCommandInterpreter::HandleCompletionWithDescriptions( + const char *current_line, uint32_t cursor_pos, int match_start_point, + int max_return_elements, SBStringList &matches, + SBStringList &descriptions) { + LLDB_INSTRUMENT_VA(this, current_line, cursor_pos, match_start_point, + max_return_elements, matches, descriptions); + + const char *cursor = current_line + cursor_pos; + const char *last_char = current_line + strlen(current_line); + return HandleCompletionWithDescriptions( + current_line, cursor, last_char, match_start_point, max_return_elements, + matches, descriptions); +} + +int SBCommandInterpreter::HandleCompletion(const char *current_line, + uint32_t cursor_pos, + int match_start_point, + int max_return_elements, + lldb::SBStringList &matches) { + LLDB_INSTRUMENT_VA(this, current_line, cursor_pos, match_start_point, + max_return_elements, matches); + + const char *cursor = current_line + cursor_pos; + const char *last_char = current_line + strlen(current_line); + return HandleCompletion(current_line, cursor, last_char, match_start_point, + max_return_elements, matches); +} + +bool SBCommandInterpreter::HasCommands() { + LLDB_INSTRUMENT_VA(this); + + return (IsValid() ? m_opaque_ptr->HasCommands() : false); +} + +bool SBCommandInterpreter::HasAliases() { + LLDB_INSTRUMENT_VA(this); + + return (IsValid() ? m_opaque_ptr->HasAliases() : false); +} + +bool SBCommandInterpreter::HasAliasOptions() { + LLDB_INSTRUMENT_VA(this); + + return (IsValid() ? m_opaque_ptr->HasAliasOptions() : false); +} + +bool SBCommandInterpreter::IsInteractive() { + LLDB_INSTRUMENT_VA(this); + + return (IsValid() ? m_opaque_ptr->IsInteractive() : false); +} + +SBProcess SBCommandInterpreter::GetProcess() { + LLDB_INSTRUMENT_VA(this); + + SBProcess sb_process; + ProcessSP process_sp; + if (IsValid()) { + TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + process_sp = target_sp->GetProcessSP(); + sb_process.SetSP(process_sp); + } + } + + return sb_process; +} + +SBDebugger SBCommandInterpreter::GetDebugger() { + LLDB_INSTRUMENT_VA(this); + + SBDebugger sb_debugger; + if (IsValid()) + sb_debugger.reset(m_opaque_ptr->GetDebugger().shared_from_this()); + + return sb_debugger; +} + +bool SBCommandInterpreter::GetPromptOnQuit() { + LLDB_INSTRUMENT_VA(this); + + return (IsValid() ? m_opaque_ptr->GetPromptOnQuit() : false); +} + +void SBCommandInterpreter::SetPromptOnQuit(bool b) { + LLDB_INSTRUMENT_VA(this, b); + + if (IsValid()) + m_opaque_ptr->SetPromptOnQuit(b); +} + +void SBCommandInterpreter::AllowExitCodeOnQuit(bool allow) { + LLDB_INSTRUMENT_VA(this, allow); + + if (m_opaque_ptr) + m_opaque_ptr->AllowExitCodeOnQuit(allow); +} + +bool SBCommandInterpreter::HasCustomQuitExitCode() { + LLDB_INSTRUMENT_VA(this); + + bool exited = false; + if (m_opaque_ptr) + m_opaque_ptr->GetQuitExitCode(exited); + return exited; +} + +int SBCommandInterpreter::GetQuitStatus() { + LLDB_INSTRUMENT_VA(this); + + bool exited = false; + return (m_opaque_ptr ? m_opaque_ptr->GetQuitExitCode(exited) : 0); +} + +void SBCommandInterpreter::ResolveCommand(const char *command_line, + SBCommandReturnObject &result) { + LLDB_INSTRUMENT_VA(this, command_line, result); + + result.Clear(); + if (command_line && IsValid()) { + m_opaque_ptr->ResolveCommand(command_line, result.ref()); + } else { + result->AppendError( + "SBCommandInterpreter or the command line is not valid"); + } +} + +CommandInterpreter *SBCommandInterpreter::get() { return m_opaque_ptr; } + +CommandInterpreter &SBCommandInterpreter::ref() { + assert(m_opaque_ptr); + return *m_opaque_ptr; +} + +void SBCommandInterpreter::reset( + lldb_private::CommandInterpreter *interpreter) { + m_opaque_ptr = interpreter; +} + +void SBCommandInterpreter::SourceInitFileInGlobalDirectory( + SBCommandReturnObject &result) { + LLDB_INSTRUMENT_VA(this, result); + + result.Clear(); + if (IsValid()) { + TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget()); + std::unique_lock<std::recursive_mutex> lock; + if (target_sp) + lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex()); + m_opaque_ptr->SourceInitFileGlobal(result.ref()); + } else { + result->AppendError("SBCommandInterpreter is not valid"); + } +} + +void SBCommandInterpreter::SourceInitFileInHomeDirectory( + SBCommandReturnObject &result) { + LLDB_INSTRUMENT_VA(this, result); + + SourceInitFileInHomeDirectory(result, /*is_repl=*/false); +} + +void SBCommandInterpreter::SourceInitFileInHomeDirectory( + SBCommandReturnObject &result, bool is_repl) { + LLDB_INSTRUMENT_VA(this, result, is_repl); + + result.Clear(); + if (IsValid()) { + TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget()); + std::unique_lock<std::recursive_mutex> lock; + if (target_sp) + lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex()); + m_opaque_ptr->SourceInitFileHome(result.ref(), is_repl); + } else { + result->AppendError("SBCommandInterpreter is not valid"); + } +} + +void SBCommandInterpreter::SourceInitFileInCurrentWorkingDirectory( + SBCommandReturnObject &result) { + LLDB_INSTRUMENT_VA(this, result); + + result.Clear(); + if (IsValid()) { + TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget()); + std::unique_lock<std::recursive_mutex> lock; + if (target_sp) + lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex()); + m_opaque_ptr->SourceInitFileCwd(result.ref()); + } else { + result->AppendError("SBCommandInterpreter is not valid"); + } +} + +SBBroadcaster SBCommandInterpreter::GetBroadcaster() { + LLDB_INSTRUMENT_VA(this); + + SBBroadcaster broadcaster(m_opaque_ptr, false); + + return broadcaster; +} + +const char *SBCommandInterpreter::GetBroadcasterClass() { + LLDB_INSTRUMENT(); + + return ConstString(CommandInterpreter::GetStaticBroadcasterClass()) + .AsCString(); +} + +const char *SBCommandInterpreter::GetArgumentTypeAsCString( + const lldb::CommandArgumentType arg_type) { + LLDB_INSTRUMENT_VA(arg_type); + + return ConstString(CommandObject::GetArgumentTypeAsCString(arg_type)) + .GetCString(); +} + +const char *SBCommandInterpreter::GetArgumentDescriptionAsCString( + const lldb::CommandArgumentType arg_type) { + LLDB_INSTRUMENT_VA(arg_type); + + return ConstString(CommandObject::GetArgumentDescriptionAsCString(arg_type)) + .GetCString(); +} + +bool SBCommandInterpreter::EventIsCommandInterpreterEvent( + const lldb::SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return event.GetBroadcasterClass() == + SBCommandInterpreter::GetBroadcasterClass(); +} + +bool SBCommandInterpreter::SetCommandOverrideCallback( + const char *command_name, lldb::CommandOverrideCallback callback, + void *baton) { + LLDB_INSTRUMENT_VA(this, command_name, callback, baton); + + if (command_name && command_name[0] && IsValid()) { + llvm::StringRef command_name_str = command_name; + CommandObject *cmd_obj = + m_opaque_ptr->GetCommandObjectForCommand(command_name_str); + if (cmd_obj) { + assert(command_name_str.empty()); + cmd_obj->SetOverrideCallback(callback, baton); + return true; + } + } + return false; +} + +SBStructuredData SBCommandInterpreter::GetStatistics() { + LLDB_INSTRUMENT_VA(this); + + SBStructuredData data; + if (!IsValid()) + return data; + + std::string json_str = + llvm::formatv("{0:2}", m_opaque_ptr->GetStatistics()).str(); + data.m_impl_up->SetObjectSP(StructuredData::ParseJSON(json_str)); + return data; +} + +SBStructuredData SBCommandInterpreter::GetTranscript() { + LLDB_INSTRUMENT_VA(this); + + SBStructuredData data; + if (IsValid()) + // A deep copy is performed by `std::make_shared` on the + // `StructuredData::Array`, via its implicitly-declared copy constructor. + // This ensures thread-safety between the user changing the returned + // `SBStructuredData` and the `CommandInterpreter` changing its internal + // `m_transcript`. + data.m_impl_up->SetObjectSP( + std::make_shared<StructuredData::Array>(m_opaque_ptr->GetTranscript())); + return data; +} + +lldb::SBCommand SBCommandInterpreter::AddMultiwordCommand(const char *name, + const char *help) { + LLDB_INSTRUMENT_VA(this, name, help); + + lldb::CommandObjectSP new_command_sp( + new CommandObjectMultiword(*m_opaque_ptr, name, help)); + new_command_sp->GetAsMultiwordCommand()->SetRemovable(true); + Status add_error = m_opaque_ptr->AddUserCommand(name, new_command_sp, true); + if (add_error.Success()) + return lldb::SBCommand(new_command_sp); + return lldb::SBCommand(); +} + +lldb::SBCommand SBCommandInterpreter::AddCommand( + const char *name, lldb::SBCommandPluginInterface *impl, const char *help) { + LLDB_INSTRUMENT_VA(this, name, impl, help); + + return AddCommand(name, impl, help, /*syntax=*/nullptr, + /*auto_repeat_command=*/""); +} + +lldb::SBCommand +SBCommandInterpreter::AddCommand(const char *name, + lldb::SBCommandPluginInterface *impl, + const char *help, const char *syntax) { + LLDB_INSTRUMENT_VA(this, name, impl, help, syntax); + return AddCommand(name, impl, help, syntax, /*auto_repeat_command=*/""); +} + +lldb::SBCommand SBCommandInterpreter::AddCommand( + const char *name, lldb::SBCommandPluginInterface *impl, const char *help, + const char *syntax, const char *auto_repeat_command) { + LLDB_INSTRUMENT_VA(this, name, impl, help, syntax, auto_repeat_command); + + lldb::CommandObjectSP new_command_sp; + new_command_sp = std::make_shared<CommandPluginInterfaceImplementation>( + *m_opaque_ptr, name, impl, help, syntax, /*flags=*/0, + auto_repeat_command); + + Status add_error = m_opaque_ptr->AddUserCommand(name, new_command_sp, true); + if (add_error.Success()) + return lldb::SBCommand(new_command_sp); + return lldb::SBCommand(); +} + +SBCommand::SBCommand() { LLDB_INSTRUMENT_VA(this); } + +SBCommand::SBCommand(lldb::CommandObjectSP cmd_sp) : m_opaque_sp(cmd_sp) {} + +bool SBCommand::IsValid() { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBCommand::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} + +const char *SBCommand::GetName() { + LLDB_INSTRUMENT_VA(this); + + return (IsValid() ? ConstString(m_opaque_sp->GetCommandName()).AsCString() : nullptr); +} + +const char *SBCommand::GetHelp() { + LLDB_INSTRUMENT_VA(this); + + return (IsValid() ? ConstString(m_opaque_sp->GetHelp()).AsCString() + : nullptr); +} + +const char *SBCommand::GetHelpLong() { + LLDB_INSTRUMENT_VA(this); + + return (IsValid() ? ConstString(m_opaque_sp->GetHelpLong()).AsCString() + : nullptr); +} + +void SBCommand::SetHelp(const char *help) { + LLDB_INSTRUMENT_VA(this, help); + + if (IsValid()) + m_opaque_sp->SetHelp(help); +} + +void SBCommand::SetHelpLong(const char *help) { + LLDB_INSTRUMENT_VA(this, help); + + if (IsValid()) + m_opaque_sp->SetHelpLong(help); +} + +lldb::SBCommand SBCommand::AddMultiwordCommand(const char *name, + const char *help) { + LLDB_INSTRUMENT_VA(this, name, help); + + if (!IsValid()) + return lldb::SBCommand(); + if (!m_opaque_sp->IsMultiwordObject()) + return lldb::SBCommand(); + CommandObjectMultiword *new_command = new CommandObjectMultiword( + m_opaque_sp->GetCommandInterpreter(), name, help); + new_command->SetRemovable(true); + lldb::CommandObjectSP new_command_sp(new_command); + if (new_command_sp && m_opaque_sp->LoadSubCommand(name, new_command_sp)) + return lldb::SBCommand(new_command_sp); + return lldb::SBCommand(); +} + +lldb::SBCommand SBCommand::AddCommand(const char *name, + lldb::SBCommandPluginInterface *impl, + const char *help) { + LLDB_INSTRUMENT_VA(this, name, impl, help); + return AddCommand(name, impl, help, /*syntax=*/nullptr, + /*auto_repeat_command=*/""); +} + +lldb::SBCommand SBCommand::AddCommand(const char *name, + lldb::SBCommandPluginInterface *impl, + const char *help, const char *syntax) { + LLDB_INSTRUMENT_VA(this, name, impl, help, syntax); + return AddCommand(name, impl, help, syntax, /*auto_repeat_command=*/""); +} + +lldb::SBCommand SBCommand::AddCommand(const char *name, + lldb::SBCommandPluginInterface *impl, + const char *help, const char *syntax, + const char *auto_repeat_command) { + LLDB_INSTRUMENT_VA(this, name, impl, help, syntax, auto_repeat_command); + + if (!IsValid()) + return lldb::SBCommand(); + if (!m_opaque_sp->IsMultiwordObject()) + return lldb::SBCommand(); + lldb::CommandObjectSP new_command_sp; + new_command_sp = std::make_shared<CommandPluginInterfaceImplementation>( + m_opaque_sp->GetCommandInterpreter(), name, impl, help, syntax, + /*flags=*/0, auto_repeat_command); + if (new_command_sp && m_opaque_sp->LoadSubCommand(name, new_command_sp)) + return lldb::SBCommand(new_command_sp); + return lldb::SBCommand(); +} + +uint32_t SBCommand::GetFlags() { + LLDB_INSTRUMENT_VA(this); + + return (IsValid() ? m_opaque_sp->GetFlags().Get() : 0); +} + +void SBCommand::SetFlags(uint32_t flags) { + LLDB_INSTRUMENT_VA(this, flags); + + if (IsValid()) + m_opaque_sp->GetFlags().Set(flags); +} diff --git a/contrib/llvm-project/lldb/source/API/SBCommandInterpreterRunOptions.cpp b/contrib/llvm-project/lldb/source/API/SBCommandInterpreterRunOptions.cpp new file mode 100644 index 000000000000..0c7581d6f1f5 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBCommandInterpreterRunOptions.cpp @@ -0,0 +1,232 @@ +//===-- SBCommandInterpreterRunOptions.cpp --------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/lldb-types.h" + +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBCommandInterpreterRunOptions.h" +#include "lldb/Interpreter/CommandInterpreter.h" + +#include <memory> + +using namespace lldb; +using namespace lldb_private; + +SBCommandInterpreterRunOptions::SBCommandInterpreterRunOptions() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_up = std::make_unique<CommandInterpreterRunOptions>(); +} + +SBCommandInterpreterRunOptions::SBCommandInterpreterRunOptions( + const SBCommandInterpreterRunOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = std::make_unique<CommandInterpreterRunOptions>(rhs.ref()); +} + +SBCommandInterpreterRunOptions::~SBCommandInterpreterRunOptions() = default; + +SBCommandInterpreterRunOptions &SBCommandInterpreterRunOptions::operator=( + const SBCommandInterpreterRunOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this == &rhs) + return *this; + *m_opaque_up = *rhs.m_opaque_up; + return *this; +} + +bool SBCommandInterpreterRunOptions::GetStopOnContinue() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetStopOnContinue(); +} + +void SBCommandInterpreterRunOptions::SetStopOnContinue(bool stop_on_continue) { + LLDB_INSTRUMENT_VA(this, stop_on_continue); + + m_opaque_up->SetStopOnContinue(stop_on_continue); +} + +bool SBCommandInterpreterRunOptions::GetStopOnError() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetStopOnError(); +} + +void SBCommandInterpreterRunOptions::SetStopOnError(bool stop_on_error) { + LLDB_INSTRUMENT_VA(this, stop_on_error); + + m_opaque_up->SetStopOnError(stop_on_error); +} + +bool SBCommandInterpreterRunOptions::GetStopOnCrash() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetStopOnCrash(); +} + +void SBCommandInterpreterRunOptions::SetStopOnCrash(bool stop_on_crash) { + LLDB_INSTRUMENT_VA(this, stop_on_crash); + + m_opaque_up->SetStopOnCrash(stop_on_crash); +} + +bool SBCommandInterpreterRunOptions::GetEchoCommands() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetEchoCommands(); +} + +void SBCommandInterpreterRunOptions::SetEchoCommands(bool echo_commands) { + LLDB_INSTRUMENT_VA(this, echo_commands); + + m_opaque_up->SetEchoCommands(echo_commands); +} + +bool SBCommandInterpreterRunOptions::GetEchoCommentCommands() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetEchoCommentCommands(); +} + +void SBCommandInterpreterRunOptions::SetEchoCommentCommands(bool echo) { + LLDB_INSTRUMENT_VA(this, echo); + + m_opaque_up->SetEchoCommentCommands(echo); +} + +bool SBCommandInterpreterRunOptions::GetPrintResults() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetPrintResults(); +} + +void SBCommandInterpreterRunOptions::SetPrintResults(bool print_results) { + LLDB_INSTRUMENT_VA(this, print_results); + + m_opaque_up->SetPrintResults(print_results); +} + +bool SBCommandInterpreterRunOptions::GetPrintErrors() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetPrintErrors(); +} + +void SBCommandInterpreterRunOptions::SetPrintErrors(bool print_errors) { + LLDB_INSTRUMENT_VA(this, print_errors); + + m_opaque_up->SetPrintErrors(print_errors); +} + +bool SBCommandInterpreterRunOptions::GetAddToHistory() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetAddToHistory(); +} + +void SBCommandInterpreterRunOptions::SetAddToHistory(bool add_to_history) { + LLDB_INSTRUMENT_VA(this, add_to_history); + + m_opaque_up->SetAddToHistory(add_to_history); +} + +bool SBCommandInterpreterRunOptions::GetAutoHandleEvents() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetAutoHandleEvents(); +} + +void SBCommandInterpreterRunOptions::SetAutoHandleEvents( + bool auto_handle_events) { + LLDB_INSTRUMENT_VA(this, auto_handle_events); + + m_opaque_up->SetAutoHandleEvents(auto_handle_events); +} + +bool SBCommandInterpreterRunOptions::GetSpawnThread() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetSpawnThread(); +} + +void SBCommandInterpreterRunOptions::SetSpawnThread(bool spawn_thread) { + LLDB_INSTRUMENT_VA(this, spawn_thread); + + m_opaque_up->SetSpawnThread(spawn_thread); +} + +bool SBCommandInterpreterRunOptions::GetAllowRepeats() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetAllowRepeats(); +} + +void SBCommandInterpreterRunOptions::SetAllowRepeats(bool allow_repeats) { + LLDB_INSTRUMENT_VA(this, allow_repeats); + + m_opaque_up->SetAllowRepeats(allow_repeats); +} + +lldb_private::CommandInterpreterRunOptions * +SBCommandInterpreterRunOptions::get() const { + return m_opaque_up.get(); +} + +lldb_private::CommandInterpreterRunOptions & +SBCommandInterpreterRunOptions::ref() const { + return *m_opaque_up; +} + +SBCommandInterpreterRunResult::SBCommandInterpreterRunResult() + : m_opaque_up(new CommandInterpreterRunResult()) + +{ + LLDB_INSTRUMENT_VA(this); +} + +SBCommandInterpreterRunResult::SBCommandInterpreterRunResult( + const SBCommandInterpreterRunResult &rhs) + : m_opaque_up(new CommandInterpreterRunResult()) { + LLDB_INSTRUMENT_VA(this, rhs); + + *m_opaque_up = *rhs.m_opaque_up; +} + +SBCommandInterpreterRunResult::SBCommandInterpreterRunResult( + const CommandInterpreterRunResult &rhs) { + m_opaque_up = std::make_unique<CommandInterpreterRunResult>(rhs); +} + +SBCommandInterpreterRunResult::~SBCommandInterpreterRunResult() = default; + +SBCommandInterpreterRunResult &SBCommandInterpreterRunResult::operator=( + const SBCommandInterpreterRunResult &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this == &rhs) + return *this; + *m_opaque_up = *rhs.m_opaque_up; + return *this; +} + +int SBCommandInterpreterRunResult::GetNumberOfErrors() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetNumErrors(); +} + +lldb::CommandInterpreterResult +SBCommandInterpreterRunResult::GetResult() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetResult(); +} diff --git a/contrib/llvm-project/lldb/source/API/SBCommandReturnObject.cpp b/contrib/llvm-project/lldb/source/API/SBCommandReturnObject.cpp new file mode 100644 index 000000000000..7d2c102b3d8c --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBCommandReturnObject.cpp @@ -0,0 +1,340 @@ +//===-- SBCommandReturnObject.cpp -----------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBCommandReturnObject.h" +#include "Utils.h" +#include "lldb/API/SBError.h" +#include "lldb/API/SBFile.h" +#include "lldb/API/SBStream.h" +#include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/Utility/ConstString.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Status.h" + +using namespace lldb; +using namespace lldb_private; + +class lldb_private::SBCommandReturnObjectImpl { +public: + SBCommandReturnObjectImpl() : m_ptr(new CommandReturnObject(false)) {} + SBCommandReturnObjectImpl(CommandReturnObject &ref) + : m_ptr(&ref), m_owned(false) {} + SBCommandReturnObjectImpl(const SBCommandReturnObjectImpl &rhs) + : m_ptr(new CommandReturnObject(*rhs.m_ptr)), m_owned(rhs.m_owned) {} + SBCommandReturnObjectImpl &operator=(const SBCommandReturnObjectImpl &rhs) { + SBCommandReturnObjectImpl copy(rhs); + std::swap(*this, copy); + return *this; + } + // rvalue ctor+assignment are not used by SBCommandReturnObject. + ~SBCommandReturnObjectImpl() { + if (m_owned) + delete m_ptr; + } + + CommandReturnObject &operator*() const { return *m_ptr; } + +private: + CommandReturnObject *m_ptr; + bool m_owned = true; +}; + +SBCommandReturnObject::SBCommandReturnObject() + : m_opaque_up(new SBCommandReturnObjectImpl()) { + LLDB_INSTRUMENT_VA(this); +} + +SBCommandReturnObject::SBCommandReturnObject(CommandReturnObject &ref) + : m_opaque_up(new SBCommandReturnObjectImpl(ref)) { + LLDB_INSTRUMENT_VA(this, ref); +} + +SBCommandReturnObject::SBCommandReturnObject(const SBCommandReturnObject &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBCommandReturnObject &SBCommandReturnObject:: +operator=(const SBCommandReturnObject &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +SBCommandReturnObject::~SBCommandReturnObject() = default; + +bool SBCommandReturnObject::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBCommandReturnObject::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + // This method is not useful but it needs to stay to keep SB API stable. + return true; +} + +const char *SBCommandReturnObject::GetOutput() { + LLDB_INSTRUMENT_VA(this); + + ConstString output(ref().GetOutputData()); + return output.AsCString(/*value_if_empty*/ ""); +} + +const char *SBCommandReturnObject::GetError() { + LLDB_INSTRUMENT_VA(this); + + ConstString output(ref().GetErrorData()); + return output.AsCString(/*value_if_empty*/ ""); +} + +size_t SBCommandReturnObject::GetOutputSize() { + LLDB_INSTRUMENT_VA(this); + + return ref().GetOutputData().size(); +} + +size_t SBCommandReturnObject::GetErrorSize() { + LLDB_INSTRUMENT_VA(this); + + return ref().GetErrorData().size(); +} + +size_t SBCommandReturnObject::PutOutput(FILE *fh) { + LLDB_INSTRUMENT_VA(this, fh); + if (fh) { + size_t num_bytes = GetOutputSize(); + if (num_bytes) + return ::fprintf(fh, "%s", GetOutput()); + } + return 0; +} + +size_t SBCommandReturnObject::PutOutput(FileSP file_sp) { + LLDB_INSTRUMENT_VA(this, file_sp); + if (!file_sp) + return 0; + return file_sp->Printf("%s", GetOutput()); +} + +size_t SBCommandReturnObject::PutOutput(SBFile file) { + LLDB_INSTRUMENT_VA(this, file); + if (!file.m_opaque_sp) + return 0; + return file.m_opaque_sp->Printf("%s", GetOutput()); +} + +size_t SBCommandReturnObject::PutError(FILE *fh) { + LLDB_INSTRUMENT_VA(this, fh); + if (fh) { + size_t num_bytes = GetErrorSize(); + if (num_bytes) + return ::fprintf(fh, "%s", GetError()); + } + return 0; +} + +size_t SBCommandReturnObject::PutError(FileSP file_sp) { + LLDB_INSTRUMENT_VA(this, file_sp); + if (!file_sp) + return 0; + return file_sp->Printf("%s", GetError()); +} + +size_t SBCommandReturnObject::PutError(SBFile file) { + LLDB_INSTRUMENT_VA(this, file); + if (!file.m_opaque_sp) + return 0; + return file.m_opaque_sp->Printf("%s", GetError()); +} + +void SBCommandReturnObject::Clear() { + LLDB_INSTRUMENT_VA(this); + + ref().Clear(); +} + +lldb::ReturnStatus SBCommandReturnObject::GetStatus() { + LLDB_INSTRUMENT_VA(this); + + return ref().GetStatus(); +} + +void SBCommandReturnObject::SetStatus(lldb::ReturnStatus status) { + LLDB_INSTRUMENT_VA(this, status); + + ref().SetStatus(status); +} + +bool SBCommandReturnObject::Succeeded() { + LLDB_INSTRUMENT_VA(this); + + return ref().Succeeded(); +} + +bool SBCommandReturnObject::HasResult() { + LLDB_INSTRUMENT_VA(this); + + return ref().HasResult(); +} + +void SBCommandReturnObject::AppendMessage(const char *message) { + LLDB_INSTRUMENT_VA(this, message); + + ref().AppendMessage(message); +} + +void SBCommandReturnObject::AppendWarning(const char *message) { + LLDB_INSTRUMENT_VA(this, message); + + ref().AppendWarning(message); +} + +CommandReturnObject *SBCommandReturnObject::operator->() const { + return &**m_opaque_up; +} + +CommandReturnObject *SBCommandReturnObject::get() const { + return &**m_opaque_up; +} + +CommandReturnObject &SBCommandReturnObject::operator*() const { + return **m_opaque_up; +} + +CommandReturnObject &SBCommandReturnObject::ref() const { + return **m_opaque_up; +} + +bool SBCommandReturnObject::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + description.Printf("Error: "); + lldb::ReturnStatus status = ref().GetStatus(); + if (status == lldb::eReturnStatusStarted) + strm.PutCString("Started"); + else if (status == lldb::eReturnStatusInvalid) + strm.PutCString("Invalid"); + else if (ref().Succeeded()) + strm.PutCString("Success"); + else + strm.PutCString("Fail"); + + if (GetOutputSize() > 0) + strm.Printf("\nOutput Message:\n%s", GetOutput()); + + if (GetErrorSize() > 0) + strm.Printf("\nError Message:\n%s", GetError()); + + return true; +} + +void SBCommandReturnObject::SetImmediateOutputFile(FILE *fh) { + LLDB_INSTRUMENT_VA(this, fh); + + SetImmediateOutputFile(fh, false); +} + +void SBCommandReturnObject::SetImmediateErrorFile(FILE *fh) { + LLDB_INSTRUMENT_VA(this, fh); + + SetImmediateErrorFile(fh, false); +} + +void SBCommandReturnObject::SetImmediateOutputFile(FILE *fh, + bool transfer_ownership) { + LLDB_INSTRUMENT_VA(this, fh, transfer_ownership); + FileSP file = std::make_shared<NativeFile>(fh, transfer_ownership); + ref().SetImmediateOutputFile(file); +} + +void SBCommandReturnObject::SetImmediateErrorFile(FILE *fh, + bool transfer_ownership) { + LLDB_INSTRUMENT_VA(this, fh, transfer_ownership); + FileSP file = std::make_shared<NativeFile>(fh, transfer_ownership); + ref().SetImmediateErrorFile(file); +} + +void SBCommandReturnObject::SetImmediateOutputFile(SBFile file) { + LLDB_INSTRUMENT_VA(this, file); + ref().SetImmediateOutputFile(file.m_opaque_sp); +} + +void SBCommandReturnObject::SetImmediateErrorFile(SBFile file) { + LLDB_INSTRUMENT_VA(this, file); + ref().SetImmediateErrorFile(file.m_opaque_sp); +} + +void SBCommandReturnObject::SetImmediateOutputFile(FileSP file_sp) { + LLDB_INSTRUMENT_VA(this, file_sp); + SetImmediateOutputFile(SBFile(file_sp)); +} + +void SBCommandReturnObject::SetImmediateErrorFile(FileSP file_sp) { + LLDB_INSTRUMENT_VA(this, file_sp); + SetImmediateErrorFile(SBFile(file_sp)); +} + +void SBCommandReturnObject::PutCString(const char *string, int len) { + LLDB_INSTRUMENT_VA(this, string, len); + + if (len == 0 || string == nullptr || *string == 0) { + return; + } else if (len > 0) { + std::string buffer(string, len); + ref().AppendMessage(buffer.c_str()); + } else + ref().AppendMessage(string); +} + +const char *SBCommandReturnObject::GetOutput(bool only_if_no_immediate) { + LLDB_INSTRUMENT_VA(this, only_if_no_immediate); + + if (!only_if_no_immediate || + ref().GetImmediateOutputStream().get() == nullptr) + return GetOutput(); + return nullptr; +} + +const char *SBCommandReturnObject::GetError(bool only_if_no_immediate) { + LLDB_INSTRUMENT_VA(this, only_if_no_immediate); + + if (!only_if_no_immediate || ref().GetImmediateErrorStream().get() == nullptr) + return GetError(); + return nullptr; +} + +size_t SBCommandReturnObject::Printf(const char *format, ...) { + va_list args; + va_start(args, format); + size_t result = ref().GetOutputStream().PrintfVarArg(format, args); + va_end(args); + return result; +} + +void SBCommandReturnObject::SetError(lldb::SBError &error, + const char *fallback_error_cstr) { + LLDB_INSTRUMENT_VA(this, error, fallback_error_cstr); + + if (error.IsValid()) + ref().SetError(error.ref(), fallback_error_cstr); + else if (fallback_error_cstr) + ref().SetError(Status(), fallback_error_cstr); +} + +void SBCommandReturnObject::SetError(const char *error_cstr) { + LLDB_INSTRUMENT_VA(this, error_cstr); + + if (error_cstr) + ref().AppendError(error_cstr); +} diff --git a/contrib/llvm-project/lldb/source/API/SBCommunication.cpp b/contrib/llvm-project/lldb/source/API/SBCommunication.cpp new file mode 100644 index 000000000000..ee33e2abd854 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBCommunication.cpp @@ -0,0 +1,175 @@ +//===-- SBCommunication.cpp -----------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBCommunication.h" +#include "lldb/API/SBBroadcaster.h" +#include "lldb/Core/ThreadedCommunication.h" +#include "lldb/Host/ConnectionFileDescriptor.h" +#include "lldb/Host/Host.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +SBCommunication::SBCommunication() { LLDB_INSTRUMENT_VA(this); } + +SBCommunication::SBCommunication(const char *broadcaster_name) + : m_opaque(new ThreadedCommunication(broadcaster_name)), + m_opaque_owned(true) { + LLDB_INSTRUMENT_VA(this, broadcaster_name); +} + +SBCommunication::~SBCommunication() { + if (m_opaque && m_opaque_owned) + delete m_opaque; + m_opaque = nullptr; + m_opaque_owned = false; +} + +bool SBCommunication::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBCommunication::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque != nullptr; +} + +bool SBCommunication::GetCloseOnEOF() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque) + return m_opaque->GetCloseOnEOF(); + return false; +} + +void SBCommunication::SetCloseOnEOF(bool b) { + LLDB_INSTRUMENT_VA(this, b); + + if (m_opaque) + m_opaque->SetCloseOnEOF(b); +} + +ConnectionStatus SBCommunication::Connect(const char *url) { + LLDB_INSTRUMENT_VA(this, url); + + if (m_opaque) { + if (!m_opaque->HasConnection()) + m_opaque->SetConnection(Host::CreateDefaultConnection(url)); + return m_opaque->Connect(url, nullptr); + } + return eConnectionStatusNoConnection; +} + +ConnectionStatus SBCommunication::AdoptFileDesriptor(int fd, bool owns_fd) { + LLDB_INSTRUMENT_VA(this, fd, owns_fd); + + ConnectionStatus status = eConnectionStatusNoConnection; + if (m_opaque) { + if (m_opaque->HasConnection()) { + if (m_opaque->IsConnected()) + m_opaque->Disconnect(); + } + m_opaque->SetConnection( + std::make_unique<ConnectionFileDescriptor>(fd, owns_fd)); + if (m_opaque->IsConnected()) + status = eConnectionStatusSuccess; + else + status = eConnectionStatusLostConnection; + } + return status; +} + +ConnectionStatus SBCommunication::Disconnect() { + LLDB_INSTRUMENT_VA(this); + + ConnectionStatus status = eConnectionStatusNoConnection; + if (m_opaque) + status = m_opaque->Disconnect(); + return status; +} + +bool SBCommunication::IsConnected() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque ? m_opaque->IsConnected() : false; +} + +size_t SBCommunication::Read(void *dst, size_t dst_len, uint32_t timeout_usec, + ConnectionStatus &status) { + LLDB_INSTRUMENT_VA(this, dst, dst_len, timeout_usec, status); + + size_t bytes_read = 0; + Timeout<std::micro> timeout = timeout_usec == UINT32_MAX + ? Timeout<std::micro>(std::nullopt) + : std::chrono::microseconds(timeout_usec); + if (m_opaque) + bytes_read = m_opaque->Read(dst, dst_len, timeout, status, nullptr); + else + status = eConnectionStatusNoConnection; + + return bytes_read; +} + +size_t SBCommunication::Write(const void *src, size_t src_len, + ConnectionStatus &status) { + LLDB_INSTRUMENT_VA(this, src, src_len, status); + + size_t bytes_written = 0; + if (m_opaque) + bytes_written = m_opaque->Write(src, src_len, status, nullptr); + else + status = eConnectionStatusNoConnection; + + return bytes_written; +} + +bool SBCommunication::ReadThreadStart() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque ? m_opaque->StartReadThread() : false; +} + +bool SBCommunication::ReadThreadStop() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque ? m_opaque->StopReadThread() : false; +} + +bool SBCommunication::ReadThreadIsRunning() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque ? m_opaque->ReadThreadIsRunning() : false; +} + +bool SBCommunication::SetReadThreadBytesReceivedCallback( + ReadThreadBytesReceived callback, void *callback_baton) { + LLDB_INSTRUMENT_VA(this, callback, callback_baton); + + bool result = false; + if (m_opaque) { + m_opaque->SetReadThreadBytesReceivedCallback(callback, callback_baton); + result = true; + } + return result; +} + +SBBroadcaster SBCommunication::GetBroadcaster() { + LLDB_INSTRUMENT_VA(this); + + SBBroadcaster broadcaster(m_opaque, false); + return broadcaster; +} + +const char *SBCommunication::GetBroadcasterClass() { + LLDB_INSTRUMENT(); + + return ConstString(ThreadedCommunication::GetStaticBroadcasterClass()) + .AsCString(); +} diff --git a/contrib/llvm-project/lldb/source/API/SBCompileUnit.cpp b/contrib/llvm-project/lldb/source/API/SBCompileUnit.cpp new file mode 100644 index 000000000000..65fdb11032b9 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBCompileUnit.cpp @@ -0,0 +1,235 @@ +//===-- SBCompileUnit.cpp -------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBCompileUnit.h" +#include "lldb/API/SBLineEntry.h" +#include "lldb/API/SBStream.h" +#include "lldb/Core/Module.h" +#include "lldb/Symbol/CompileUnit.h" +#include "lldb/Symbol/LineEntry.h" +#include "lldb/Symbol/LineTable.h" +#include "lldb/Symbol/SymbolFile.h" +#include "lldb/Symbol/Type.h" +#include "lldb/Symbol/TypeList.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +SBCompileUnit::SBCompileUnit() { LLDB_INSTRUMENT_VA(this); } + +SBCompileUnit::SBCompileUnit(lldb_private::CompileUnit *lldb_object_ptr) + : m_opaque_ptr(lldb_object_ptr) {} + +SBCompileUnit::SBCompileUnit(const SBCompileUnit &rhs) + : m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const SBCompileUnit &SBCompileUnit::operator=(const SBCompileUnit &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_ptr = rhs.m_opaque_ptr; + return *this; +} + +SBCompileUnit::~SBCompileUnit() { m_opaque_ptr = nullptr; } + +SBFileSpec SBCompileUnit::GetFileSpec() const { + LLDB_INSTRUMENT_VA(this); + + SBFileSpec file_spec; + if (m_opaque_ptr) + file_spec.SetFileSpec(m_opaque_ptr->GetPrimaryFile()); + return file_spec; +} + +uint32_t SBCompileUnit::GetNumLineEntries() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) { + LineTable *line_table = m_opaque_ptr->GetLineTable(); + if (line_table) { + return line_table->GetSize(); + } + } + return 0; +} + +SBLineEntry SBCompileUnit::GetLineEntryAtIndex(uint32_t idx) const { + LLDB_INSTRUMENT_VA(this, idx); + + SBLineEntry sb_line_entry; + if (m_opaque_ptr) { + LineTable *line_table = m_opaque_ptr->GetLineTable(); + if (line_table) { + LineEntry line_entry; + if (line_table->GetLineEntryAtIndex(idx, line_entry)) + sb_line_entry.SetLineEntry(line_entry); + } + } + + return sb_line_entry; +} + +uint32_t SBCompileUnit::FindLineEntryIndex(lldb::SBLineEntry &line_entry, + bool exact) const { + LLDB_INSTRUMENT_VA(this, line_entry, exact); + + if (!m_opaque_ptr || !line_entry.IsValid()) + return UINT32_MAX; + + LineEntry found_line_entry; + + return m_opaque_ptr->FindLineEntry(0, line_entry.GetLine(), + line_entry.GetFileSpec().get(), exact, + &line_entry.ref()); +} + +uint32_t SBCompileUnit::FindLineEntryIndex(uint32_t start_idx, uint32_t line, + SBFileSpec *inline_file_spec) const { + LLDB_INSTRUMENT_VA(this, start_idx, line, inline_file_spec); + + const bool exact = true; + return FindLineEntryIndex(start_idx, line, inline_file_spec, exact); +} + +uint32_t SBCompileUnit::FindLineEntryIndex(uint32_t start_idx, uint32_t line, + SBFileSpec *inline_file_spec, + bool exact) const { + LLDB_INSTRUMENT_VA(this, start_idx, line, inline_file_spec, exact); + + uint32_t index = UINT32_MAX; + if (m_opaque_ptr) { + FileSpec file_spec; + if (inline_file_spec && inline_file_spec->IsValid()) + file_spec = inline_file_spec->ref(); + else + file_spec = m_opaque_ptr->GetPrimaryFile(); + + LineEntry line_entry; + index = m_opaque_ptr->FindLineEntry( + start_idx, line, inline_file_spec ? inline_file_spec->get() : nullptr, + exact, &line_entry); + } + + return index; +} + +uint32_t SBCompileUnit::GetNumSupportFiles() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return m_opaque_ptr->GetSupportFiles().GetSize(); + + return 0; +} + +lldb::SBTypeList SBCompileUnit::GetTypes(uint32_t type_mask) { + LLDB_INSTRUMENT_VA(this, type_mask); + + SBTypeList sb_type_list; + + if (!m_opaque_ptr) + return sb_type_list; + + ModuleSP module_sp(m_opaque_ptr->GetModule()); + if (!module_sp) + return sb_type_list; + + SymbolFile *symfile = module_sp->GetSymbolFile(); + if (!symfile) + return sb_type_list; + + TypeClass type_class = static_cast<TypeClass>(type_mask); + TypeList type_list; + symfile->GetTypes(m_opaque_ptr, type_class, type_list); + sb_type_list.m_opaque_up->Append(type_list); + return sb_type_list; +} + +SBFileSpec SBCompileUnit::GetSupportFileAtIndex(uint32_t idx) const { + LLDB_INSTRUMENT_VA(this, idx); + + SBFileSpec sb_file_spec; + if (m_opaque_ptr) { + FileSpec spec = m_opaque_ptr->GetSupportFiles().GetFileSpecAtIndex(idx); + sb_file_spec.SetFileSpec(spec); + } + + return sb_file_spec; +} + +uint32_t SBCompileUnit::FindSupportFileIndex(uint32_t start_idx, + const SBFileSpec &sb_file, + bool full) { + LLDB_INSTRUMENT_VA(this, start_idx, sb_file, full); + + if (m_opaque_ptr) { + const SupportFileList &support_files = m_opaque_ptr->GetSupportFiles(); + return support_files.FindFileIndex(start_idx, sb_file.ref(), full); + } + return 0; +} + +lldb::LanguageType SBCompileUnit::GetLanguage() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return m_opaque_ptr->GetLanguage(); + return lldb::eLanguageTypeUnknown; +} + +bool SBCompileUnit::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBCompileUnit::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_ptr != nullptr; +} + +bool SBCompileUnit::operator==(const SBCompileUnit &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_ptr == rhs.m_opaque_ptr; +} + +bool SBCompileUnit::operator!=(const SBCompileUnit &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_ptr != rhs.m_opaque_ptr; +} + +const lldb_private::CompileUnit *SBCompileUnit::operator->() const { + return m_opaque_ptr; +} + +const lldb_private::CompileUnit &SBCompileUnit::operator*() const { + return *m_opaque_ptr; +} + +lldb_private::CompileUnit *SBCompileUnit::get() { return m_opaque_ptr; } + +void SBCompileUnit::reset(lldb_private::CompileUnit *lldb_object_ptr) { + m_opaque_ptr = lldb_object_ptr; +} + +bool SBCompileUnit::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + if (m_opaque_ptr) { + m_opaque_ptr->Dump(&strm, false); + } else + strm.PutCString("No value"); + + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBData.cpp b/contrib/llvm-project/lldb/source/API/SBData.cpp new file mode 100644 index 000000000000..924a4cdb93bf --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBData.cpp @@ -0,0 +1,623 @@ +//===-- SBData.cpp --------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBData.h" +#include "lldb/API/SBError.h" +#include "lldb/API/SBStream.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/Core/DumpDataExtractor.h" +#include "lldb/Utility/DataBufferHeap.h" +#include "lldb/Utility/DataExtractor.h" +#include "lldb/Utility/Stream.h" + +#include <cinttypes> +#include <memory> + +using namespace lldb; +using namespace lldb_private; + +SBData::SBData() : m_opaque_sp(new DataExtractor()) { + LLDB_INSTRUMENT_VA(this); +} + +SBData::SBData(const lldb::DataExtractorSP &data_sp) : m_opaque_sp(data_sp) {} + +SBData::SBData(const SBData &rhs) : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const SBData &SBData::operator=(const SBData &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; +} + +SBData::~SBData() = default; + +void SBData::SetOpaque(const lldb::DataExtractorSP &data_sp) { + m_opaque_sp = data_sp; +} + +lldb_private::DataExtractor *SBData::get() const { return m_opaque_sp.get(); } + +lldb_private::DataExtractor *SBData::operator->() const { + return m_opaque_sp.operator->(); +} + +lldb::DataExtractorSP &SBData::operator*() { return m_opaque_sp; } + +const lldb::DataExtractorSP &SBData::operator*() const { return m_opaque_sp; } + +bool SBData::IsValid() { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBData::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} + +uint8_t SBData::GetAddressByteSize() { + LLDB_INSTRUMENT_VA(this); + + uint8_t value = 0; + if (m_opaque_sp.get()) + value = m_opaque_sp->GetAddressByteSize(); + return value; +} + +void SBData::SetAddressByteSize(uint8_t addr_byte_size) { + LLDB_INSTRUMENT_VA(this, addr_byte_size); + + if (m_opaque_sp.get()) + m_opaque_sp->SetAddressByteSize(addr_byte_size); +} + +void SBData::Clear() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp.get()) + m_opaque_sp->Clear(); +} + +size_t SBData::GetByteSize() { + LLDB_INSTRUMENT_VA(this); + + size_t value = 0; + if (m_opaque_sp.get()) + value = m_opaque_sp->GetByteSize(); + return value; +} + +lldb::ByteOrder SBData::GetByteOrder() { + LLDB_INSTRUMENT_VA(this); + + lldb::ByteOrder value = eByteOrderInvalid; + if (m_opaque_sp.get()) + value = m_opaque_sp->GetByteOrder(); + return value; +} + +void SBData::SetByteOrder(lldb::ByteOrder endian) { + LLDB_INSTRUMENT_VA(this, endian); + + if (m_opaque_sp.get()) + m_opaque_sp->SetByteOrder(endian); +} + +float SBData::GetFloat(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + float value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetFloat(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + return value; +} + +double SBData::GetDouble(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + double value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetDouble(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + return value; +} + +long double SBData::GetLongDouble(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + long double value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetLongDouble(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + return value; +} + +lldb::addr_t SBData::GetAddress(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + lldb::addr_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetAddress(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + return value; +} + +uint8_t SBData::GetUnsignedInt8(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + uint8_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetU8(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + return value; +} + +uint16_t SBData::GetUnsignedInt16(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + uint16_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetU16(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + return value; +} + +uint32_t SBData::GetUnsignedInt32(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + uint32_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetU32(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + return value; +} + +uint64_t SBData::GetUnsignedInt64(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + uint64_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetU64(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + return value; +} + +int8_t SBData::GetSignedInt8(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + int8_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = (int8_t)m_opaque_sp->GetMaxS64(&offset, 1); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + return value; +} + +int16_t SBData::GetSignedInt16(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + int16_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = (int16_t)m_opaque_sp->GetMaxS64(&offset, 2); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + return value; +} + +int32_t SBData::GetSignedInt32(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + int32_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = (int32_t)m_opaque_sp->GetMaxS64(&offset, 4); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + return value; +} + +int64_t SBData::GetSignedInt64(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + int64_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = (int64_t)m_opaque_sp->GetMaxS64(&offset, 8); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + return value; +} + +const char *SBData::GetString(lldb::SBError &error, lldb::offset_t offset) { + LLDB_INSTRUMENT_VA(this, error, offset); + + if (!m_opaque_sp) { + error.SetErrorString("no value to read from"); + return nullptr; + } + + lldb::offset_t old_offset = offset; + const char *value = m_opaque_sp->GetCStr(&offset); + if (offset == old_offset || value == nullptr) { + error.SetErrorString("unable to read data"); + return nullptr; + } + + return ConstString(value).GetCString(); +} + +bool SBData::GetDescription(lldb::SBStream &description, + lldb::addr_t base_addr) { + LLDB_INSTRUMENT_VA(this, description, base_addr); + + Stream &strm = description.ref(); + + if (m_opaque_sp) { + DumpDataExtractor(*m_opaque_sp, &strm, 0, lldb::eFormatBytesWithASCII, 1, + m_opaque_sp->GetByteSize(), 16, base_addr, 0, 0); + } else + strm.PutCString("No value"); + + return true; +} + +size_t SBData::ReadRawData(lldb::SBError &error, lldb::offset_t offset, + void *buf, size_t size) { + LLDB_INSTRUMENT_VA(this, error, offset, buf, size); + + void *ok = nullptr; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + ok = m_opaque_sp->GetU8(&offset, buf, size); + if ((offset == old_offset) || (ok == nullptr)) + error.SetErrorString("unable to read data"); + } + return ok ? size : 0; +} + +void SBData::SetData(lldb::SBError &error, const void *buf, size_t size, + lldb::ByteOrder endian, uint8_t addr_size) { + LLDB_INSTRUMENT_VA(this, error, buf, size, endian, addr_size); + + if (!m_opaque_sp.get()) + m_opaque_sp = std::make_shared<DataExtractor>(buf, size, endian, addr_size); + else + { + m_opaque_sp->SetData(buf, size, endian); + m_opaque_sp->SetAddressByteSize(addr_size); + } +} + +void SBData::SetDataWithOwnership(lldb::SBError &error, const void *buf, + size_t size, lldb::ByteOrder endian, + uint8_t addr_size) { + LLDB_INSTRUMENT_VA(this, error, buf, size, endian, addr_size); + + lldb::DataBufferSP buffer_sp = std::make_shared<DataBufferHeap>(buf, size); + + if (!m_opaque_sp.get()) + m_opaque_sp = std::make_shared<DataExtractor>(buf, size, endian, addr_size); + else { + m_opaque_sp->SetData(buffer_sp); + m_opaque_sp->SetByteOrder(endian); + m_opaque_sp->SetAddressByteSize(addr_size); + } +} + +bool SBData::Append(const SBData &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + bool value = false; + if (m_opaque_sp.get() && rhs.m_opaque_sp.get()) + value = m_opaque_sp.get()->Append(*rhs.m_opaque_sp); + return value; +} + +lldb::SBData SBData::CreateDataFromCString(lldb::ByteOrder endian, + uint32_t addr_byte_size, + const char *data) { + LLDB_INSTRUMENT_VA(endian, addr_byte_size, data); + + if (!data || !data[0]) + return SBData(); + + uint32_t data_len = strlen(data); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(data, data_len)); + lldb::DataExtractorSP data_sp( + new DataExtractor(buffer_sp, endian, addr_byte_size)); + + SBData ret(data_sp); + + return ret; +} + +lldb::SBData SBData::CreateDataFromUInt64Array(lldb::ByteOrder endian, + uint32_t addr_byte_size, + uint64_t *array, + size_t array_len) { + LLDB_INSTRUMENT_VA(endian, addr_byte_size, array, array_len); + + if (!array || array_len == 0) + return SBData(); + + size_t data_len = array_len * sizeof(uint64_t); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + lldb::DataExtractorSP data_sp( + new DataExtractor(buffer_sp, endian, addr_byte_size)); + + SBData ret(data_sp); + + return ret; +} + +lldb::SBData SBData::CreateDataFromUInt32Array(lldb::ByteOrder endian, + uint32_t addr_byte_size, + uint32_t *array, + size_t array_len) { + LLDB_INSTRUMENT_VA(endian, addr_byte_size, array, array_len); + + if (!array || array_len == 0) + return SBData(); + + size_t data_len = array_len * sizeof(uint32_t); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + lldb::DataExtractorSP data_sp( + new DataExtractor(buffer_sp, endian, addr_byte_size)); + + SBData ret(data_sp); + + return ret; +} + +lldb::SBData SBData::CreateDataFromSInt64Array(lldb::ByteOrder endian, + uint32_t addr_byte_size, + int64_t *array, + size_t array_len) { + LLDB_INSTRUMENT_VA(endian, addr_byte_size, array, array_len); + + if (!array || array_len == 0) + return SBData(); + + size_t data_len = array_len * sizeof(int64_t); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + lldb::DataExtractorSP data_sp( + new DataExtractor(buffer_sp, endian, addr_byte_size)); + + SBData ret(data_sp); + + return ret; +} + +lldb::SBData SBData::CreateDataFromSInt32Array(lldb::ByteOrder endian, + uint32_t addr_byte_size, + int32_t *array, + size_t array_len) { + LLDB_INSTRUMENT_VA(endian, addr_byte_size, array, array_len); + + if (!array || array_len == 0) + return SBData(); + + size_t data_len = array_len * sizeof(int32_t); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + lldb::DataExtractorSP data_sp( + new DataExtractor(buffer_sp, endian, addr_byte_size)); + + SBData ret(data_sp); + + return ret; +} + +lldb::SBData SBData::CreateDataFromDoubleArray(lldb::ByteOrder endian, + uint32_t addr_byte_size, + double *array, + size_t array_len) { + LLDB_INSTRUMENT_VA(endian, addr_byte_size, array, array_len); + + if (!array || array_len == 0) + return SBData(); + + size_t data_len = array_len * sizeof(double); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + lldb::DataExtractorSP data_sp( + new DataExtractor(buffer_sp, endian, addr_byte_size)); + + SBData ret(data_sp); + + return ret; +} + +bool SBData::SetDataFromCString(const char *data) { + LLDB_INSTRUMENT_VA(this, data); + + if (!data) { + return false; + } + + size_t data_len = strlen(data); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(data, data_len)); + + if (!m_opaque_sp.get()) + m_opaque_sp = std::make_shared<DataExtractor>(buffer_sp, GetByteOrder(), + GetAddressByteSize()); + else + m_opaque_sp->SetData(buffer_sp); + + + return true; +} + +bool SBData::SetDataFromUInt64Array(uint64_t *array, size_t array_len) { + LLDB_INSTRUMENT_VA(this, array, array_len); + + if (!array || array_len == 0) { + return false; + } + + size_t data_len = array_len * sizeof(uint64_t); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + + if (!m_opaque_sp.get()) + m_opaque_sp = std::make_shared<DataExtractor>(buffer_sp, GetByteOrder(), + GetAddressByteSize()); + else + m_opaque_sp->SetData(buffer_sp); + + + return true; +} + +bool SBData::SetDataFromUInt32Array(uint32_t *array, size_t array_len) { + LLDB_INSTRUMENT_VA(this, array, array_len); + + if (!array || array_len == 0) { + return false; + } + + size_t data_len = array_len * sizeof(uint32_t); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + + if (!m_opaque_sp.get()) + m_opaque_sp = std::make_shared<DataExtractor>(buffer_sp, GetByteOrder(), + GetAddressByteSize()); + else + m_opaque_sp->SetData(buffer_sp); + + return true; +} + +bool SBData::SetDataFromSInt64Array(int64_t *array, size_t array_len) { + LLDB_INSTRUMENT_VA(this, array, array_len); + + if (!array || array_len == 0) { + return false; + } + + size_t data_len = array_len * sizeof(int64_t); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + + if (!m_opaque_sp.get()) + m_opaque_sp = std::make_shared<DataExtractor>(buffer_sp, GetByteOrder(), + GetAddressByteSize()); + else + m_opaque_sp->SetData(buffer_sp); + + return true; +} + +bool SBData::SetDataFromSInt32Array(int32_t *array, size_t array_len) { + LLDB_INSTRUMENT_VA(this, array, array_len); + + if (!array || array_len == 0) { + return false; + } + + size_t data_len = array_len * sizeof(int32_t); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + + if (!m_opaque_sp.get()) + m_opaque_sp = std::make_shared<DataExtractor>(buffer_sp, GetByteOrder(), + GetAddressByteSize()); + else + m_opaque_sp->SetData(buffer_sp); + + return true; +} + +bool SBData::SetDataFromDoubleArray(double *array, size_t array_len) { + LLDB_INSTRUMENT_VA(this, array, array_len); + + if (!array || array_len == 0) { + return false; + } + + size_t data_len = array_len * sizeof(double); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + + if (!m_opaque_sp.get()) + m_opaque_sp = std::make_shared<DataExtractor>(buffer_sp, GetByteOrder(), + GetAddressByteSize()); + else + m_opaque_sp->SetData(buffer_sp); + + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBDebugger.cpp b/contrib/llvm-project/lldb/source/API/SBDebugger.cpp new file mode 100644 index 000000000000..29da7d33dd80 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBDebugger.cpp @@ -0,0 +1,1748 @@ +//===-- SBDebugger.cpp ----------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBDebugger.h" +#include "SystemInitializerFull.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/LLDBLog.h" + +#include "lldb/API/SBBroadcaster.h" +#include "lldb/API/SBCommandInterpreter.h" +#include "lldb/API/SBCommandInterpreterRunOptions.h" +#include "lldb/API/SBCommandReturnObject.h" +#include "lldb/API/SBError.h" +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBFile.h" +#include "lldb/API/SBFrame.h" +#include "lldb/API/SBListener.h" +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBSourceManager.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStringList.h" +#include "lldb/API/SBStructuredData.h" +#include "lldb/API/SBTarget.h" +#include "lldb/API/SBThread.h" +#include "lldb/API/SBTrace.h" +#include "lldb/API/SBTypeCategory.h" +#include "lldb/API/SBTypeFilter.h" +#include "lldb/API/SBTypeFormat.h" +#include "lldb/API/SBTypeNameSpecifier.h" +#include "lldb/API/SBTypeSummary.h" +#include "lldb/API/SBTypeSynthetic.h" + +#include "lldb/Core/Debugger.h" +#include "lldb/Core/DebuggerEvents.h" +#include "lldb/Core/PluginManager.h" +#include "lldb/Core/Progress.h" +#include "lldb/Core/StructuredDataImpl.h" +#include "lldb/DataFormatters/DataVisualization.h" +#include "lldb/Host/Config.h" +#include "lldb/Host/StreamFile.h" +#include "lldb/Host/XML.h" +#include "lldb/Initialization/SystemLifetimeManager.h" +#include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Interpreter/OptionArgParser.h" +#include "lldb/Interpreter/OptionGroupPlatform.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/TargetList.h" +#include "lldb/Utility/Args.h" +#include "lldb/Utility/Diagnostics.h" +#include "lldb/Utility/State.h" +#include "lldb/Version/Version.h" + +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/DynamicLibrary.h" +#include "llvm/Support/ManagedStatic.h" +#include "llvm/Support/PrettyStackTrace.h" +#include "llvm/Support/Signals.h" + +using namespace lldb; +using namespace lldb_private; + +static llvm::ManagedStatic<SystemLifetimeManager> g_debugger_lifetime; + +SBError SBInputReader::Initialize( + lldb::SBDebugger &sb_debugger, + unsigned long (*callback)(void *, lldb::SBInputReader *, + lldb::InputReaderAction, char const *, + unsigned long), + void *a, lldb::InputReaderGranularity b, char const *c, char const *d, + bool e) { + LLDB_INSTRUMENT_VA(this, sb_debugger, callback, a, b, c, d, e); + + return SBError(); +} + +void SBInputReader::SetIsDone(bool b) { LLDB_INSTRUMENT_VA(this, b); } + +bool SBInputReader::IsActive() const { + LLDB_INSTRUMENT_VA(this); + + return false; +} + +SBDebugger::SBDebugger() { LLDB_INSTRUMENT_VA(this); } + +SBDebugger::SBDebugger(const lldb::DebuggerSP &debugger_sp) + : m_opaque_sp(debugger_sp) { + LLDB_INSTRUMENT_VA(this, debugger_sp); +} + +SBDebugger::SBDebugger(const SBDebugger &rhs) : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBDebugger::~SBDebugger() = default; + +SBDebugger &SBDebugger::operator=(const SBDebugger &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; +} + +const char *SBDebugger::GetBroadcasterClass() { + LLDB_INSTRUMENT(); + + return ConstString(Debugger::GetStaticBroadcasterClass()).AsCString(); +} + +const char *SBDebugger::GetProgressFromEvent(const lldb::SBEvent &event, + uint64_t &progress_id, + uint64_t &completed, + uint64_t &total, + bool &is_debugger_specific) { + LLDB_INSTRUMENT_VA(event); + + const ProgressEventData *progress_data = + ProgressEventData::GetEventDataFromEvent(event.get()); + if (progress_data == nullptr) + return nullptr; + progress_id = progress_data->GetID(); + completed = progress_data->GetCompleted(); + total = progress_data->GetTotal(); + is_debugger_specific = progress_data->IsDebuggerSpecific(); + ConstString message(progress_data->GetMessage()); + return message.AsCString(); +} + +lldb::SBStructuredData +SBDebugger::GetProgressDataFromEvent(const lldb::SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + StructuredData::DictionarySP dictionary_sp = + ProgressEventData::GetAsStructuredData(event.get()); + + if (!dictionary_sp) + return {}; + + SBStructuredData data; + data.m_impl_up->SetObjectSP(std::move(dictionary_sp)); + return data; +} + +lldb::SBStructuredData +SBDebugger::GetDiagnosticFromEvent(const lldb::SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + StructuredData::DictionarySP dictionary_sp = + DiagnosticEventData::GetAsStructuredData(event.get()); + + if (!dictionary_sp) + return {}; + + SBStructuredData data; + data.m_impl_up->SetObjectSP(std::move(dictionary_sp)); + return data; +} + +SBBroadcaster SBDebugger::GetBroadcaster() { + LLDB_INSTRUMENT_VA(this); + SBBroadcaster broadcaster(&m_opaque_sp->GetBroadcaster(), false); + return broadcaster; +} + +void SBDebugger::Initialize() { + LLDB_INSTRUMENT(); + SBError ignored = SBDebugger::InitializeWithErrorHandling(); +} + +lldb::SBError SBDebugger::InitializeWithErrorHandling() { + LLDB_INSTRUMENT(); + + auto LoadPlugin = [](const lldb::DebuggerSP &debugger_sp, + const FileSpec &spec, + Status &error) -> llvm::sys::DynamicLibrary { + llvm::sys::DynamicLibrary dynlib = + llvm::sys::DynamicLibrary::getPermanentLibrary(spec.GetPath().c_str()); + if (dynlib.isValid()) { + typedef bool (*LLDBCommandPluginInit)(lldb::SBDebugger & debugger); + + lldb::SBDebugger debugger_sb(debugger_sp); + // This calls the bool lldb::PluginInitialize(lldb::SBDebugger debugger) + // function. + // TODO: mangle this differently for your system - on OSX, the first + // underscore needs to be removed and the second one stays + LLDBCommandPluginInit init_func = + (LLDBCommandPluginInit)(uintptr_t)dynlib.getAddressOfSymbol( + "_ZN4lldb16PluginInitializeENS_10SBDebuggerE"); + if (init_func) { + if (init_func(debugger_sb)) + return dynlib; + else + error.SetErrorString("plug-in refused to load " + "(lldb::PluginInitialize(lldb::SBDebugger) " + "returned false)"); + } else { + error.SetErrorString("plug-in is missing the required initialization: " + "lldb::PluginInitialize(lldb::SBDebugger)"); + } + } else { + if (FileSystem::Instance().Exists(spec)) + error.SetErrorString("this file does not represent a loadable dylib"); + else + error.SetErrorString("no such file"); + } + return llvm::sys::DynamicLibrary(); + }; + + SBError error; + if (auto e = g_debugger_lifetime->Initialize( + std::make_unique<SystemInitializerFull>(), LoadPlugin)) { + error.SetError(Status(std::move(e))); + } + return error; +} + +void SBDebugger::PrintStackTraceOnError() { + LLDB_INSTRUMENT(); + + llvm::EnablePrettyStackTrace(); + static std::string executable = + llvm::sys::fs::getMainExecutable(nullptr, nullptr); + llvm::sys::PrintStackTraceOnErrorSignal(executable); +} + +static void DumpDiagnostics(void *cookie) { + Diagnostics::Instance().Dump(llvm::errs()); +} + +void SBDebugger::PrintDiagnosticsOnError() { + LLDB_INSTRUMENT(); + + llvm::sys::AddSignalHandler(&DumpDiagnostics, nullptr); +} + +void SBDebugger::Terminate() { + LLDB_INSTRUMENT(); + + g_debugger_lifetime->Terminate(); +} + +void SBDebugger::Clear() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + m_opaque_sp->ClearIOHandlers(); + + m_opaque_sp.reset(); +} + +SBDebugger SBDebugger::Create() { + LLDB_INSTRUMENT(); + + return SBDebugger::Create(false, nullptr, nullptr); +} + +SBDebugger SBDebugger::Create(bool source_init_files) { + LLDB_INSTRUMENT_VA(source_init_files); + + return SBDebugger::Create(source_init_files, nullptr, nullptr); +} + +SBDebugger SBDebugger::Create(bool source_init_files, + lldb::LogOutputCallback callback, void *baton) + +{ + LLDB_INSTRUMENT_VA(source_init_files, callback, baton); + + SBDebugger debugger; + + // Currently we have issues if this function is called simultaneously on two + // different threads. The issues mainly revolve around the fact that the + // lldb_private::FormatManager uses global collections and having two threads + // parsing the .lldbinit files can cause mayhem. So to get around this for + // now we need to use a mutex to prevent bad things from happening. + static std::recursive_mutex g_mutex; + std::lock_guard<std::recursive_mutex> guard(g_mutex); + + debugger.reset(Debugger::CreateInstance(callback, baton)); + + SBCommandInterpreter interp = debugger.GetCommandInterpreter(); + if (source_init_files) { + interp.get()->SkipLLDBInitFiles(false); + interp.get()->SkipAppInitFiles(false); + SBCommandReturnObject result; + interp.SourceInitFileInGlobalDirectory(result); + interp.SourceInitFileInHomeDirectory(result, false); + } else { + interp.get()->SkipLLDBInitFiles(true); + interp.get()->SkipAppInitFiles(true); + } + return debugger; +} + +void SBDebugger::Destroy(SBDebugger &debugger) { + LLDB_INSTRUMENT_VA(debugger); + + Debugger::Destroy(debugger.m_opaque_sp); + + if (debugger.m_opaque_sp.get() != nullptr) + debugger.m_opaque_sp.reset(); +} + +void SBDebugger::MemoryPressureDetected() { + LLDB_INSTRUMENT(); + + // Since this function can be call asynchronously, we allow it to be non- + // mandatory. We have seen deadlocks with this function when called so we + // need to safeguard against this until we can determine what is causing the + // deadlocks. + + const bool mandatory = false; + + ModuleList::RemoveOrphanSharedModules(mandatory); +} + +bool SBDebugger::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBDebugger::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} + +void SBDebugger::SetAsync(bool b) { + LLDB_INSTRUMENT_VA(this, b); + + if (m_opaque_sp) + m_opaque_sp->SetAsyncExecution(b); +} + +bool SBDebugger::GetAsync() { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_sp ? m_opaque_sp->GetAsyncExecution() : false); +} + +void SBDebugger::SkipLLDBInitFiles(bool b) { + LLDB_INSTRUMENT_VA(this, b); + + if (m_opaque_sp) + m_opaque_sp->GetCommandInterpreter().SkipLLDBInitFiles(b); +} + +void SBDebugger::SkipAppInitFiles(bool b) { + LLDB_INSTRUMENT_VA(this, b); + + if (m_opaque_sp) + m_opaque_sp->GetCommandInterpreter().SkipAppInitFiles(b); +} + +void SBDebugger::SetInputFileHandle(FILE *fh, bool transfer_ownership) { + LLDB_INSTRUMENT_VA(this, fh, transfer_ownership); + if (m_opaque_sp) + m_opaque_sp->SetInputFile( + (FileSP)std::make_shared<NativeFile>(fh, transfer_ownership)); +} + +SBError SBDebugger::SetInputString(const char *data) { + LLDB_INSTRUMENT_VA(this, data); + SBError sb_error; + if (data == nullptr) { + sb_error.SetErrorString("String data is null"); + return sb_error; + } + + size_t size = strlen(data); + if (size == 0) { + sb_error.SetErrorString("String data is empty"); + return sb_error; + } + + if (!m_opaque_sp) { + sb_error.SetErrorString("invalid debugger"); + return sb_error; + } + + sb_error.SetError(m_opaque_sp->SetInputString(data)); + return sb_error; +} + +// Shouldn't really be settable after initialization as this could cause lots +// of problems; don't want users trying to switch modes in the middle of a +// debugging session. +SBError SBDebugger::SetInputFile(SBFile file) { + LLDB_INSTRUMENT_VA(this, file); + + SBError error; + if (!m_opaque_sp) { + error.ref().SetErrorString("invalid debugger"); + return error; + } + if (!file) { + error.ref().SetErrorString("invalid file"); + return error; + } + m_opaque_sp->SetInputFile(file.m_opaque_sp); + return error; +} + +SBError SBDebugger::SetInputFile(FileSP file_sp) { + LLDB_INSTRUMENT_VA(this, file_sp); + return SetInputFile(SBFile(file_sp)); +} + +SBError SBDebugger::SetOutputFile(FileSP file_sp) { + LLDB_INSTRUMENT_VA(this, file_sp); + return SetOutputFile(SBFile(file_sp)); +} + +void SBDebugger::SetOutputFileHandle(FILE *fh, bool transfer_ownership) { + LLDB_INSTRUMENT_VA(this, fh, transfer_ownership); + SetOutputFile((FileSP)std::make_shared<NativeFile>(fh, transfer_ownership)); +} + +SBError SBDebugger::SetOutputFile(SBFile file) { + LLDB_INSTRUMENT_VA(this, file); + SBError error; + if (!m_opaque_sp) { + error.ref().SetErrorString("invalid debugger"); + return error; + } + if (!file) { + error.ref().SetErrorString("invalid file"); + return error; + } + m_opaque_sp->SetOutputFile(file.m_opaque_sp); + return error; +} + +void SBDebugger::SetErrorFileHandle(FILE *fh, bool transfer_ownership) { + LLDB_INSTRUMENT_VA(this, fh, transfer_ownership); + SetErrorFile((FileSP)std::make_shared<NativeFile>(fh, transfer_ownership)); +} + +SBError SBDebugger::SetErrorFile(FileSP file_sp) { + LLDB_INSTRUMENT_VA(this, file_sp); + return SetErrorFile(SBFile(file_sp)); +} + +SBError SBDebugger::SetErrorFile(SBFile file) { + LLDB_INSTRUMENT_VA(this, file); + SBError error; + if (!m_opaque_sp) { + error.ref().SetErrorString("invalid debugger"); + return error; + } + if (!file) { + error.ref().SetErrorString("invalid file"); + return error; + } + m_opaque_sp->SetErrorFile(file.m_opaque_sp); + return error; +} + +lldb::SBStructuredData SBDebugger::GetSetting(const char *setting) { + LLDB_INSTRUMENT_VA(this, setting); + + SBStructuredData data; + if (!m_opaque_sp) + return data; + + StreamString json_strm; + ExecutionContext exe_ctx( + m_opaque_sp->GetCommandInterpreter().GetExecutionContext()); + if (setting && strlen(setting) > 0) + m_opaque_sp->DumpPropertyValue(&exe_ctx, json_strm, setting, + /*dump_mask*/ 0, + /*is_json*/ true); + else + m_opaque_sp->DumpAllPropertyValues(&exe_ctx, json_strm, /*dump_mask*/ 0, + /*is_json*/ true); + + data.m_impl_up->SetObjectSP(StructuredData::ParseJSON(json_strm.GetString())); + return data; +} + +FILE *SBDebugger::GetInputFileHandle() { + LLDB_INSTRUMENT_VA(this); + if (m_opaque_sp) { + File &file_sp = m_opaque_sp->GetInputFile(); + return file_sp.GetStream(); + } + return nullptr; +} + +SBFile SBDebugger::GetInputFile() { + LLDB_INSTRUMENT_VA(this); + if (m_opaque_sp) { + return SBFile(m_opaque_sp->GetInputFileSP()); + } + return SBFile(); +} + +FILE *SBDebugger::GetOutputFileHandle() { + LLDB_INSTRUMENT_VA(this); + if (m_opaque_sp) { + StreamFile &stream_file = m_opaque_sp->GetOutputStream(); + return stream_file.GetFile().GetStream(); + } + return nullptr; +} + +SBFile SBDebugger::GetOutputFile() { + LLDB_INSTRUMENT_VA(this); + if (m_opaque_sp) { + SBFile file(m_opaque_sp->GetOutputStream().GetFileSP()); + return file; + } + return SBFile(); +} + +FILE *SBDebugger::GetErrorFileHandle() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) { + StreamFile &stream_file = m_opaque_sp->GetErrorStream(); + return stream_file.GetFile().GetStream(); + } + return nullptr; +} + +SBFile SBDebugger::GetErrorFile() { + LLDB_INSTRUMENT_VA(this); + SBFile file; + if (m_opaque_sp) { + SBFile file(m_opaque_sp->GetErrorStream().GetFileSP()); + return file; + } + return SBFile(); +} + +void SBDebugger::SaveInputTerminalState() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + m_opaque_sp->SaveInputTerminalState(); +} + +void SBDebugger::RestoreInputTerminalState() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + m_opaque_sp->RestoreInputTerminalState(); +} +SBCommandInterpreter SBDebugger::GetCommandInterpreter() { + LLDB_INSTRUMENT_VA(this); + + SBCommandInterpreter sb_interpreter; + if (m_opaque_sp) + sb_interpreter.reset(&m_opaque_sp->GetCommandInterpreter()); + + return sb_interpreter; +} + +void SBDebugger::HandleCommand(const char *command) { + LLDB_INSTRUMENT_VA(this, command); + + if (m_opaque_sp) { + TargetSP target_sp(m_opaque_sp->GetSelectedTarget()); + std::unique_lock<std::recursive_mutex> lock; + if (target_sp) + lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex()); + + SBCommandInterpreter sb_interpreter(GetCommandInterpreter()); + SBCommandReturnObject result; + + sb_interpreter.HandleCommand(command, result, false); + + result.PutError(m_opaque_sp->GetErrorStream().GetFileSP()); + result.PutOutput(m_opaque_sp->GetOutputStream().GetFileSP()); + + if (!m_opaque_sp->GetAsyncExecution()) { + SBProcess process(GetCommandInterpreter().GetProcess()); + ProcessSP process_sp(process.GetSP()); + if (process_sp) { + EventSP event_sp; + ListenerSP lldb_listener_sp = m_opaque_sp->GetListener(); + while (lldb_listener_sp->GetEventForBroadcaster( + process_sp.get(), event_sp, std::chrono::seconds(0))) { + SBEvent event(event_sp); + HandleProcessEvent(process, event, GetOutputFile(), GetErrorFile()); + } + } + } + } +} + +SBListener SBDebugger::GetListener() { + LLDB_INSTRUMENT_VA(this); + + SBListener sb_listener; + if (m_opaque_sp) + sb_listener.reset(m_opaque_sp->GetListener()); + + return sb_listener; +} + +void SBDebugger::HandleProcessEvent(const SBProcess &process, + const SBEvent &event, SBFile out, + SBFile err) { + LLDB_INSTRUMENT_VA(this, process, event, out, err); + + return HandleProcessEvent(process, event, out.m_opaque_sp, err.m_opaque_sp); +} + +void SBDebugger::HandleProcessEvent(const SBProcess &process, + const SBEvent &event, FILE *out, + FILE *err) { + LLDB_INSTRUMENT_VA(this, process, event, out, err); + + FileSP outfile = std::make_shared<NativeFile>(out, false); + FileSP errfile = std::make_shared<NativeFile>(err, false); + return HandleProcessEvent(process, event, outfile, errfile); +} + +void SBDebugger::HandleProcessEvent(const SBProcess &process, + const SBEvent &event, FileSP out_sp, + FileSP err_sp) { + + LLDB_INSTRUMENT_VA(this, process, event, out_sp, err_sp); + + if (!process.IsValid()) + return; + + TargetSP target_sp(process.GetTarget().GetSP()); + if (!target_sp) + return; + + const uint32_t event_type = event.GetType(); + char stdio_buffer[1024]; + size_t len; + + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + + if (event_type & + (Process::eBroadcastBitSTDOUT | Process::eBroadcastBitStateChanged)) { + // Drain stdout when we stop just in case we have any bytes + while ((len = process.GetSTDOUT(stdio_buffer, sizeof(stdio_buffer))) > 0) + if (out_sp) + out_sp->Write(stdio_buffer, len); + } + + if (event_type & + (Process::eBroadcastBitSTDERR | Process::eBroadcastBitStateChanged)) { + // Drain stderr when we stop just in case we have any bytes + while ((len = process.GetSTDERR(stdio_buffer, sizeof(stdio_buffer))) > 0) + if (err_sp) + err_sp->Write(stdio_buffer, len); + } + + if (event_type & Process::eBroadcastBitStateChanged) { + StateType event_state = SBProcess::GetStateFromEvent(event); + + if (event_state == eStateInvalid) + return; + + bool is_stopped = StateIsStoppedState(event_state); + if (!is_stopped) + process.ReportEventState(event, out_sp); + } +} + +SBSourceManager SBDebugger::GetSourceManager() { + LLDB_INSTRUMENT_VA(this); + + SBSourceManager sb_source_manager(*this); + return sb_source_manager; +} + +bool SBDebugger::GetDefaultArchitecture(char *arch_name, size_t arch_name_len) { + LLDB_INSTRUMENT_VA(arch_name, arch_name_len); + + if (arch_name && arch_name_len) { + ArchSpec default_arch = Target::GetDefaultArchitecture(); + + if (default_arch.IsValid()) { + const std::string &triple_str = default_arch.GetTriple().str(); + if (!triple_str.empty()) + ::snprintf(arch_name, arch_name_len, "%s", triple_str.c_str()); + else + ::snprintf(arch_name, arch_name_len, "%s", + default_arch.GetArchitectureName()); + return true; + } + } + if (arch_name && arch_name_len) + arch_name[0] = '\0'; + return false; +} + +bool SBDebugger::SetDefaultArchitecture(const char *arch_name) { + LLDB_INSTRUMENT_VA(arch_name); + + if (arch_name) { + ArchSpec arch(arch_name); + if (arch.IsValid()) { + Target::SetDefaultArchitecture(arch); + return true; + } + } + return false; +} + +ScriptLanguage +SBDebugger::GetScriptingLanguage(const char *script_language_name) { + LLDB_INSTRUMENT_VA(this, script_language_name); + + if (!script_language_name) + return eScriptLanguageDefault; + return OptionArgParser::ToScriptLanguage( + llvm::StringRef(script_language_name), eScriptLanguageDefault, nullptr); +} + +SBStructuredData +SBDebugger::GetScriptInterpreterInfo(lldb::ScriptLanguage language) { + LLDB_INSTRUMENT_VA(this, language); + SBStructuredData data; + if (m_opaque_sp) { + lldb_private::ScriptInterpreter *interp = + m_opaque_sp->GetScriptInterpreter(language); + if (interp) { + data.m_impl_up->SetObjectSP(interp->GetInterpreterInfo()); + } + } + return data; +} + +const char *SBDebugger::GetVersionString() { + LLDB_INSTRUMENT(); + + return lldb_private::GetVersion(); +} + +const char *SBDebugger::StateAsCString(StateType state) { + LLDB_INSTRUMENT_VA(state); + + return lldb_private::StateAsCString(state); +} + +static void AddBoolConfigEntry(StructuredData::Dictionary &dict, + llvm::StringRef name, bool value, + llvm::StringRef description) { + auto entry_up = std::make_unique<StructuredData::Dictionary>(); + entry_up->AddBooleanItem("value", value); + entry_up->AddStringItem("description", description); + dict.AddItem(name, std::move(entry_up)); +} + +static void AddLLVMTargets(StructuredData::Dictionary &dict) { + auto array_up = std::make_unique<StructuredData::Array>(); +#define LLVM_TARGET(target) \ + array_up->AddItem(std::make_unique<StructuredData::String>(#target)); +#include "llvm/Config/Targets.def" + auto entry_up = std::make_unique<StructuredData::Dictionary>(); + entry_up->AddItem("value", std::move(array_up)); + entry_up->AddStringItem("description", "A list of configured LLVM targets."); + dict.AddItem("targets", std::move(entry_up)); +} + +SBStructuredData SBDebugger::GetBuildConfiguration() { + LLDB_INSTRUMENT(); + + auto config_up = std::make_unique<StructuredData::Dictionary>(); + AddBoolConfigEntry( + *config_up, "xml", XMLDocument::XMLEnabled(), + "A boolean value that indicates if XML support is enabled in LLDB"); + AddBoolConfigEntry( + *config_up, "curses", LLDB_ENABLE_CURSES, + "A boolean value that indicates if curses support is enabled in LLDB"); + AddBoolConfigEntry( + *config_up, "editline", LLDB_ENABLE_LIBEDIT, + "A boolean value that indicates if editline support is enabled in LLDB"); + AddBoolConfigEntry(*config_up, "editline_wchar", LLDB_EDITLINE_USE_WCHAR, + "A boolean value that indicates if editline wide " + "characters support is enabled in LLDB"); + AddBoolConfigEntry( + *config_up, "lzma", LLDB_ENABLE_LZMA, + "A boolean value that indicates if lzma support is enabled in LLDB"); + AddBoolConfigEntry( + *config_up, "python", LLDB_ENABLE_PYTHON, + "A boolean value that indicates if python support is enabled in LLDB"); + AddBoolConfigEntry( + *config_up, "lua", LLDB_ENABLE_LUA, + "A boolean value that indicates if lua support is enabled in LLDB"); + AddBoolConfigEntry(*config_up, "fbsdvmcore", LLDB_ENABLE_FBSDVMCORE, + "A boolean value that indicates if fbsdvmcore support is " + "enabled in LLDB"); + AddLLVMTargets(*config_up); + + SBStructuredData data; + data.m_impl_up->SetObjectSP(std::move(config_up)); + return data; +} + +bool SBDebugger::StateIsRunningState(StateType state) { + LLDB_INSTRUMENT_VA(state); + + const bool result = lldb_private::StateIsRunningState(state); + + return result; +} + +bool SBDebugger::StateIsStoppedState(StateType state) { + LLDB_INSTRUMENT_VA(state); + + const bool result = lldb_private::StateIsStoppedState(state, false); + + return result; +} + +lldb::SBTarget SBDebugger::CreateTarget(const char *filename, + const char *target_triple, + const char *platform_name, + bool add_dependent_modules, + lldb::SBError &sb_error) { + LLDB_INSTRUMENT_VA(this, filename, target_triple, platform_name, + add_dependent_modules, sb_error); + + SBTarget sb_target; + TargetSP target_sp; + if (m_opaque_sp) { + sb_error.Clear(); + OptionGroupPlatform platform_options(false); + platform_options.SetPlatformName(platform_name); + + sb_error.ref() = m_opaque_sp->GetTargetList().CreateTarget( + *m_opaque_sp, filename, target_triple, + add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo, + &platform_options, target_sp); + + if (sb_error.Success()) + sb_target.SetSP(target_sp); + } else { + sb_error.SetErrorString("invalid debugger"); + } + + Log *log = GetLog(LLDBLog::API); + LLDB_LOGF(log, + "SBDebugger(%p)::CreateTarget (filename=\"%s\", triple=%s, " + "platform_name=%s, add_dependent_modules=%u, error=%s) => " + "SBTarget(%p)", + static_cast<void *>(m_opaque_sp.get()), filename, target_triple, + platform_name, add_dependent_modules, sb_error.GetCString(), + static_cast<void *>(target_sp.get())); + + return sb_target; +} + +SBTarget +SBDebugger::CreateTargetWithFileAndTargetTriple(const char *filename, + const char *target_triple) { + LLDB_INSTRUMENT_VA(this, filename, target_triple); + + SBTarget sb_target; + TargetSP target_sp; + if (m_opaque_sp) { + const bool add_dependent_modules = true; + Status error(m_opaque_sp->GetTargetList().CreateTarget( + *m_opaque_sp, filename, target_triple, + add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo, nullptr, + target_sp)); + sb_target.SetSP(target_sp); + } + + Log *log = GetLog(LLDBLog::API); + LLDB_LOGF(log, + "SBDebugger(%p)::CreateTargetWithFileAndTargetTriple " + "(filename=\"%s\", triple=%s) => SBTarget(%p)", + static_cast<void *>(m_opaque_sp.get()), filename, target_triple, + static_cast<void *>(target_sp.get())); + + return sb_target; +} + +SBTarget SBDebugger::CreateTargetWithFileAndArch(const char *filename, + const char *arch_cstr) { + LLDB_INSTRUMENT_VA(this, filename, arch_cstr); + + Log *log = GetLog(LLDBLog::API); + + SBTarget sb_target; + TargetSP target_sp; + if (m_opaque_sp) { + Status error; + if (arch_cstr == nullptr) { + // The version of CreateTarget that takes an ArchSpec won't accept an + // empty ArchSpec, so when the arch hasn't been specified, we need to + // call the target triple version. + error = m_opaque_sp->GetTargetList().CreateTarget( + *m_opaque_sp, filename, arch_cstr, eLoadDependentsYes, nullptr, + target_sp); + } else { + PlatformSP platform_sp = + m_opaque_sp->GetPlatformList().GetSelectedPlatform(); + ArchSpec arch = + Platform::GetAugmentedArchSpec(platform_sp.get(), arch_cstr); + if (arch.IsValid()) + error = m_opaque_sp->GetTargetList().CreateTarget( + *m_opaque_sp, filename, arch, eLoadDependentsYes, platform_sp, + target_sp); + else + error.SetErrorStringWithFormat("invalid arch_cstr: %s", arch_cstr); + } + if (error.Success()) + sb_target.SetSP(target_sp); + } + + LLDB_LOGF(log, + "SBDebugger(%p)::CreateTargetWithFileAndArch (filename=\"%s\", " + "arch=%s) => SBTarget(%p)", + static_cast<void *>(m_opaque_sp.get()), + filename ? filename : "<unspecified>", + arch_cstr ? arch_cstr : "<unspecified>", + static_cast<void *>(target_sp.get())); + + return sb_target; +} + +SBTarget SBDebugger::CreateTarget(const char *filename) { + LLDB_INSTRUMENT_VA(this, filename); + + SBTarget sb_target; + TargetSP target_sp; + if (m_opaque_sp) { + Status error; + const bool add_dependent_modules = true; + error = m_opaque_sp->GetTargetList().CreateTarget( + *m_opaque_sp, filename, "", + add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo, nullptr, + target_sp); + + if (error.Success()) + sb_target.SetSP(target_sp); + } + Log *log = GetLog(LLDBLog::API); + LLDB_LOGF(log, + "SBDebugger(%p)::CreateTarget (filename=\"%s\") => SBTarget(%p)", + static_cast<void *>(m_opaque_sp.get()), filename, + static_cast<void *>(target_sp.get())); + return sb_target; +} + +SBTarget SBDebugger::GetDummyTarget() { + LLDB_INSTRUMENT_VA(this); + + SBTarget sb_target; + if (m_opaque_sp) { + sb_target.SetSP(m_opaque_sp->GetDummyTarget().shared_from_this()); + } + Log *log = GetLog(LLDBLog::API); + LLDB_LOGF(log, "SBDebugger(%p)::GetDummyTarget() => SBTarget(%p)", + static_cast<void *>(m_opaque_sp.get()), + static_cast<void *>(sb_target.GetSP().get())); + return sb_target; +} + +bool SBDebugger::DeleteTarget(lldb::SBTarget &target) { + LLDB_INSTRUMENT_VA(this, target); + + bool result = false; + if (m_opaque_sp) { + TargetSP target_sp(target.GetSP()); + if (target_sp) { + // No need to lock, the target list is thread safe + result = m_opaque_sp->GetTargetList().DeleteTarget(target_sp); + target_sp->Destroy(); + target.Clear(); + } + } + + Log *log = GetLog(LLDBLog::API); + LLDB_LOGF(log, "SBDebugger(%p)::DeleteTarget (SBTarget(%p)) => %i", + static_cast<void *>(m_opaque_sp.get()), + static_cast<void *>(target.m_opaque_sp.get()), result); + + return result; +} + +SBTarget SBDebugger::GetTargetAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBTarget sb_target; + if (m_opaque_sp) { + // No need to lock, the target list is thread safe + sb_target.SetSP(m_opaque_sp->GetTargetList().GetTargetAtIndex(idx)); + } + return sb_target; +} + +uint32_t SBDebugger::GetIndexOfTarget(lldb::SBTarget target) { + LLDB_INSTRUMENT_VA(this, target); + + lldb::TargetSP target_sp = target.GetSP(); + if (!target_sp) + return UINT32_MAX; + + if (!m_opaque_sp) + return UINT32_MAX; + + return m_opaque_sp->GetTargetList().GetIndexOfTarget(target.GetSP()); +} + +SBTarget SBDebugger::FindTargetWithProcessID(lldb::pid_t pid) { + LLDB_INSTRUMENT_VA(this, pid); + + SBTarget sb_target; + if (m_opaque_sp) { + // No need to lock, the target list is thread safe + sb_target.SetSP(m_opaque_sp->GetTargetList().FindTargetWithProcessID(pid)); + } + return sb_target; +} + +SBTarget SBDebugger::FindTargetWithFileAndArch(const char *filename, + const char *arch_name) { + LLDB_INSTRUMENT_VA(this, filename, arch_name); + + SBTarget sb_target; + if (m_opaque_sp && filename && filename[0]) { + // No need to lock, the target list is thread safe + ArchSpec arch = Platform::GetAugmentedArchSpec( + m_opaque_sp->GetPlatformList().GetSelectedPlatform().get(), arch_name); + TargetSP target_sp( + m_opaque_sp->GetTargetList().FindTargetWithExecutableAndArchitecture( + FileSpec(filename), arch_name ? &arch : nullptr)); + sb_target.SetSP(target_sp); + } + return sb_target; +} + +SBTarget SBDebugger::FindTargetWithLLDBProcess(const ProcessSP &process_sp) { + SBTarget sb_target; + if (m_opaque_sp) { + // No need to lock, the target list is thread safe + sb_target.SetSP( + m_opaque_sp->GetTargetList().FindTargetWithProcess(process_sp.get())); + } + return sb_target; +} + +uint32_t SBDebugger::GetNumTargets() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) { + // No need to lock, the target list is thread safe + return m_opaque_sp->GetTargetList().GetNumTargets(); + } + return 0; +} + +SBTarget SBDebugger::GetSelectedTarget() { + LLDB_INSTRUMENT_VA(this); + + Log *log = GetLog(LLDBLog::API); + + SBTarget sb_target; + TargetSP target_sp; + if (m_opaque_sp) { + // No need to lock, the target list is thread safe + target_sp = m_opaque_sp->GetTargetList().GetSelectedTarget(); + sb_target.SetSP(target_sp); + } + + if (log) { + SBStream sstr; + sb_target.GetDescription(sstr, eDescriptionLevelBrief); + LLDB_LOGF(log, "SBDebugger(%p)::GetSelectedTarget () => SBTarget(%p): %s", + static_cast<void *>(m_opaque_sp.get()), + static_cast<void *>(target_sp.get()), sstr.GetData()); + } + + return sb_target; +} + +void SBDebugger::SetSelectedTarget(SBTarget &sb_target) { + LLDB_INSTRUMENT_VA(this, sb_target); + + Log *log = GetLog(LLDBLog::API); + + TargetSP target_sp(sb_target.GetSP()); + if (m_opaque_sp) { + m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp); + } + if (log) { + SBStream sstr; + sb_target.GetDescription(sstr, eDescriptionLevelBrief); + LLDB_LOGF(log, "SBDebugger(%p)::SetSelectedTarget () => SBTarget(%p): %s", + static_cast<void *>(m_opaque_sp.get()), + static_cast<void *>(target_sp.get()), sstr.GetData()); + } +} + +SBPlatform SBDebugger::GetSelectedPlatform() { + LLDB_INSTRUMENT_VA(this); + + Log *log = GetLog(LLDBLog::API); + + SBPlatform sb_platform; + DebuggerSP debugger_sp(m_opaque_sp); + if (debugger_sp) { + sb_platform.SetSP(debugger_sp->GetPlatformList().GetSelectedPlatform()); + } + LLDB_LOGF(log, "SBDebugger(%p)::GetSelectedPlatform () => SBPlatform(%p): %s", + static_cast<void *>(m_opaque_sp.get()), + static_cast<void *>(sb_platform.GetSP().get()), + sb_platform.GetName()); + return sb_platform; +} + +void SBDebugger::SetSelectedPlatform(SBPlatform &sb_platform) { + LLDB_INSTRUMENT_VA(this, sb_platform); + + Log *log = GetLog(LLDBLog::API); + + DebuggerSP debugger_sp(m_opaque_sp); + if (debugger_sp) { + debugger_sp->GetPlatformList().SetSelectedPlatform(sb_platform.GetSP()); + } + + LLDB_LOGF(log, "SBDebugger(%p)::SetSelectedPlatform (SBPlatform(%p) %s)", + static_cast<void *>(m_opaque_sp.get()), + static_cast<void *>(sb_platform.GetSP().get()), + sb_platform.GetName()); +} + +uint32_t SBDebugger::GetNumPlatforms() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) { + // No need to lock, the platform list is thread safe + return m_opaque_sp->GetPlatformList().GetSize(); + } + return 0; +} + +SBPlatform SBDebugger::GetPlatformAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBPlatform sb_platform; + if (m_opaque_sp) { + // No need to lock, the platform list is thread safe + sb_platform.SetSP(m_opaque_sp->GetPlatformList().GetAtIndex(idx)); + } + return sb_platform; +} + +uint32_t SBDebugger::GetNumAvailablePlatforms() { + LLDB_INSTRUMENT_VA(this); + + uint32_t idx = 0; + while (true) { + if (PluginManager::GetPlatformPluginNameAtIndex(idx).empty()) { + break; + } + ++idx; + } + // +1 for the host platform, which should always appear first in the list. + return idx + 1; +} + +SBStructuredData SBDebugger::GetAvailablePlatformInfoAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBStructuredData data; + auto platform_dict = std::make_unique<StructuredData::Dictionary>(); + llvm::StringRef name_str("name"), desc_str("description"); + + if (idx == 0) { + PlatformSP host_platform_sp(Platform::GetHostPlatform()); + platform_dict->AddStringItem(name_str, host_platform_sp->GetPluginName()); + platform_dict->AddStringItem( + desc_str, llvm::StringRef(host_platform_sp->GetDescription())); + } else if (idx > 0) { + llvm::StringRef plugin_name = + PluginManager::GetPlatformPluginNameAtIndex(idx - 1); + if (plugin_name.empty()) { + return data; + } + platform_dict->AddStringItem(name_str, llvm::StringRef(plugin_name)); + + llvm::StringRef plugin_desc = + PluginManager::GetPlatformPluginDescriptionAtIndex(idx - 1); + platform_dict->AddStringItem(desc_str, llvm::StringRef(plugin_desc)); + } + + data.m_impl_up->SetObjectSP( + StructuredData::ObjectSP(platform_dict.release())); + return data; +} + +void SBDebugger::DispatchInput(void *baton, const void *data, size_t data_len) { + LLDB_INSTRUMENT_VA(this, baton, data, data_len); + + DispatchInput(data, data_len); +} + +void SBDebugger::DispatchInput(const void *data, size_t data_len) { + LLDB_INSTRUMENT_VA(this, data, data_len); + + // Log *log(GetLog (LLDBLog::API)); + // + // if (log) + // LLDB_LOGF(log, "SBDebugger(%p)::DispatchInput (data=\"%.*s\", + // size_t=%" PRIu64 ")", + // m_opaque_sp.get(), + // (int) data_len, + // (const char *) data, + // (uint64_t)data_len); + // + // if (m_opaque_sp) + // m_opaque_sp->DispatchInput ((const char *) data, data_len); +} + +void SBDebugger::DispatchInputInterrupt() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + m_opaque_sp->DispatchInputInterrupt(); +} + +void SBDebugger::DispatchInputEndOfFile() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + m_opaque_sp->DispatchInputEndOfFile(); +} + +void SBDebugger::PushInputReader(SBInputReader &reader) { + LLDB_INSTRUMENT_VA(this, reader); +} + +void SBDebugger::RunCommandInterpreter(bool auto_handle_events, + bool spawn_thread) { + LLDB_INSTRUMENT_VA(this, auto_handle_events, spawn_thread); + + if (m_opaque_sp) { + CommandInterpreterRunOptions options; + options.SetAutoHandleEvents(auto_handle_events); + options.SetSpawnThread(spawn_thread); + m_opaque_sp->GetCommandInterpreter().RunCommandInterpreter(options); + } +} + +void SBDebugger::RunCommandInterpreter(bool auto_handle_events, + bool spawn_thread, + SBCommandInterpreterRunOptions &options, + int &num_errors, bool &quit_requested, + bool &stopped_for_crash) + +{ + LLDB_INSTRUMENT_VA(this, auto_handle_events, spawn_thread, options, + num_errors, quit_requested, stopped_for_crash); + + if (m_opaque_sp) { + options.SetAutoHandleEvents(auto_handle_events); + options.SetSpawnThread(spawn_thread); + CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter(); + CommandInterpreterRunResult result = + interp.RunCommandInterpreter(options.ref()); + num_errors = result.GetNumErrors(); + quit_requested = + result.IsResult(lldb::eCommandInterpreterResultQuitRequested); + stopped_for_crash = + result.IsResult(lldb::eCommandInterpreterResultInferiorCrash); + } +} + +SBCommandInterpreterRunResult SBDebugger::RunCommandInterpreter( + const SBCommandInterpreterRunOptions &options) { + LLDB_INSTRUMENT_VA(this, options); + + if (!m_opaque_sp) + return SBCommandInterpreterRunResult(); + + CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter(); + CommandInterpreterRunResult result = + interp.RunCommandInterpreter(options.ref()); + + return SBCommandInterpreterRunResult(result); +} + +SBError SBDebugger::RunREPL(lldb::LanguageType language, + const char *repl_options) { + LLDB_INSTRUMENT_VA(this, language, repl_options); + + SBError error; + if (m_opaque_sp) + error.ref() = m_opaque_sp->RunREPL(language, repl_options); + else + error.SetErrorString("invalid debugger"); + return error; +} + +void SBDebugger::reset(const DebuggerSP &debugger_sp) { + m_opaque_sp = debugger_sp; +} + +Debugger *SBDebugger::get() const { return m_opaque_sp.get(); } + +Debugger &SBDebugger::ref() const { + assert(m_opaque_sp.get()); + return *m_opaque_sp; +} + +const lldb::DebuggerSP &SBDebugger::get_sp() const { return m_opaque_sp; } + +SBDebugger SBDebugger::FindDebuggerWithID(int id) { + LLDB_INSTRUMENT_VA(id); + + // No need to lock, the debugger list is thread safe + SBDebugger sb_debugger; + DebuggerSP debugger_sp = Debugger::FindDebuggerWithID(id); + if (debugger_sp) + sb_debugger.reset(debugger_sp); + return sb_debugger; +} + +const char *SBDebugger::GetInstanceName() { + LLDB_INSTRUMENT_VA(this); + + if (!m_opaque_sp) + return nullptr; + + return ConstString(m_opaque_sp->GetInstanceName()).AsCString(); +} + +SBError SBDebugger::SetInternalVariable(const char *var_name, const char *value, + const char *debugger_instance_name) { + LLDB_INSTRUMENT_VA(var_name, value, debugger_instance_name); + + SBError sb_error; + DebuggerSP debugger_sp( + Debugger::FindDebuggerWithInstanceName(debugger_instance_name)); + Status error; + if (debugger_sp) { + ExecutionContext exe_ctx( + debugger_sp->GetCommandInterpreter().GetExecutionContext()); + error = debugger_sp->SetPropertyValue(&exe_ctx, eVarSetOperationAssign, + var_name, value); + } else { + error.SetErrorStringWithFormat("invalid debugger instance name '%s'", + debugger_instance_name); + } + if (error.Fail()) + sb_error.SetError(error); + return sb_error; +} + +SBStringList +SBDebugger::GetInternalVariableValue(const char *var_name, + const char *debugger_instance_name) { + LLDB_INSTRUMENT_VA(var_name, debugger_instance_name); + + DebuggerSP debugger_sp( + Debugger::FindDebuggerWithInstanceName(debugger_instance_name)); + Status error; + if (debugger_sp) { + ExecutionContext exe_ctx( + debugger_sp->GetCommandInterpreter().GetExecutionContext()); + lldb::OptionValueSP value_sp( + debugger_sp->GetPropertyValue(&exe_ctx, var_name, error)); + if (value_sp) { + StreamString value_strm; + value_sp->DumpValue(&exe_ctx, value_strm, OptionValue::eDumpOptionValue); + const std::string &value_str = std::string(value_strm.GetString()); + if (!value_str.empty()) { + StringList string_list; + string_list.SplitIntoLines(value_str); + return SBStringList(&string_list); + } + } + } + return SBStringList(); +} + +uint32_t SBDebugger::GetTerminalWidth() const { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_sp ? m_opaque_sp->GetTerminalWidth() : 0); +} + +void SBDebugger::SetTerminalWidth(uint32_t term_width) { + LLDB_INSTRUMENT_VA(this, term_width); + + if (m_opaque_sp) + m_opaque_sp->SetTerminalWidth(term_width); +} + +const char *SBDebugger::GetPrompt() const { + LLDB_INSTRUMENT_VA(this); + + Log *log = GetLog(LLDBLog::API); + + LLDB_LOG(log, "SBDebugger({0:x})::GetPrompt () => \"{1}\"", + static_cast<void *>(m_opaque_sp.get()), + (m_opaque_sp ? m_opaque_sp->GetPrompt() : "")); + + return (m_opaque_sp ? ConstString(m_opaque_sp->GetPrompt()).GetCString() + : nullptr); +} + +void SBDebugger::SetPrompt(const char *prompt) { + LLDB_INSTRUMENT_VA(this, prompt); + + if (m_opaque_sp) + m_opaque_sp->SetPrompt(llvm::StringRef(prompt)); +} + +const char *SBDebugger::GetReproducerPath() const { + LLDB_INSTRUMENT_VA(this); + + return "GetReproducerPath has been deprecated"; +} + +ScriptLanguage SBDebugger::GetScriptLanguage() const { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_sp ? m_opaque_sp->GetScriptLanguage() : eScriptLanguageNone); +} + +void SBDebugger::SetScriptLanguage(ScriptLanguage script_lang) { + LLDB_INSTRUMENT_VA(this, script_lang); + + if (m_opaque_sp) { + m_opaque_sp->SetScriptLanguage(script_lang); + } +} + +LanguageType SBDebugger::GetREPLLanguage() const { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_sp ? m_opaque_sp->GetREPLLanguage() : eLanguageTypeUnknown); +} + +void SBDebugger::SetREPLLanguage(LanguageType repl_lang) { + LLDB_INSTRUMENT_VA(this, repl_lang); + + if (m_opaque_sp) { + m_opaque_sp->SetREPLLanguage(repl_lang); + } +} + +bool SBDebugger::SetUseExternalEditor(bool value) { + LLDB_INSTRUMENT_VA(this, value); + + return (m_opaque_sp ? m_opaque_sp->SetUseExternalEditor(value) : false); +} + +bool SBDebugger::GetUseExternalEditor() { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_sp ? m_opaque_sp->GetUseExternalEditor() : false); +} + +bool SBDebugger::SetUseColor(bool value) { + LLDB_INSTRUMENT_VA(this, value); + + return (m_opaque_sp ? m_opaque_sp->SetUseColor(value) : false); +} + +bool SBDebugger::GetUseColor() const { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_sp ? m_opaque_sp->GetUseColor() : false); +} + +bool SBDebugger::SetUseSourceCache(bool value) { + LLDB_INSTRUMENT_VA(this, value); + + return (m_opaque_sp ? m_opaque_sp->SetUseSourceCache(value) : false); +} + +bool SBDebugger::GetUseSourceCache() const { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_sp ? m_opaque_sp->GetUseSourceCache() : false); +} + +bool SBDebugger::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + if (m_opaque_sp) { + const char *name = m_opaque_sp->GetInstanceName().c_str(); + user_id_t id = m_opaque_sp->GetID(); + strm.Printf("Debugger (instance: \"%s\", id: %" PRIu64 ")", name, id); + } else + strm.PutCString("No value"); + + return true; +} + +user_id_t SBDebugger::GetID() { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_sp ? m_opaque_sp->GetID() : LLDB_INVALID_UID); +} + +SBError SBDebugger::SetCurrentPlatform(const char *platform_name_cstr) { + LLDB_INSTRUMENT_VA(this, platform_name_cstr); + + SBError sb_error; + if (m_opaque_sp) { + if (platform_name_cstr && platform_name_cstr[0]) { + PlatformList &platforms = m_opaque_sp->GetPlatformList(); + if (PlatformSP platform_sp = platforms.GetOrCreate(platform_name_cstr)) + platforms.SetSelectedPlatform(platform_sp); + else + sb_error.ref().SetErrorString("platform not found"); + } else { + sb_error.ref().SetErrorString("invalid platform name"); + } + } else { + sb_error.ref().SetErrorString("invalid debugger"); + } + return sb_error; +} + +bool SBDebugger::SetCurrentPlatformSDKRoot(const char *sysroot) { + LLDB_INSTRUMENT_VA(this, sysroot); + + if (SBPlatform platform = GetSelectedPlatform()) { + platform.SetSDKRoot(sysroot); + return true; + } + return false; +} + +bool SBDebugger::GetCloseInputOnEOF() const { + LLDB_INSTRUMENT_VA(this); + + return false; +} + +void SBDebugger::SetCloseInputOnEOF(bool b) { + LLDB_INSTRUMENT_VA(this, b); +} + +SBTypeCategory SBDebugger::GetCategory(const char *category_name) { + LLDB_INSTRUMENT_VA(this, category_name); + + if (!category_name || *category_name == 0) + return SBTypeCategory(); + + TypeCategoryImplSP category_sp; + + if (DataVisualization::Categories::GetCategory(ConstString(category_name), + category_sp, false)) { + return SBTypeCategory(category_sp); + } else { + return SBTypeCategory(); + } +} + +SBTypeCategory SBDebugger::GetCategory(lldb::LanguageType lang_type) { + LLDB_INSTRUMENT_VA(this, lang_type); + + TypeCategoryImplSP category_sp; + if (DataVisualization::Categories::GetCategory(lang_type, category_sp)) { + return SBTypeCategory(category_sp); + } else { + return SBTypeCategory(); + } +} + +SBTypeCategory SBDebugger::CreateCategory(const char *category_name) { + LLDB_INSTRUMENT_VA(this, category_name); + + if (!category_name || *category_name == 0) + return SBTypeCategory(); + + TypeCategoryImplSP category_sp; + + if (DataVisualization::Categories::GetCategory(ConstString(category_name), + category_sp, true)) { + return SBTypeCategory(category_sp); + } else { + return SBTypeCategory(); + } +} + +bool SBDebugger::DeleteCategory(const char *category_name) { + LLDB_INSTRUMENT_VA(this, category_name); + + if (!category_name || *category_name == 0) + return false; + + return DataVisualization::Categories::Delete(ConstString(category_name)); +} + +uint32_t SBDebugger::GetNumCategories() { + LLDB_INSTRUMENT_VA(this); + + return DataVisualization::Categories::GetCount(); +} + +SBTypeCategory SBDebugger::GetCategoryAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + return SBTypeCategory( + DataVisualization::Categories::GetCategoryAtIndex(index)); +} + +SBTypeCategory SBDebugger::GetDefaultCategory() { + LLDB_INSTRUMENT_VA(this); + + return GetCategory("default"); +} + +SBTypeFormat SBDebugger::GetFormatForType(SBTypeNameSpecifier type_name) { + LLDB_INSTRUMENT_VA(this, type_name); + + SBTypeCategory default_category_sb = GetDefaultCategory(); + if (default_category_sb.GetEnabled()) + return default_category_sb.GetFormatForType(type_name); + return SBTypeFormat(); +} + +SBTypeSummary SBDebugger::GetSummaryForType(SBTypeNameSpecifier type_name) { + LLDB_INSTRUMENT_VA(this, type_name); + + if (!type_name.IsValid()) + return SBTypeSummary(); + return SBTypeSummary(DataVisualization::GetSummaryForType(type_name.GetSP())); +} + +SBTypeFilter SBDebugger::GetFilterForType(SBTypeNameSpecifier type_name) { + LLDB_INSTRUMENT_VA(this, type_name); + + if (!type_name.IsValid()) + return SBTypeFilter(); + return SBTypeFilter(DataVisualization::GetFilterForType(type_name.GetSP())); +} + +SBTypeSynthetic SBDebugger::GetSyntheticForType(SBTypeNameSpecifier type_name) { + LLDB_INSTRUMENT_VA(this, type_name); + + if (!type_name.IsValid()) + return SBTypeSynthetic(); + return SBTypeSynthetic( + DataVisualization::GetSyntheticForType(type_name.GetSP())); +} + +static llvm::ArrayRef<const char *> GetCategoryArray(const char **categories) { + if (categories == nullptr) + return {}; + size_t len = 0; + while (categories[len] != nullptr) + ++len; + return llvm::ArrayRef(categories, len); +} + +bool SBDebugger::EnableLog(const char *channel, const char **categories) { + LLDB_INSTRUMENT_VA(this, channel, categories); + + if (m_opaque_sp) { + uint32_t log_options = + LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME; + std::string error; + llvm::raw_string_ostream error_stream(error); + return m_opaque_sp->EnableLog(channel, GetCategoryArray(categories), "", + log_options, /*buffer_size=*/0, + eLogHandlerStream, error_stream); + } else + return false; +} + +void SBDebugger::SetLoggingCallback(lldb::LogOutputCallback log_callback, + void *baton) { + LLDB_INSTRUMENT_VA(this, log_callback, baton); + + if (m_opaque_sp) { + return m_opaque_sp->SetLoggingCallback(log_callback, baton); + } +} + +void SBDebugger::SetDestroyCallback( + lldb::SBDebuggerDestroyCallback destroy_callback, void *baton) { + LLDB_INSTRUMENT_VA(this, destroy_callback, baton); + if (m_opaque_sp) { + return m_opaque_sp->SetDestroyCallback( + destroy_callback, baton); + } +} + +lldb::callback_token_t +SBDebugger::AddDestroyCallback(lldb::SBDebuggerDestroyCallback destroy_callback, + void *baton) { + LLDB_INSTRUMENT_VA(this, destroy_callback, baton); + + if (m_opaque_sp) + return m_opaque_sp->AddDestroyCallback(destroy_callback, baton); + + return LLDB_INVALID_CALLBACK_TOKEN; +} + +bool SBDebugger::RemoveDestroyCallback(lldb::callback_token_t token) { + LLDB_INSTRUMENT_VA(this, token); + + if (m_opaque_sp) + return m_opaque_sp->RemoveDestroyCallback(token); + + return false; +} + +SBTrace +SBDebugger::LoadTraceFromFile(SBError &error, + const SBFileSpec &trace_description_file) { + LLDB_INSTRUMENT_VA(this, error, trace_description_file); + return SBTrace::LoadTraceFromFile(error, *this, trace_description_file); +} + +void SBDebugger::RequestInterrupt() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + m_opaque_sp->RequestInterrupt(); +} +void SBDebugger::CancelInterruptRequest() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + m_opaque_sp->CancelInterruptRequest(); +} + +bool SBDebugger::InterruptRequested() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + return m_opaque_sp->InterruptRequested(); + return false; +} + +bool SBDebugger::SupportsLanguage(lldb::LanguageType language) { + return TypeSystem::SupportsLanguageStatic(language); +} diff --git a/contrib/llvm-project/lldb/source/API/SBDeclaration.cpp b/contrib/llvm-project/lldb/source/API/SBDeclaration.cpp new file mode 100644 index 000000000000..5b7def09b5cc --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBDeclaration.cpp @@ -0,0 +1,164 @@ +//===-- SBDeclaration.cpp -------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBDeclaration.h" +#include "Utils.h" +#include "lldb/API/SBStream.h" +#include "lldb/Core/Declaration.h" +#include "lldb/Host/PosixApi.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Stream.h" + +#include <climits> + +using namespace lldb; +using namespace lldb_private; + +SBDeclaration::SBDeclaration() { LLDB_INSTRUMENT_VA(this); } + +SBDeclaration::SBDeclaration(const SBDeclaration &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBDeclaration::SBDeclaration(const lldb_private::Declaration *lldb_object_ptr) { + if (lldb_object_ptr) + m_opaque_up = std::make_unique<Declaration>(*lldb_object_ptr); +} + +const SBDeclaration &SBDeclaration::operator=(const SBDeclaration &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +void SBDeclaration::SetDeclaration( + const lldb_private::Declaration &lldb_object_ref) { + ref() = lldb_object_ref; +} + +SBDeclaration::~SBDeclaration() = default; + +bool SBDeclaration::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBDeclaration::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up.get() && m_opaque_up->IsValid(); +} + +SBFileSpec SBDeclaration::GetFileSpec() const { + LLDB_INSTRUMENT_VA(this); + + SBFileSpec sb_file_spec; + if (m_opaque_up.get() && m_opaque_up->GetFile()) + sb_file_spec.SetFileSpec(m_opaque_up->GetFile()); + + return sb_file_spec; +} + +uint32_t SBDeclaration::GetLine() const { + LLDB_INSTRUMENT_VA(this); + + uint32_t line = 0; + if (m_opaque_up) + line = m_opaque_up->GetLine(); + + + return line; +} + +uint32_t SBDeclaration::GetColumn() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + return m_opaque_up->GetColumn(); + return 0; +} + +void SBDeclaration::SetFileSpec(lldb::SBFileSpec filespec) { + LLDB_INSTRUMENT_VA(this, filespec); + + if (filespec.IsValid()) + ref().SetFile(filespec.ref()); + else + ref().SetFile(FileSpec()); +} +void SBDeclaration::SetLine(uint32_t line) { + LLDB_INSTRUMENT_VA(this, line); + + ref().SetLine(line); +} + +void SBDeclaration::SetColumn(uint32_t column) { + LLDB_INSTRUMENT_VA(this, column); + + ref().SetColumn(column); +} + +bool SBDeclaration::operator==(const SBDeclaration &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + lldb_private::Declaration *lhs_ptr = m_opaque_up.get(); + lldb_private::Declaration *rhs_ptr = rhs.m_opaque_up.get(); + + if (lhs_ptr && rhs_ptr) + return lldb_private::Declaration::Compare(*lhs_ptr, *rhs_ptr) == 0; + + return lhs_ptr == rhs_ptr; +} + +bool SBDeclaration::operator!=(const SBDeclaration &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + lldb_private::Declaration *lhs_ptr = m_opaque_up.get(); + lldb_private::Declaration *rhs_ptr = rhs.m_opaque_up.get(); + + if (lhs_ptr && rhs_ptr) + return lldb_private::Declaration::Compare(*lhs_ptr, *rhs_ptr) != 0; + + return lhs_ptr != rhs_ptr; +} + +const lldb_private::Declaration *SBDeclaration::operator->() const { + return m_opaque_up.get(); +} + +lldb_private::Declaration &SBDeclaration::ref() { + if (m_opaque_up == nullptr) + m_opaque_up = std::make_unique<lldb_private::Declaration>(); + return *m_opaque_up; +} + +const lldb_private::Declaration &SBDeclaration::ref() const { + return *m_opaque_up; +} + +bool SBDeclaration::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + if (m_opaque_up) { + char file_path[PATH_MAX * 2]; + m_opaque_up->GetFile().GetPath(file_path, sizeof(file_path)); + strm.Printf("%s:%u", file_path, GetLine()); + if (GetColumn() > 0) + strm.Printf(":%u", GetColumn()); + } else + strm.PutCString("No value"); + + return true; +} + +lldb_private::Declaration *SBDeclaration::get() { return m_opaque_up.get(); } diff --git a/contrib/llvm-project/lldb/source/API/SBEnvironment.cpp b/contrib/llvm-project/lldb/source/API/SBEnvironment.cpp new file mode 100644 index 000000000000..5fafabe02e01 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBEnvironment.cpp @@ -0,0 +1,124 @@ +//===-- SBEnvironment.cpp -------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBEnvironment.h" +#include "Utils.h" +#include "lldb/API/SBStringList.h" +#include "lldb/Utility/ConstString.h" +#include "lldb/Utility/Environment.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +SBEnvironment::SBEnvironment() : m_opaque_up(new Environment()) { + LLDB_INSTRUMENT_VA(this); +} + +SBEnvironment::SBEnvironment(const SBEnvironment &rhs) + : m_opaque_up(clone(rhs.m_opaque_up)) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBEnvironment::SBEnvironment(Environment rhs) + : m_opaque_up(new Environment(std::move(rhs))) {} + +SBEnvironment::~SBEnvironment() = default; + +const SBEnvironment &SBEnvironment::operator=(const SBEnvironment &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +size_t SBEnvironment::GetNumValues() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->size(); +} + +const char *SBEnvironment::Get(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + + auto entry = m_opaque_up->find(name); + if (entry == m_opaque_up->end()) { + return nullptr; + } + return ConstString(entry->second).AsCString(""); +} + +const char *SBEnvironment::GetNameAtIndex(size_t index) { + LLDB_INSTRUMENT_VA(this, index); + + if (index >= GetNumValues()) + return nullptr; + return ConstString(std::next(m_opaque_up->begin(), index)->first()) + .AsCString(""); +} + +const char *SBEnvironment::GetValueAtIndex(size_t index) { + LLDB_INSTRUMENT_VA(this, index); + + if (index >= GetNumValues()) + return nullptr; + return ConstString(std::next(m_opaque_up->begin(), index)->second) + .AsCString(""); +} + +bool SBEnvironment::Set(const char *name, const char *value, bool overwrite) { + LLDB_INSTRUMENT_VA(this, name, value, overwrite); + + if (overwrite) { + m_opaque_up->insert_or_assign(name, std::string(value)); + return true; + } + return m_opaque_up->try_emplace(name, std::string(value)).second; +} + +bool SBEnvironment::Unset(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + + return m_opaque_up->erase(name); +} + +SBStringList SBEnvironment::GetEntries() { + LLDB_INSTRUMENT_VA(this); + + SBStringList entries; + for (const auto &KV : *m_opaque_up) { + entries.AppendString(Environment::compose(KV).c_str()); + } + return entries; +} + +void SBEnvironment::PutEntry(const char *name_and_value) { + LLDB_INSTRUMENT_VA(this, name_and_value); + + auto split = llvm::StringRef(name_and_value).split('='); + m_opaque_up->insert_or_assign(split.first.str(), split.second.str()); +} + +void SBEnvironment::SetEntries(const SBStringList &entries, bool append) { + LLDB_INSTRUMENT_VA(this, entries, append); + + if (!append) + m_opaque_up->clear(); + for (size_t i = 0; i < entries.GetSize(); i++) { + PutEntry(entries.GetStringAtIndex(i)); + } +} + +void SBEnvironment::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_up->clear(); +} + +Environment &SBEnvironment::ref() const { return *m_opaque_up; } diff --git a/contrib/llvm-project/lldb/source/API/SBError.cpp b/contrib/llvm-project/lldb/source/API/SBError.cpp new file mode 100644 index 000000000000..2eb9e927514a --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBError.cpp @@ -0,0 +1,192 @@ +//===-- SBError.cpp -------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBError.h" +#include "Utils.h" +#include "lldb/API/SBStream.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Status.h" + +#include <cstdarg> + +using namespace lldb; +using namespace lldb_private; + +SBError::SBError() { LLDB_INSTRUMENT_VA(this); } + +SBError::SBError(const SBError &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBError::SBError(const char *message) { + LLDB_INSTRUMENT_VA(this, message); + + SetErrorString(message); +} + +SBError::SBError(const lldb_private::Status &status) + : m_opaque_up(new Status(status)) { + LLDB_INSTRUMENT_VA(this, status); +} + +SBError::~SBError() = default; + +const SBError &SBError::operator=(const SBError &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +const char *SBError::GetCString() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + return m_opaque_up->AsCString(); + return nullptr; +} + +void SBError::Clear() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + m_opaque_up->Clear(); +} + +bool SBError::Fail() const { + LLDB_INSTRUMENT_VA(this); + + bool ret_value = false; + if (m_opaque_up) + ret_value = m_opaque_up->Fail(); + + + return ret_value; +} + +bool SBError::Success() const { + LLDB_INSTRUMENT_VA(this); + + bool ret_value = true; + if (m_opaque_up) + ret_value = m_opaque_up->Success(); + + return ret_value; +} + +uint32_t SBError::GetError() const { + LLDB_INSTRUMENT_VA(this); + + uint32_t err = 0; + if (m_opaque_up) + err = m_opaque_up->GetError(); + + + return err; +} + +ErrorType SBError::GetType() const { + LLDB_INSTRUMENT_VA(this); + + ErrorType err_type = eErrorTypeInvalid; + if (m_opaque_up) + err_type = m_opaque_up->GetType(); + + return err_type; +} + +void SBError::SetError(uint32_t err, ErrorType type) { + LLDB_INSTRUMENT_VA(this, err, type); + + CreateIfNeeded(); + m_opaque_up->SetError(err, type); +} + +void SBError::SetError(const Status &lldb_error) { + CreateIfNeeded(); + *m_opaque_up = lldb_error; +} + +void SBError::SetErrorToErrno() { + LLDB_INSTRUMENT_VA(this); + + CreateIfNeeded(); + m_opaque_up->SetErrorToErrno(); +} + +void SBError::SetErrorToGenericError() { + LLDB_INSTRUMENT_VA(this); + + CreateIfNeeded(); + m_opaque_up->SetErrorToGenericError(); +} + +void SBError::SetErrorString(const char *err_str) { + LLDB_INSTRUMENT_VA(this, err_str); + + CreateIfNeeded(); + m_opaque_up->SetErrorString(err_str); +} + +int SBError::SetErrorStringWithFormat(const char *format, ...) { + CreateIfNeeded(); + va_list args; + va_start(args, format); + int num_chars = m_opaque_up->SetErrorStringWithVarArg(format, args); + va_end(args); + return num_chars; +} + +bool SBError::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBError::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up != nullptr; +} + +void SBError::CreateIfNeeded() { + if (m_opaque_up == nullptr) + m_opaque_up = std::make_unique<Status>(); +} + +lldb_private::Status *SBError::operator->() { return m_opaque_up.get(); } + +lldb_private::Status *SBError::get() { return m_opaque_up.get(); } + +lldb_private::Status &SBError::ref() { + CreateIfNeeded(); + return *m_opaque_up; +} + +const lldb_private::Status &SBError::operator*() const { + // Be sure to call "IsValid()" before calling this function or it will crash + return *m_opaque_up; +} + +bool SBError::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + if (m_opaque_up) { + if (m_opaque_up->Success()) + description.Printf("success"); + else { + const char *err_string = GetCString(); + description.Printf("error: %s", + (err_string != nullptr ? err_string : "")); + } + } else + description.Printf("error: <NULL>"); + + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBEvent.cpp b/contrib/llvm-project/lldb/source/API/SBEvent.cpp new file mode 100644 index 000000000000..aa9c0ff097d4 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBEvent.cpp @@ -0,0 +1,199 @@ +//===-- SBEvent.cpp -------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBBroadcaster.h" +#include "lldb/API/SBStream.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/Breakpoint/Breakpoint.h" +#include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Target/Process.h" +#include "lldb/Utility/ConstString.h" +#include "lldb/Utility/Event.h" +#include "lldb/Utility/Stream.h" + +using namespace lldb; +using namespace lldb_private; + +SBEvent::SBEvent() { LLDB_INSTRUMENT_VA(this); } + +SBEvent::SBEvent(uint32_t event_type, const char *cstr, uint32_t cstr_len) + : m_event_sp(new Event( + event_type, new EventDataBytes(llvm::StringRef(cstr, cstr_len)))), + m_opaque_ptr(m_event_sp.get()) { + LLDB_INSTRUMENT_VA(this, event_type, cstr, cstr_len); +} + +SBEvent::SBEvent(EventSP &event_sp) + : m_event_sp(event_sp), m_opaque_ptr(event_sp.get()) { + LLDB_INSTRUMENT_VA(this, event_sp); +} + +SBEvent::SBEvent(Event *event_ptr) : m_opaque_ptr(event_ptr) { + LLDB_INSTRUMENT_VA(this, event_ptr); +} + +SBEvent::SBEvent(const SBEvent &rhs) + : m_event_sp(rhs.m_event_sp), m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const SBEvent &SBEvent::operator=(const SBEvent &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_event_sp = rhs.m_event_sp; + m_opaque_ptr = rhs.m_opaque_ptr; + } + return *this; +} + +SBEvent::~SBEvent() = default; + +const char *SBEvent::GetDataFlavor() { + LLDB_INSTRUMENT_VA(this); + + Event *lldb_event = get(); + if (lldb_event) { + EventData *event_data = lldb_event->GetData(); + if (event_data) + return ConstString(lldb_event->GetData()->GetFlavor()).GetCString(); + } + return nullptr; +} + +uint32_t SBEvent::GetType() const { + LLDB_INSTRUMENT_VA(this); + + const Event *lldb_event = get(); + uint32_t event_type = 0; + if (lldb_event) + event_type = lldb_event->GetType(); + + + return event_type; +} + +SBBroadcaster SBEvent::GetBroadcaster() const { + LLDB_INSTRUMENT_VA(this); + + SBBroadcaster broadcaster; + const Event *lldb_event = get(); + if (lldb_event) + broadcaster.reset(lldb_event->GetBroadcaster(), false); + return broadcaster; +} + +const char *SBEvent::GetBroadcasterClass() const { + LLDB_INSTRUMENT_VA(this); + + const Event *lldb_event = get(); + if (lldb_event) + return ConstString(lldb_event->GetBroadcaster()->GetBroadcasterClass()) + .AsCString(); + else + return "unknown class"; +} + +bool SBEvent::BroadcasterMatchesPtr(const SBBroadcaster *broadcaster) { + LLDB_INSTRUMENT_VA(this, broadcaster); + + if (broadcaster) + return BroadcasterMatchesRef(*broadcaster); + return false; +} + +bool SBEvent::BroadcasterMatchesRef(const SBBroadcaster &broadcaster) { + LLDB_INSTRUMENT_VA(this, broadcaster); + + Event *lldb_event = get(); + bool success = false; + if (lldb_event) + success = lldb_event->BroadcasterIs(broadcaster.get()); + + + return success; +} + +void SBEvent::Clear() { + LLDB_INSTRUMENT_VA(this); + + Event *lldb_event = get(); + if (lldb_event) + lldb_event->Clear(); +} + +EventSP &SBEvent::GetSP() const { return m_event_sp; } + +Event *SBEvent::get() const { + // There is a dangerous accessor call GetSharedPtr which can be used, so if + // we have anything valid in m_event_sp, we must use that since if it gets + // used by a function that puts something in there, then it won't update + // m_opaque_ptr... + if (m_event_sp) + m_opaque_ptr = m_event_sp.get(); + + return m_opaque_ptr; +} + +void SBEvent::reset(EventSP &event_sp) { + m_event_sp = event_sp; + m_opaque_ptr = m_event_sp.get(); +} + +void SBEvent::reset(Event *event_ptr) { + m_opaque_ptr = event_ptr; + m_event_sp.reset(); +} + +bool SBEvent::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBEvent::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + // Do NOT use m_opaque_ptr directly!!! Must use the SBEvent::get() accessor. + // See comments in SBEvent::get().... + return SBEvent::get() != nullptr; +} + +const char *SBEvent::GetCStringFromEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return ConstString(static_cast<const char *>( + EventDataBytes::GetBytesFromEvent(event.get()))) + .GetCString(); +} + +bool SBEvent::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + if (get()) { + m_opaque_ptr->Dump(&strm); + } else + strm.PutCString("No value"); + + return true; +} + +bool SBEvent::GetDescription(SBStream &description) const { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + if (get()) { + m_opaque_ptr->Dump(&strm); + } else + strm.PutCString("No value"); + + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBExecutionContext.cpp b/contrib/llvm-project/lldb/source/API/SBExecutionContext.cpp new file mode 100644 index 000000000000..a0b68e6efe38 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBExecutionContext.cpp @@ -0,0 +1,123 @@ +//===-- SBExecutionContext.cpp --------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBExecutionContext.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBFrame.h" +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBTarget.h" +#include "lldb/API/SBThread.h" + +#include "lldb/Target/ExecutionContext.h" + +using namespace lldb; +using namespace lldb_private; + +SBExecutionContext::SBExecutionContext() { LLDB_INSTRUMENT_VA(this); } + +SBExecutionContext::SBExecutionContext(const lldb::SBExecutionContext &rhs) + : m_exe_ctx_sp(rhs.m_exe_ctx_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBExecutionContext::SBExecutionContext( + lldb::ExecutionContextRefSP exe_ctx_ref_sp) + : m_exe_ctx_sp(exe_ctx_ref_sp) { + LLDB_INSTRUMENT_VA(this, exe_ctx_ref_sp); +} + +SBExecutionContext::SBExecutionContext(const lldb::SBTarget &target) + : m_exe_ctx_sp(new ExecutionContextRef()) { + LLDB_INSTRUMENT_VA(this, target); + + m_exe_ctx_sp->SetTargetSP(target.GetSP()); +} + +SBExecutionContext::SBExecutionContext(const lldb::SBProcess &process) + : m_exe_ctx_sp(new ExecutionContextRef()) { + LLDB_INSTRUMENT_VA(this, process); + + m_exe_ctx_sp->SetProcessSP(process.GetSP()); +} + +SBExecutionContext::SBExecutionContext(lldb::SBThread thread) + : m_exe_ctx_sp(new ExecutionContextRef()) { + LLDB_INSTRUMENT_VA(this, thread); + + m_exe_ctx_sp->SetThreadPtr(thread.get()); +} + +SBExecutionContext::SBExecutionContext(const lldb::SBFrame &frame) + : m_exe_ctx_sp(new ExecutionContextRef()) { + LLDB_INSTRUMENT_VA(this, frame); + + m_exe_ctx_sp->SetFrameSP(frame.GetFrameSP()); +} + +SBExecutionContext::~SBExecutionContext() = default; + +const SBExecutionContext &SBExecutionContext:: +operator=(const lldb::SBExecutionContext &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_exe_ctx_sp = rhs.m_exe_ctx_sp; + return *this; +} + +ExecutionContextRef *SBExecutionContext::get() const { + return m_exe_ctx_sp.get(); +} + +SBTarget SBExecutionContext::GetTarget() const { + LLDB_INSTRUMENT_VA(this); + + SBTarget sb_target; + if (m_exe_ctx_sp) { + TargetSP target_sp(m_exe_ctx_sp->GetTargetSP()); + if (target_sp) + sb_target.SetSP(target_sp); + } + return sb_target; +} + +SBProcess SBExecutionContext::GetProcess() const { + LLDB_INSTRUMENT_VA(this); + + SBProcess sb_process; + if (m_exe_ctx_sp) { + ProcessSP process_sp(m_exe_ctx_sp->GetProcessSP()); + if (process_sp) + sb_process.SetSP(process_sp); + } + return sb_process; +} + +SBThread SBExecutionContext::GetThread() const { + LLDB_INSTRUMENT_VA(this); + + SBThread sb_thread; + if (m_exe_ctx_sp) { + ThreadSP thread_sp(m_exe_ctx_sp->GetThreadSP()); + if (thread_sp) + sb_thread.SetThread(thread_sp); + } + return sb_thread; +} + +SBFrame SBExecutionContext::GetFrame() const { + LLDB_INSTRUMENT_VA(this); + + SBFrame sb_frame; + if (m_exe_ctx_sp) { + StackFrameSP frame_sp(m_exe_ctx_sp->GetFrameSP()); + if (frame_sp) + sb_frame.SetFrameSP(frame_sp); + } + return sb_frame; +} diff --git a/contrib/llvm-project/lldb/source/API/SBExpressionOptions.cpp b/contrib/llvm-project/lldb/source/API/SBExpressionOptions.cpp new file mode 100644 index 000000000000..15ed403eaaea --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBExpressionOptions.cpp @@ -0,0 +1,265 @@ +//===-- SBExpressionOptions.cpp -------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBExpressionOptions.h" +#include "Utils.h" +#include "lldb/API/SBStream.h" +#include "lldb/Target/Target.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +SBExpressionOptions::SBExpressionOptions() + : m_opaque_up(new EvaluateExpressionOptions()) { + LLDB_INSTRUMENT_VA(this); +} + +SBExpressionOptions::SBExpressionOptions(const SBExpressionOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +const SBExpressionOptions &SBExpressionOptions:: +operator=(const SBExpressionOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +SBExpressionOptions::~SBExpressionOptions() = default; + +bool SBExpressionOptions::GetCoerceResultToId() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->DoesCoerceToId(); +} + +void SBExpressionOptions::SetCoerceResultToId(bool coerce) { + LLDB_INSTRUMENT_VA(this, coerce); + + m_opaque_up->SetCoerceToId(coerce); +} + +bool SBExpressionOptions::GetUnwindOnError() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->DoesUnwindOnError(); +} + +void SBExpressionOptions::SetUnwindOnError(bool unwind) { + LLDB_INSTRUMENT_VA(this, unwind); + + m_opaque_up->SetUnwindOnError(unwind); +} + +bool SBExpressionOptions::GetIgnoreBreakpoints() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->DoesIgnoreBreakpoints(); +} + +void SBExpressionOptions::SetIgnoreBreakpoints(bool ignore) { + LLDB_INSTRUMENT_VA(this, ignore); + + m_opaque_up->SetIgnoreBreakpoints(ignore); +} + +lldb::DynamicValueType SBExpressionOptions::GetFetchDynamicValue() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetUseDynamic(); +} + +void SBExpressionOptions::SetFetchDynamicValue(lldb::DynamicValueType dynamic) { + LLDB_INSTRUMENT_VA(this, dynamic); + + m_opaque_up->SetUseDynamic(dynamic); +} + +uint32_t SBExpressionOptions::GetTimeoutInMicroSeconds() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetTimeout() ? m_opaque_up->GetTimeout()->count() : 0; +} + +void SBExpressionOptions::SetTimeoutInMicroSeconds(uint32_t timeout) { + LLDB_INSTRUMENT_VA(this, timeout); + + m_opaque_up->SetTimeout(timeout == 0 ? Timeout<std::micro>(std::nullopt) + : std::chrono::microseconds(timeout)); +} + +uint32_t SBExpressionOptions::GetOneThreadTimeoutInMicroSeconds() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetOneThreadTimeout() + ? m_opaque_up->GetOneThreadTimeout()->count() + : 0; +} + +void SBExpressionOptions::SetOneThreadTimeoutInMicroSeconds(uint32_t timeout) { + LLDB_INSTRUMENT_VA(this, timeout); + + m_opaque_up->SetOneThreadTimeout(timeout == 0 + ? Timeout<std::micro>(std::nullopt) + : std::chrono::microseconds(timeout)); +} + +bool SBExpressionOptions::GetTryAllThreads() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetTryAllThreads(); +} + +void SBExpressionOptions::SetTryAllThreads(bool run_others) { + LLDB_INSTRUMENT_VA(this, run_others); + + m_opaque_up->SetTryAllThreads(run_others); +} + +bool SBExpressionOptions::GetStopOthers() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetStopOthers(); +} + +void SBExpressionOptions::SetStopOthers(bool run_others) { + LLDB_INSTRUMENT_VA(this, run_others); + + m_opaque_up->SetStopOthers(run_others); +} + +bool SBExpressionOptions::GetTrapExceptions() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetTrapExceptions(); +} + +void SBExpressionOptions::SetTrapExceptions(bool trap_exceptions) { + LLDB_INSTRUMENT_VA(this, trap_exceptions); + + m_opaque_up->SetTrapExceptions(trap_exceptions); +} + +void SBExpressionOptions::SetLanguage(lldb::LanguageType language) { + LLDB_INSTRUMENT_VA(this, language); + + m_opaque_up->SetLanguage(language); +} + +void SBExpressionOptions::SetLanguage(lldb::SBSourceLanguageName name, + uint32_t version) { + LLDB_INSTRUMENT_VA(this, name, version); + + m_opaque_up->SetLanguage(name, version); +} + +void SBExpressionOptions::SetCancelCallback( + lldb::ExpressionCancelCallback callback, void *baton) { + LLDB_INSTRUMENT_VA(this, callback, baton); + + m_opaque_up->SetCancelCallback(callback, baton); +} + +bool SBExpressionOptions::GetGenerateDebugInfo() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetGenerateDebugInfo(); +} + +void SBExpressionOptions::SetGenerateDebugInfo(bool b) { + LLDB_INSTRUMENT_VA(this, b); + + return m_opaque_up->SetGenerateDebugInfo(b); +} + +bool SBExpressionOptions::GetSuppressPersistentResult() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetSuppressPersistentResult(); +} + +void SBExpressionOptions::SetSuppressPersistentResult(bool b) { + LLDB_INSTRUMENT_VA(this, b); + + return m_opaque_up->SetSuppressPersistentResult(b); +} + +const char *SBExpressionOptions::GetPrefix() const { + LLDB_INSTRUMENT_VA(this); + + return ConstString(m_opaque_up->GetPrefix()).GetCString(); +} + +void SBExpressionOptions::SetPrefix(const char *prefix) { + LLDB_INSTRUMENT_VA(this, prefix); + + return m_opaque_up->SetPrefix(prefix); +} + +bool SBExpressionOptions::GetAutoApplyFixIts() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetAutoApplyFixIts(); +} + +void SBExpressionOptions::SetAutoApplyFixIts(bool b) { + LLDB_INSTRUMENT_VA(this, b); + + return m_opaque_up->SetAutoApplyFixIts(b); +} + +uint64_t SBExpressionOptions::GetRetriesWithFixIts() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetRetriesWithFixIts(); +} + +void SBExpressionOptions::SetRetriesWithFixIts(uint64_t retries) { + LLDB_INSTRUMENT_VA(this, retries); + + return m_opaque_up->SetRetriesWithFixIts(retries); +} + +bool SBExpressionOptions::GetTopLevel() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetExecutionPolicy() == eExecutionPolicyTopLevel; +} + +void SBExpressionOptions::SetTopLevel(bool b) { + LLDB_INSTRUMENT_VA(this, b); + + m_opaque_up->SetExecutionPolicy(b ? eExecutionPolicyTopLevel + : m_opaque_up->default_execution_policy); +} + +bool SBExpressionOptions::GetAllowJIT() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetExecutionPolicy() != eExecutionPolicyNever; +} + +void SBExpressionOptions::SetAllowJIT(bool allow) { + LLDB_INSTRUMENT_VA(this, allow); + + m_opaque_up->SetExecutionPolicy(allow ? m_opaque_up->default_execution_policy + : eExecutionPolicyNever); +} + +EvaluateExpressionOptions *SBExpressionOptions::get() const { + return m_opaque_up.get(); +} + +EvaluateExpressionOptions &SBExpressionOptions::ref() const { + return *m_opaque_up; +} diff --git a/contrib/llvm-project/lldb/source/API/SBFile.cpp b/contrib/llvm-project/lldb/source/API/SBFile.cpp new file mode 100644 index 000000000000..0db859c3b746 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBFile.cpp @@ -0,0 +1,129 @@ +//===-- SBFile.cpp --------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBFile.h" +#include "lldb/API/SBError.h" +#include "lldb/Host/File.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +SBFile::~SBFile() = default; + +SBFile::SBFile(FileSP file_sp) : m_opaque_sp(file_sp) { + // We have no way to capture the incoming FileSP as the class isn't + // instrumented, so pretend that it's always null. + LLDB_INSTRUMENT_VA(this, file_sp); +} + +SBFile::SBFile(const SBFile &rhs) : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBFile &SBFile ::operator=(const SBFile &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; +} + +SBFile::SBFile() { LLDB_INSTRUMENT_VA(this); } + +SBFile::SBFile(FILE *file, bool transfer_ownership) { + LLDB_INSTRUMENT_VA(this, file, transfer_ownership); + + m_opaque_sp = std::make_shared<NativeFile>(file, transfer_ownership); +} + +SBFile::SBFile(int fd, const char *mode, bool transfer_owndership) { + LLDB_INSTRUMENT_VA(this, fd, mode, transfer_owndership); + + auto options = File::GetOptionsFromMode(mode); + if (!options) { + llvm::consumeError(options.takeError()); + return; + } + m_opaque_sp = + std::make_shared<NativeFile>(fd, options.get(), transfer_owndership); +} + +SBError SBFile::Read(uint8_t *buf, size_t num_bytes, size_t *bytes_read) { + LLDB_INSTRUMENT_VA(this, buf, num_bytes, bytes_read); + + SBError error; + if (!m_opaque_sp) { + error.SetErrorString("invalid SBFile"); + *bytes_read = 0; + } else { + Status status = m_opaque_sp->Read(buf, num_bytes); + error.SetError(status); + *bytes_read = num_bytes; + } + return error; +} + +SBError SBFile::Write(const uint8_t *buf, size_t num_bytes, + size_t *bytes_written) { + LLDB_INSTRUMENT_VA(this, buf, num_bytes, bytes_written); + + SBError error; + if (!m_opaque_sp) { + error.SetErrorString("invalid SBFile"); + *bytes_written = 0; + } else { + Status status = m_opaque_sp->Write(buf, num_bytes); + error.SetError(status); + *bytes_written = num_bytes; + } + return error; +} + +SBError SBFile::Flush() { + LLDB_INSTRUMENT_VA(this); + + SBError error; + if (!m_opaque_sp) { + error.SetErrorString("invalid SBFile"); + } else { + Status status = m_opaque_sp->Flush(); + error.SetError(status); + } + return error; +} + +bool SBFile::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return m_opaque_sp && m_opaque_sp->IsValid(); +} + +SBError SBFile::Close() { + LLDB_INSTRUMENT_VA(this); + SBError error; + if (m_opaque_sp) { + Status status = m_opaque_sp->Close(); + error.SetError(status); + } + return error; +} + +SBFile::operator bool() const { + LLDB_INSTRUMENT_VA(this); + return IsValid(); +} + +bool SBFile::operator!() const { + LLDB_INSTRUMENT_VA(this); + return !IsValid(); +} + +FileSP SBFile::GetFile() const { + LLDB_INSTRUMENT_VA(this); + return m_opaque_sp; +} diff --git a/contrib/llvm-project/lldb/source/API/SBFileSpec.cpp b/contrib/llvm-project/lldb/source/API/SBFileSpec.cpp new file mode 100644 index 000000000000..a7df9afc4b8e --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBFileSpec.cpp @@ -0,0 +1,182 @@ +//===-- SBFileSpec.cpp ----------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBFileSpec.h" +#include "Utils.h" +#include "lldb/API/SBStream.h" +#include "lldb/Host/FileSystem.h" +#include "lldb/Host/PosixApi.h" +#include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Stream.h" + +#include "llvm/ADT/SmallString.h" + +#include <cinttypes> +#include <climits> + +using namespace lldb; +using namespace lldb_private; + +SBFileSpec::SBFileSpec() : m_opaque_up(new lldb_private::FileSpec()) { + LLDB_INSTRUMENT_VA(this); +} + +SBFileSpec::SBFileSpec(const SBFileSpec &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBFileSpec::SBFileSpec(const lldb_private::FileSpec &fspec) + : m_opaque_up(new lldb_private::FileSpec(fspec)) {} + +// Deprecated!!! +SBFileSpec::SBFileSpec(const char *path) : m_opaque_up(new FileSpec(path)) { + LLDB_INSTRUMENT_VA(this, path); + + FileSystem::Instance().Resolve(*m_opaque_up); +} + +SBFileSpec::SBFileSpec(const char *path, bool resolve) + : m_opaque_up(new FileSpec(path)) { + LLDB_INSTRUMENT_VA(this, path, resolve); + + if (resolve) + FileSystem::Instance().Resolve(*m_opaque_up); +} + +SBFileSpec::~SBFileSpec() = default; + +const SBFileSpec &SBFileSpec::operator=(const SBFileSpec &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +bool SBFileSpec::operator==(const SBFileSpec &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return ref() == rhs.ref(); +} + +bool SBFileSpec::operator!=(const SBFileSpec &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return !(*this == rhs); +} + +bool SBFileSpec::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBFileSpec::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->operator bool(); +} + +bool SBFileSpec::Exists() const { + LLDB_INSTRUMENT_VA(this); + + return FileSystem::Instance().Exists(*m_opaque_up); +} + +bool SBFileSpec::ResolveExecutableLocation() { + LLDB_INSTRUMENT_VA(this); + + return FileSystem::Instance().ResolveExecutableLocation(*m_opaque_up); +} + +int SBFileSpec::ResolvePath(const char *src_path, char *dst_path, + size_t dst_len) { + LLDB_INSTRUMENT_VA(src_path, dst_path, dst_len); + + llvm::SmallString<64> result(src_path); + FileSystem::Instance().Resolve(result); + ::snprintf(dst_path, dst_len, "%s", result.c_str()); + return std::min(dst_len - 1, result.size()); +} + +const char *SBFileSpec::GetFilename() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetFilename().AsCString(); +} + +const char *SBFileSpec::GetDirectory() const { + LLDB_INSTRUMENT_VA(this); + + FileSpec directory{*m_opaque_up}; + directory.ClearFilename(); + return directory.GetPathAsConstString().GetCString(); +} + +void SBFileSpec::SetFilename(const char *filename) { + LLDB_INSTRUMENT_VA(this, filename); + + if (filename && filename[0]) + m_opaque_up->SetFilename(filename); + else + m_opaque_up->ClearFilename(); +} + +void SBFileSpec::SetDirectory(const char *directory) { + LLDB_INSTRUMENT_VA(this, directory); + + if (directory && directory[0]) + m_opaque_up->SetDirectory(directory); + else + m_opaque_up->ClearDirectory(); +} + +uint32_t SBFileSpec::GetPath(char *dst_path, size_t dst_len) const { + LLDB_INSTRUMENT_VA(this, dst_path, dst_len); + + uint32_t result = m_opaque_up->GetPath(dst_path, dst_len); + + if (result == 0 && dst_path && dst_len > 0) + *dst_path = '\0'; + return result; +} + +const lldb_private::FileSpec *SBFileSpec::operator->() const { + return m_opaque_up.get(); +} + +const lldb_private::FileSpec *SBFileSpec::get() const { + return m_opaque_up.get(); +} + +const lldb_private::FileSpec &SBFileSpec::operator*() const { + return *m_opaque_up; +} + +const lldb_private::FileSpec &SBFileSpec::ref() const { return *m_opaque_up; } + +void SBFileSpec::SetFileSpec(const lldb_private::FileSpec &fs) { + *m_opaque_up = fs; +} + +bool SBFileSpec::GetDescription(SBStream &description) const { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + char path[PATH_MAX]; + if (m_opaque_up->GetPath(path, sizeof(path))) + strm.PutCString(path); + return true; +} + +void SBFileSpec::AppendPathComponent(const char *fn) { + LLDB_INSTRUMENT_VA(this, fn); + + m_opaque_up->AppendPathComponent(fn); +} diff --git a/contrib/llvm-project/lldb/source/API/SBFileSpecList.cpp b/contrib/llvm-project/lldb/source/API/SBFileSpecList.cpp new file mode 100644 index 000000000000..74a368a3cabe --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBFileSpecList.cpp @@ -0,0 +1,116 @@ +//===-- SBFileSpecList.cpp ------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBFileSpecList.h" +#include "Utils.h" +#include "lldb/API/SBFileSpec.h" +#include "lldb/API/SBStream.h" +#include "lldb/Host/PosixApi.h" +#include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/FileSpecList.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Stream.h" + +#include <climits> + +using namespace lldb; +using namespace lldb_private; + +SBFileSpecList::SBFileSpecList() : m_opaque_up(new FileSpecList()) { + LLDB_INSTRUMENT_VA(this); +} + +SBFileSpecList::SBFileSpecList(const SBFileSpecList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBFileSpecList::~SBFileSpecList() = default; + +const SBFileSpecList &SBFileSpecList::operator=(const SBFileSpecList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +uint32_t SBFileSpecList::GetSize() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetSize(); +} + +void SBFileSpecList::Append(const SBFileSpec &sb_file) { + LLDB_INSTRUMENT_VA(this, sb_file); + + m_opaque_up->Append(sb_file.ref()); +} + +bool SBFileSpecList::AppendIfUnique(const SBFileSpec &sb_file) { + LLDB_INSTRUMENT_VA(this, sb_file); + + return m_opaque_up->AppendIfUnique(sb_file.ref()); +} + +void SBFileSpecList::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_up->Clear(); +} + +uint32_t SBFileSpecList::FindFileIndex(uint32_t idx, const SBFileSpec &sb_file, + bool full) { + LLDB_INSTRUMENT_VA(this, idx, sb_file, full); + + return m_opaque_up->FindFileIndex(idx, sb_file.ref(), full); +} + +const SBFileSpec SBFileSpecList::GetFileSpecAtIndex(uint32_t idx) const { + LLDB_INSTRUMENT_VA(this, idx); + + SBFileSpec new_spec; + new_spec.SetFileSpec(m_opaque_up->GetFileSpecAtIndex(idx)); + return new_spec; +} + +const lldb_private::FileSpecList *SBFileSpecList::operator->() const { + return m_opaque_up.get(); +} + +const lldb_private::FileSpecList *SBFileSpecList::get() const { + return m_opaque_up.get(); +} + +const lldb_private::FileSpecList &SBFileSpecList::operator*() const { + return *m_opaque_up; +} + +const lldb_private::FileSpecList &SBFileSpecList::ref() const { + return *m_opaque_up; +} + +bool SBFileSpecList::GetDescription(SBStream &description) const { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + if (m_opaque_up) { + uint32_t num_files = m_opaque_up->GetSize(); + strm.Printf("%d files: ", num_files); + for (uint32_t i = 0; i < num_files; i++) { + char path[PATH_MAX]; + if (m_opaque_up->GetFileSpecAtIndex(i).GetPath(path, sizeof(path))) + strm.Printf("\n %s", path); + } + } else + strm.PutCString("No value"); + + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBFormat.cpp b/contrib/llvm-project/lldb/source/API/SBFormat.cpp new file mode 100644 index 000000000000..51cddceea037 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBFormat.cpp @@ -0,0 +1,44 @@ +//===-- SBFormat.cpp ------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBFormat.h" +#include "Utils.h" +#include "lldb/Core/FormatEntity.h" +#include "lldb/lldb-types.h" +#include <lldb/API/SBError.h> +#include <lldb/Utility/Status.h> + +using namespace lldb; +using namespace lldb_private; + +SBFormat::SBFormat() : m_opaque_sp() {} + +SBFormat::SBFormat(const SBFormat &rhs) { + m_opaque_sp = clone(rhs.m_opaque_sp); +} + +SBFormat::~SBFormat() = default; + +SBFormat &SBFormat::operator=(const SBFormat &rhs) { + if (this != &rhs) + m_opaque_sp = clone(rhs.m_opaque_sp); + return *this; +} + +SBFormat::operator bool() const { return (bool)m_opaque_sp; } + +SBFormat::SBFormat(const char *format, lldb::SBError &error) { + FormatEntrySP format_entry_sp = std::make_shared<FormatEntity::Entry>(); + Status status = FormatEntity::Parse(format, *format_entry_sp); + + error.SetError(status); + if (error.Success()) + m_opaque_sp = format_entry_sp; +} + +lldb::FormatEntrySP SBFormat::GetFormatEntrySP() const { return m_opaque_sp; } diff --git a/contrib/llvm-project/lldb/source/API/SBFrame.cpp b/contrib/llvm-project/lldb/source/API/SBFrame.cpp new file mode 100644 index 000000000000..47fc88625e30 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBFrame.cpp @@ -0,0 +1,1315 @@ +//===-- SBFrame.cpp -------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <algorithm> +#include <set> +#include <string> + +#include "lldb/API/SBFrame.h" + +#include "lldb/lldb-types.h" + +#include "Utils.h" +#include "lldb/Core/Address.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Core/ValueObjectRegister.h" +#include "lldb/Core/ValueObjectVariable.h" +#include "lldb/Core/ValueObjectConstResult.h" +#include "lldb/Expression/ExpressionVariable.h" +#include "lldb/Expression/UserExpression.h" +#include "lldb/Host/Host.h" +#include "lldb/Symbol/Block.h" +#include "lldb/Symbol/Function.h" +#include "lldb/Symbol/Symbol.h" +#include "lldb/Symbol/SymbolContext.h" +#include "lldb/Symbol/Variable.h" +#include "lldb/Symbol/VariableList.h" +#include "lldb/Target/ExecutionContext.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/RegisterContext.h" +#include "lldb/Target/StackFrame.h" +#include "lldb/Target/StackFrameRecognizer.h" +#include "lldb/Target/StackID.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" +#include "lldb/Utility/ConstString.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/LLDBLog.h" +#include "lldb/Utility/Stream.h" + +#include "lldb/API/SBAddress.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBExpressionOptions.h" +#include "lldb/API/SBFormat.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBSymbolContext.h" +#include "lldb/API/SBThread.h" +#include "lldb/API/SBValue.h" +#include "lldb/API/SBVariablesOptions.h" + +#include "llvm/Support/PrettyStackTrace.h" + +using namespace lldb; +using namespace lldb_private; + +SBFrame::SBFrame() : m_opaque_sp(new ExecutionContextRef()) { + LLDB_INSTRUMENT_VA(this); +} + +SBFrame::SBFrame(const StackFrameSP &lldb_object_sp) + : m_opaque_sp(new ExecutionContextRef(lldb_object_sp)) { + LLDB_INSTRUMENT_VA(this, lldb_object_sp); +} + +SBFrame::SBFrame(const SBFrame &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_sp = clone(rhs.m_opaque_sp); +} + +SBFrame::~SBFrame() = default; + +const SBFrame &SBFrame::operator=(const SBFrame &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_sp = clone(rhs.m_opaque_sp); + return *this; +} + +StackFrameSP SBFrame::GetFrameSP() const { + return (m_opaque_sp ? m_opaque_sp->GetFrameSP() : StackFrameSP()); +} + +void SBFrame::SetFrameSP(const StackFrameSP &lldb_object_sp) { + return m_opaque_sp->SetFrameSP(lldb_object_sp); +} + +bool SBFrame::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBFrame::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) + return GetFrameSP().get() != nullptr; + } + + // Without a target & process we can't have a valid stack frame. + return false; +} + +SBSymbolContext SBFrame::GetSymbolContext(uint32_t resolve_scope) const { + LLDB_INSTRUMENT_VA(this, resolve_scope); + + SBSymbolContext sb_sym_ctx; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + SymbolContextItem scope = static_cast<SymbolContextItem>(resolve_scope); + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + if (StackFrame *frame = exe_ctx.GetFramePtr()) + sb_sym_ctx = frame->GetSymbolContext(scope); + } + } + + return sb_sym_ctx; +} + +SBModule SBFrame::GetModule() const { + LLDB_INSTRUMENT_VA(this); + + SBModule sb_module; + ModuleSP module_sp; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + module_sp = frame->GetSymbolContext(eSymbolContextModule).module_sp; + sb_module.SetSP(module_sp); + } + } + } + + return sb_module; +} + +SBCompileUnit SBFrame::GetCompileUnit() const { + LLDB_INSTRUMENT_VA(this); + + SBCompileUnit sb_comp_unit; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + sb_comp_unit.reset( + frame->GetSymbolContext(eSymbolContextCompUnit).comp_unit); + } + } + } + + return sb_comp_unit; +} + +SBFunction SBFrame::GetFunction() const { + LLDB_INSTRUMENT_VA(this); + + SBFunction sb_function; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + sb_function.reset( + frame->GetSymbolContext(eSymbolContextFunction).function); + } + } + } + + return sb_function; +} + +SBSymbol SBFrame::GetSymbol() const { + LLDB_INSTRUMENT_VA(this); + + SBSymbol sb_symbol; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + sb_symbol.reset(frame->GetSymbolContext(eSymbolContextSymbol).symbol); + } + } + } + + return sb_symbol; +} + +SBBlock SBFrame::GetBlock() const { + LLDB_INSTRUMENT_VA(this); + + SBBlock sb_block; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) + sb_block.SetPtr(frame->GetSymbolContext(eSymbolContextBlock).block); + } + } + return sb_block; +} + +SBBlock SBFrame::GetFrameBlock() const { + LLDB_INSTRUMENT_VA(this); + + SBBlock sb_block; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) + sb_block.SetPtr(frame->GetFrameBlock()); + } + } + return sb_block; +} + +SBLineEntry SBFrame::GetLineEntry() const { + LLDB_INSTRUMENT_VA(this); + + SBLineEntry sb_line_entry; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + sb_line_entry.SetLineEntry( + frame->GetSymbolContext(eSymbolContextLineEntry).line_entry); + } + } + } + return sb_line_entry; +} + +uint32_t SBFrame::GetFrameID() const { + LLDB_INSTRUMENT_VA(this); + + uint32_t frame_idx = UINT32_MAX; + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + if (frame) + frame_idx = frame->GetFrameIndex(); + + return frame_idx; +} + +lldb::addr_t SBFrame::GetCFA() const { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + if (frame) + return frame->GetStackID().GetCallFrameAddress(); + return LLDB_INVALID_ADDRESS; +} + +addr_t SBFrame::GetPC() const { + LLDB_INSTRUMENT_VA(this); + + addr_t addr = LLDB_INVALID_ADDRESS; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + addr = frame->GetFrameCodeAddress().GetOpcodeLoadAddress( + target, AddressClass::eCode); + } + } + } + + return addr; +} + +bool SBFrame::SetPC(addr_t new_pc) { + LLDB_INSTRUMENT_VA(this, new_pc); + + bool ret_val = false; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + if (StackFrame *frame = exe_ctx.GetFramePtr()) { + if (RegisterContextSP reg_ctx_sp = frame->GetRegisterContext()) { + ret_val = reg_ctx_sp->SetPC(new_pc); + } + } + } + } + + return ret_val; +} + +addr_t SBFrame::GetSP() const { + LLDB_INSTRUMENT_VA(this); + + addr_t addr = LLDB_INVALID_ADDRESS; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + if (StackFrame *frame = exe_ctx.GetFramePtr()) { + if (RegisterContextSP reg_ctx_sp = frame->GetRegisterContext()) { + addr = reg_ctx_sp->GetSP(); + } + } + } + } + + return addr; +} + +addr_t SBFrame::GetFP() const { + LLDB_INSTRUMENT_VA(this); + + addr_t addr = LLDB_INVALID_ADDRESS; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + if (StackFrame *frame = exe_ctx.GetFramePtr()) { + if (RegisterContextSP reg_ctx_sp = frame->GetRegisterContext()) { + addr = reg_ctx_sp->GetFP(); + } + } + } + } + + return addr; +} + +SBAddress SBFrame::GetPCAddress() const { + LLDB_INSTRUMENT_VA(this); + + SBAddress sb_addr; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) + sb_addr.SetAddress(frame->GetFrameCodeAddress()); + } + } + return sb_addr; +} + +void SBFrame::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_sp->Clear(); +} + +lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path) { + LLDB_INSTRUMENT_VA(this, var_path); + + SBValue sb_value; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + if (frame && target) { + lldb::DynamicValueType use_dynamic = + frame->CalculateTarget()->GetPreferDynamicValue(); + sb_value = GetValueForVariablePath(var_path, use_dynamic); + } + return sb_value; +} + +lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path, + DynamicValueType use_dynamic) { + LLDB_INSTRUMENT_VA(this, var_path, use_dynamic); + + SBValue sb_value; + if (var_path == nullptr || var_path[0] == '\0') { + return sb_value; + } + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + VariableSP var_sp; + Status error; + ValueObjectSP value_sp(frame->GetValueForVariableExpressionPath( + var_path, eNoDynamicValues, + StackFrame::eExpressionPathOptionCheckPtrVsMember | + StackFrame::eExpressionPathOptionsAllowDirectIVarAccess, + var_sp, error)); + sb_value.SetSP(value_sp, use_dynamic); + } + } + } + return sb_value; +} + +SBValue SBFrame::FindVariable(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + + SBValue value; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + if (frame && target) { + lldb::DynamicValueType use_dynamic = + frame->CalculateTarget()->GetPreferDynamicValue(); + value = FindVariable(name, use_dynamic); + } + return value; +} + +SBValue SBFrame::FindVariable(const char *name, + lldb::DynamicValueType use_dynamic) { + LLDB_INSTRUMENT_VA(this, name, use_dynamic); + + VariableSP var_sp; + SBValue sb_value; + + if (name == nullptr || name[0] == '\0') { + return sb_value; + } + + ValueObjectSP value_sp; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + value_sp = frame->FindVariable(ConstString(name)); + + if (value_sp) + sb_value.SetSP(value_sp, use_dynamic); + } + } + } + + return sb_value; +} + +SBValue SBFrame::FindValue(const char *name, ValueType value_type) { + LLDB_INSTRUMENT_VA(this, name, value_type); + + SBValue value; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + if (frame && target) { + lldb::DynamicValueType use_dynamic = + frame->CalculateTarget()->GetPreferDynamicValue(); + value = FindValue(name, value_type, use_dynamic); + } + return value; +} + +SBValue SBFrame::FindValue(const char *name, ValueType value_type, + lldb::DynamicValueType use_dynamic) { + LLDB_INSTRUMENT_VA(this, name, value_type, use_dynamic); + + SBValue sb_value; + + if (name == nullptr || name[0] == '\0') { + return sb_value; + } + + ValueObjectSP value_sp; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + VariableList variable_list; + + switch (value_type) { + case eValueTypeVariableGlobal: // global variable + case eValueTypeVariableStatic: // static variable + case eValueTypeVariableArgument: // function argument variables + case eValueTypeVariableLocal: // function local variables + case eValueTypeVariableThreadLocal: // thread local variables + { + SymbolContext sc(frame->GetSymbolContext(eSymbolContextBlock)); + + const bool can_create = true; + const bool get_parent_variables = true; + const bool stop_if_block_is_inlined_function = true; + + if (sc.block) + sc.block->AppendVariables( + can_create, get_parent_variables, + stop_if_block_is_inlined_function, + [frame](Variable *v) { return v->IsInScope(frame); }, + &variable_list); + if (value_type == eValueTypeVariableGlobal + || value_type == eValueTypeVariableStatic) { + const bool get_file_globals = true; + VariableList *frame_vars = frame->GetVariableList(get_file_globals, + nullptr); + if (frame_vars) + frame_vars->AppendVariablesIfUnique(variable_list); + } + ConstString const_name(name); + VariableSP variable_sp( + variable_list.FindVariable(const_name, value_type)); + if (variable_sp) { + value_sp = frame->GetValueObjectForFrameVariable(variable_sp, + eNoDynamicValues); + sb_value.SetSP(value_sp, use_dynamic); + } + } break; + + case eValueTypeRegister: // stack frame register value + { + RegisterContextSP reg_ctx(frame->GetRegisterContext()); + if (reg_ctx) { + if (const RegisterInfo *reg_info = + reg_ctx->GetRegisterInfoByName(name)) { + value_sp = ValueObjectRegister::Create(frame, reg_ctx, reg_info); + sb_value.SetSP(value_sp); + } + } + } break; + + case eValueTypeRegisterSet: // A collection of stack frame register + // values + { + RegisterContextSP reg_ctx(frame->GetRegisterContext()); + if (reg_ctx) { + const uint32_t num_sets = reg_ctx->GetRegisterSetCount(); + for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) { + const RegisterSet *reg_set = reg_ctx->GetRegisterSet(set_idx); + if (reg_set && + (llvm::StringRef(reg_set->name).equals_insensitive(name) || + llvm::StringRef(reg_set->short_name) + .equals_insensitive(name))) { + value_sp = + ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx); + sb_value.SetSP(value_sp); + break; + } + } + } + } break; + + case eValueTypeConstResult: // constant result variables + { + ConstString const_name(name); + ExpressionVariableSP expr_var_sp( + target->GetPersistentVariable(const_name)); + if (expr_var_sp) { + value_sp = expr_var_sp->GetValueObject(); + sb_value.SetSP(value_sp, use_dynamic); + } + } break; + + default: + break; + } + } + } + } + + return sb_value; +} + +bool SBFrame::IsEqual(const SBFrame &that) const { + LLDB_INSTRUMENT_VA(this, that); + + lldb::StackFrameSP this_sp = GetFrameSP(); + lldb::StackFrameSP that_sp = that.GetFrameSP(); + return (this_sp && that_sp && this_sp->GetStackID() == that_sp->GetStackID()); +} + +bool SBFrame::operator==(const SBFrame &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return IsEqual(rhs); +} + +bool SBFrame::operator!=(const SBFrame &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return !IsEqual(rhs); +} + +SBThread SBFrame::GetThread() const { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + ThreadSP thread_sp(exe_ctx.GetThreadSP()); + SBThread sb_thread(thread_sp); + + return sb_thread; +} + +const char *SBFrame::Disassemble() const { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (!target || !process) + return nullptr; + + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + if (auto *frame = exe_ctx.GetFramePtr()) + return ConstString(frame->Disassemble()).GetCString(); + } + + return nullptr; +} + +SBValueList SBFrame::GetVariables(bool arguments, bool locals, bool statics, + bool in_scope_only) { + LLDB_INSTRUMENT_VA(this, arguments, locals, statics, in_scope_only); + + SBValueList value_list; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + if (frame && target) { + lldb::DynamicValueType use_dynamic = + frame->CalculateTarget()->GetPreferDynamicValue(); + const bool include_runtime_support_values = + target->GetDisplayRuntimeSupportValues(); + + SBVariablesOptions options; + options.SetIncludeArguments(arguments); + options.SetIncludeLocals(locals); + options.SetIncludeStatics(statics); + options.SetInScopeOnly(in_scope_only); + options.SetIncludeRuntimeSupportValues(include_runtime_support_values); + options.SetUseDynamic(use_dynamic); + + value_list = GetVariables(options); + } + return value_list; +} + +lldb::SBValueList SBFrame::GetVariables(bool arguments, bool locals, + bool statics, bool in_scope_only, + lldb::DynamicValueType use_dynamic) { + LLDB_INSTRUMENT_VA(this, arguments, locals, statics, in_scope_only, + use_dynamic); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + Target *target = exe_ctx.GetTargetPtr(); + const bool include_runtime_support_values = + target ? target->GetDisplayRuntimeSupportValues() : false; + SBVariablesOptions options; + options.SetIncludeArguments(arguments); + options.SetIncludeLocals(locals); + options.SetIncludeStatics(statics); + options.SetInScopeOnly(in_scope_only); + options.SetIncludeRuntimeSupportValues(include_runtime_support_values); + options.SetUseDynamic(use_dynamic); + return GetVariables(options); +} + +SBValueList SBFrame::GetVariables(const lldb::SBVariablesOptions &options) { + LLDB_INSTRUMENT_VA(this, options); + + SBValueList value_list; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + + const bool statics = options.GetIncludeStatics(); + const bool arguments = options.GetIncludeArguments(); + const bool recognized_arguments = + options.GetIncludeRecognizedArguments(SBTarget(exe_ctx.GetTargetSP())); + const bool locals = options.GetIncludeLocals(); + const bool in_scope_only = options.GetInScopeOnly(); + const bool include_runtime_support_values = + options.GetIncludeRuntimeSupportValues(); + const lldb::DynamicValueType use_dynamic = options.GetUseDynamic(); + + + std::set<VariableSP> variable_set; + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + Debugger &dbg = process->GetTarget().GetDebugger(); + VariableList *variable_list = nullptr; + Status var_error; + variable_list = frame->GetVariableList(true, &var_error); + if (var_error.Fail()) + value_list.SetError(var_error); + if (variable_list) { + const size_t num_variables = variable_list->GetSize(); + if (num_variables) { + size_t num_produced = 0; + for (const VariableSP &variable_sp : *variable_list) { + if (INTERRUPT_REQUESTED(dbg, + "Interrupted getting frame variables with {0} of {1} " + "produced.", num_produced, num_variables)) + return {}; + + if (variable_sp) { + bool add_variable = false; + switch (variable_sp->GetScope()) { + case eValueTypeVariableGlobal: + case eValueTypeVariableStatic: + case eValueTypeVariableThreadLocal: + add_variable = statics; + break; + + case eValueTypeVariableArgument: + add_variable = arguments; + break; + + case eValueTypeVariableLocal: + add_variable = locals; + break; + + default: + break; + } + if (add_variable) { + // Only add variables once so we don't end up with duplicates + if (variable_set.find(variable_sp) == variable_set.end()) + variable_set.insert(variable_sp); + else + continue; + + if (in_scope_only && !variable_sp->IsInScope(frame)) + continue; + + ValueObjectSP valobj_sp(frame->GetValueObjectForFrameVariable( + variable_sp, eNoDynamicValues)); + + if (!include_runtime_support_values && valobj_sp != nullptr && + valobj_sp->IsRuntimeSupportValue()) + continue; + + SBValue value_sb; + value_sb.SetSP(valobj_sp, use_dynamic); + value_list.Append(value_sb); + } + } + } + num_produced++; + } + } + if (recognized_arguments) { + auto recognized_frame = frame->GetRecognizedFrame(); + if (recognized_frame) { + ValueObjectListSP recognized_arg_list = + recognized_frame->GetRecognizedArguments(); + if (recognized_arg_list) { + for (auto &rec_value_sp : recognized_arg_list->GetObjects()) { + SBValue value_sb; + value_sb.SetSP(rec_value_sp, use_dynamic); + value_list.Append(value_sb); + } + } + } + } + } + } + } + + return value_list; +} + +SBValueList SBFrame::GetRegisters() { + LLDB_INSTRUMENT_VA(this); + + SBValueList value_list; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + RegisterContextSP reg_ctx(frame->GetRegisterContext()); + if (reg_ctx) { + const uint32_t num_sets = reg_ctx->GetRegisterSetCount(); + for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) { + value_list.Append( + ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx)); + } + } + } + } + } + + return value_list; +} + +SBValue SBFrame::FindRegister(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + + SBValue result; + ValueObjectSP value_sp; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + RegisterContextSP reg_ctx(frame->GetRegisterContext()); + if (reg_ctx) { + if (const RegisterInfo *reg_info = + reg_ctx->GetRegisterInfoByName(name)) { + value_sp = ValueObjectRegister::Create(frame, reg_ctx, reg_info); + result.SetSP(value_sp); + } + } + } + } + } + + return result; +} + +SBError SBFrame::GetDescriptionWithFormat(const SBFormat &format, + SBStream &output) { + Stream &strm = output.ref(); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + SBError error; + + if (!format) { + error.SetErrorString("The provided SBFormat object is invalid"); + return error; + } + + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame && + frame->DumpUsingFormat(strm, format.GetFormatEntrySP().get())) { + return error; + } + } + } + error.SetErrorStringWithFormat( + "It was not possible to generate a frame " + "description with the given format string '%s'", + format.GetFormatEntrySP()->string.c_str()); + return error; +} + +bool SBFrame::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + frame->DumpUsingSettingsFormat(&strm); + } + } + + } else + strm.PutCString("No value"); + + return true; +} + +SBValue SBFrame::EvaluateExpression(const char *expr) { + LLDB_INSTRUMENT_VA(this, expr); + + SBValue result; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + if (frame && target) { + SBExpressionOptions options; + lldb::DynamicValueType fetch_dynamic_value = + frame->CalculateTarget()->GetPreferDynamicValue(); + options.SetFetchDynamicValue(fetch_dynamic_value); + options.SetUnwindOnError(true); + options.SetIgnoreBreakpoints(true); + SourceLanguage language = target->GetLanguage(); + if (!language) + language = frame->GetLanguage(); + options.SetLanguage((SBSourceLanguageName)language.name, language.version); + return EvaluateExpression(expr, options); + } else { + Status error; + error.SetErrorString("can't evaluate expressions when the " + "process is running."); + ValueObjectSP error_val_sp = ValueObjectConstResult::Create(nullptr, error); + result.SetSP(error_val_sp, false); + } + return result; +} + +SBValue +SBFrame::EvaluateExpression(const char *expr, + lldb::DynamicValueType fetch_dynamic_value) { + LLDB_INSTRUMENT_VA(this, expr, fetch_dynamic_value); + + SBExpressionOptions options; + options.SetFetchDynamicValue(fetch_dynamic_value); + options.SetUnwindOnError(true); + options.SetIgnoreBreakpoints(true); + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + SourceLanguage language; + if (target) + language = target->GetLanguage(); + if (!language && frame) + language = frame->GetLanguage(); + options.SetLanguage((SBSourceLanguageName)language.name, language.version); + return EvaluateExpression(expr, options); +} + +SBValue SBFrame::EvaluateExpression(const char *expr, + lldb::DynamicValueType fetch_dynamic_value, + bool unwind_on_error) { + LLDB_INSTRUMENT_VA(this, expr, fetch_dynamic_value, unwind_on_error); + + SBExpressionOptions options; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + options.SetFetchDynamicValue(fetch_dynamic_value); + options.SetUnwindOnError(unwind_on_error); + options.SetIgnoreBreakpoints(true); + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + SourceLanguage language; + if (target) + language = target->GetLanguage(); + if (!language && frame) + language = frame->GetLanguage(); + options.SetLanguage((SBSourceLanguageName)language.name, language.version); + return EvaluateExpression(expr, options); +} + +lldb::SBValue SBFrame::EvaluateExpression(const char *expr, + const SBExpressionOptions &options) { + LLDB_INSTRUMENT_VA(this, expr, options); + + Log *expr_log = GetLog(LLDBLog::Expressions); + + SBValue expr_result; + + if (expr == nullptr || expr[0] == '\0') { + return expr_result; + } + + ValueObjectSP expr_value_sp; + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + std::unique_ptr<llvm::PrettyStackTraceFormat> stack_trace; + if (target->GetDisplayExpressionsInCrashlogs()) { + StreamString frame_description; + frame->DumpUsingSettingsFormat(&frame_description); + stack_trace = std::make_unique<llvm::PrettyStackTraceFormat>( + "SBFrame::EvaluateExpression (expr = \"%s\", fetch_dynamic_value " + "= %u) %s", + expr, options.GetFetchDynamicValue(), + frame_description.GetData()); + } + + target->EvaluateExpression(expr, frame, expr_value_sp, options.ref()); + expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue()); + } + } else { + Status error; + error.SetErrorString("can't evaluate expressions when the " + "process is running."); + expr_value_sp = ValueObjectConstResult::Create(nullptr, error); + expr_result.SetSP(expr_value_sp, false); + } + } else { + Status error; + error.SetErrorString("sbframe object is not valid."); + expr_value_sp = ValueObjectConstResult::Create(nullptr, error); + expr_result.SetSP(expr_value_sp, false); + } + + if (expr_result.GetError().Success()) + LLDB_LOGF(expr_log, + "** [SBFrame::EvaluateExpression] Expression result is " + "%s, summary %s **", + expr_result.GetValue(), expr_result.GetSummary()); + else + LLDB_LOGF(expr_log, + "** [SBFrame::EvaluateExpression] Expression evaluation failed: " + "%s **", + expr_result.GetError().GetCString()); + + return expr_result; +} + +bool SBFrame::IsInlined() { + LLDB_INSTRUMENT_VA(this); + + return static_cast<const SBFrame *>(this)->IsInlined(); +} + +bool SBFrame::IsInlined() const { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + + Block *block = frame->GetSymbolContext(eSymbolContextBlock).block; + if (block) + return block->GetContainingInlinedBlock() != nullptr; + } + } + } + return false; +} + +bool SBFrame::IsArtificial() { + LLDB_INSTRUMENT_VA(this); + + return static_cast<const SBFrame *>(this)->IsArtificial(); +} + +bool SBFrame::IsArtificial() const { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + if (frame) + return frame->IsArtificial(); + + return false; +} + +const char *SBFrame::GetFunctionName() { + LLDB_INSTRUMENT_VA(this); + + return static_cast<const SBFrame *>(this)->GetFunctionName(); +} + +lldb::LanguageType SBFrame::GuessLanguage() const { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + return frame->GuessLanguage().AsLanguageType(); + } + } + } + return eLanguageTypeUnknown; +} + +const char *SBFrame::GetFunctionName() const { + LLDB_INSTRUMENT_VA(this); + + const char *name = nullptr; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction | + eSymbolContextBlock | + eSymbolContextSymbol)); + if (sc.block) { + Block *inlined_block = sc.block->GetContainingInlinedBlock(); + if (inlined_block) { + const InlineFunctionInfo *inlined_info = + inlined_block->GetInlinedFunctionInfo(); + name = inlined_info->GetName().AsCString(); + } + } + + if (name == nullptr) { + if (sc.function) + name = sc.function->GetName().GetCString(); + } + + if (name == nullptr) { + if (sc.symbol) + name = sc.symbol->GetName().GetCString(); + } + } + } + } + return name; +} + +const char *SBFrame::GetDisplayFunctionName() { + LLDB_INSTRUMENT_VA(this); + + const char *name = nullptr; + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction | + eSymbolContextBlock | + eSymbolContextSymbol)); + if (sc.block) { + Block *inlined_block = sc.block->GetContainingInlinedBlock(); + if (inlined_block) { + const InlineFunctionInfo *inlined_info = + inlined_block->GetInlinedFunctionInfo(); + name = inlined_info->GetDisplayName().AsCString(); + } + } + + if (name == nullptr) { + if (sc.function) + name = sc.function->GetDisplayName().GetCString(); + } + + if (name == nullptr) { + if (sc.symbol) + name = sc.symbol->GetDisplayName().GetCString(); + } + } + } + } + return name; +} diff --git a/contrib/llvm-project/lldb/source/API/SBFunction.cpp b/contrib/llvm-project/lldb/source/API/SBFunction.cpp new file mode 100644 index 000000000000..6a97352fc2c2 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBFunction.cpp @@ -0,0 +1,245 @@ +//===-- SBFunction.cpp ----------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBFunction.h" +#include "lldb/API/SBAddressRange.h" +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBStream.h" +#include "lldb/Core/Disassembler.h" +#include "lldb/Core/Module.h" +#include "lldb/Symbol/CompileUnit.h" +#include "lldb/Symbol/Function.h" +#include "lldb/Symbol/Type.h" +#include "lldb/Symbol/VariableList.h" +#include "lldb/Target/ExecutionContext.h" +#include "lldb/Target/Target.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +SBFunction::SBFunction() { LLDB_INSTRUMENT_VA(this); } + +SBFunction::SBFunction(lldb_private::Function *lldb_object_ptr) + : m_opaque_ptr(lldb_object_ptr) {} + +SBFunction::SBFunction(const lldb::SBFunction &rhs) + : m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const SBFunction &SBFunction::operator=(const SBFunction &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_ptr = rhs.m_opaque_ptr; + return *this; +} + +SBFunction::~SBFunction() { m_opaque_ptr = nullptr; } + +bool SBFunction::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBFunction::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_ptr != nullptr; +} + +const char *SBFunction::GetName() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return m_opaque_ptr->GetName().AsCString(); + + return nullptr; +} + +const char *SBFunction::GetDisplayName() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return m_opaque_ptr->GetMangled().GetDisplayDemangledName().AsCString(); + + return nullptr; +} + +const char *SBFunction::GetMangledName() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return m_opaque_ptr->GetMangled().GetMangledName().AsCString(); + return nullptr; +} + +bool SBFunction::operator==(const SBFunction &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_ptr == rhs.m_opaque_ptr; +} + +bool SBFunction::operator!=(const SBFunction &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_ptr != rhs.m_opaque_ptr; +} + +bool SBFunction::GetDescription(SBStream &s) { + LLDB_INSTRUMENT_VA(this, s); + + if (m_opaque_ptr) { + s.Printf("SBFunction: id = 0x%8.8" PRIx64 ", name = %s", + m_opaque_ptr->GetID(), m_opaque_ptr->GetName().AsCString()); + Type *func_type = m_opaque_ptr->GetType(); + if (func_type) + s.Printf(", type = %s", func_type->GetName().AsCString()); + return true; + } + s.Printf("No value"); + return false; +} + +SBInstructionList SBFunction::GetInstructions(SBTarget target) { + LLDB_INSTRUMENT_VA(this, target); + + return GetInstructions(target, nullptr); +} + +SBInstructionList SBFunction::GetInstructions(SBTarget target, + const char *flavor) { + LLDB_INSTRUMENT_VA(this, target, flavor); + + SBInstructionList sb_instructions; + if (m_opaque_ptr) { + TargetSP target_sp(target.GetSP()); + std::unique_lock<std::recursive_mutex> lock; + ModuleSP module_sp( + m_opaque_ptr->GetAddressRange().GetBaseAddress().GetModule()); + if (target_sp && module_sp) { + lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex()); + const bool force_live_memory = true; + sb_instructions.SetDisassembler(Disassembler::DisassembleRange( + module_sp->GetArchitecture(), nullptr, flavor, *target_sp, + m_opaque_ptr->GetAddressRange(), force_live_memory)); + } + } + return sb_instructions; +} + +lldb_private::Function *SBFunction::get() { return m_opaque_ptr; } + +void SBFunction::reset(lldb_private::Function *lldb_object_ptr) { + m_opaque_ptr = lldb_object_ptr; +} + +SBAddress SBFunction::GetStartAddress() { + LLDB_INSTRUMENT_VA(this); + + SBAddress addr; + if (m_opaque_ptr) + addr.SetAddress(m_opaque_ptr->GetAddressRange().GetBaseAddress()); + return addr; +} + +SBAddress SBFunction::GetEndAddress() { + LLDB_INSTRUMENT_VA(this); + + SBAddress addr; + if (m_opaque_ptr) { + addr_t byte_size = m_opaque_ptr->GetAddressRange().GetByteSize(); + if (byte_size > 0) { + addr.SetAddress(m_opaque_ptr->GetAddressRange().GetBaseAddress()); + addr->Slide(byte_size); + } + } + return addr; +} + +lldb::SBAddressRangeList SBFunction::GetRanges() { + LLDB_INSTRUMENT_VA(this); + + lldb::SBAddressRangeList ranges; + if (m_opaque_ptr) { + lldb::SBAddressRange range; + (*range.m_opaque_up) = m_opaque_ptr->GetAddressRange(); + ranges.Append(std::move(range)); + } + + return ranges; +} + +const char *SBFunction::GetArgumentName(uint32_t arg_idx) { + LLDB_INSTRUMENT_VA(this, arg_idx); + + if (!m_opaque_ptr) + return nullptr; + + Block &block = m_opaque_ptr->GetBlock(true); + VariableListSP variable_list_sp = block.GetBlockVariableList(true); + if (!variable_list_sp) + return nullptr; + + VariableList arguments; + variable_list_sp->AppendVariablesWithScope(eValueTypeVariableArgument, + arguments, true); + lldb::VariableSP variable_sp = arguments.GetVariableAtIndex(arg_idx); + if (!variable_sp) + return nullptr; + + return variable_sp->GetName().GetCString(); +} + +uint32_t SBFunction::GetPrologueByteSize() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return m_opaque_ptr->GetPrologueByteSize(); + return 0; +} + +SBType SBFunction::GetType() { + LLDB_INSTRUMENT_VA(this); + + SBType sb_type; + if (m_opaque_ptr) { + Type *function_type = m_opaque_ptr->GetType(); + if (function_type) + sb_type.ref().SetType(function_type->shared_from_this()); + } + return sb_type; +} + +SBBlock SBFunction::GetBlock() { + LLDB_INSTRUMENT_VA(this); + + SBBlock sb_block; + if (m_opaque_ptr) + sb_block.SetPtr(&m_opaque_ptr->GetBlock(true)); + return sb_block; +} + +lldb::LanguageType SBFunction::GetLanguage() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) { + if (m_opaque_ptr->GetCompileUnit()) + return m_opaque_ptr->GetCompileUnit()->GetLanguage(); + } + return lldb::eLanguageTypeUnknown; +} + +bool SBFunction::GetIsOptimized() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) { + if (m_opaque_ptr->GetCompileUnit()) + return m_opaque_ptr->GetCompileUnit()->GetIsOptimized(); + } + return false; +} diff --git a/contrib/llvm-project/lldb/source/API/SBHostOS.cpp b/contrib/llvm-project/lldb/source/API/SBHostOS.cpp new file mode 100644 index 000000000000..a77a703bba37 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBHostOS.cpp @@ -0,0 +1,123 @@ +//===-- SBHostOS.cpp ------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBHostOS.h" +#include "lldb/API/SBError.h" +#include "lldb/Host/Config.h" +#include "lldb/Host/FileSystem.h" +#include "lldb/Host/Host.h" +#include "lldb/Host/HostInfo.h" +#include "lldb/Host/HostNativeThread.h" +#include "lldb/Host/HostThread.h" +#include "lldb/Host/ThreadLauncher.h" +#include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/Instrumentation.h" + +#include "Plugins/ExpressionParser/Clang/ClangHost.h" +#if LLDB_ENABLE_PYTHON +#include "Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h" +#endif + +#include "llvm/ADT/SmallString.h" +#include "llvm/Support/Path.h" + +using namespace lldb; +using namespace lldb_private; + +SBFileSpec SBHostOS::GetProgramFileSpec() { + LLDB_INSTRUMENT(); + + SBFileSpec sb_filespec; + sb_filespec.SetFileSpec(HostInfo::GetProgramFileSpec()); + return sb_filespec; +} + +SBFileSpec SBHostOS::GetLLDBPythonPath() { + LLDB_INSTRUMENT(); + + return GetLLDBPath(ePathTypePythonDir); +} + +SBFileSpec SBHostOS::GetLLDBPath(lldb::PathType path_type) { + LLDB_INSTRUMENT_VA(path_type); + + FileSpec fspec; + switch (path_type) { + case ePathTypeLLDBShlibDir: + fspec = HostInfo::GetShlibDir(); + break; + case ePathTypeSupportExecutableDir: + fspec = HostInfo::GetSupportExeDir(); + break; + case ePathTypeHeaderDir: + fspec = HostInfo::GetHeaderDir(); + break; + case ePathTypePythonDir: +#if LLDB_ENABLE_PYTHON + fspec = ScriptInterpreterPython::GetPythonDir(); +#endif + break; + case ePathTypeLLDBSystemPlugins: + fspec = HostInfo::GetSystemPluginDir(); + break; + case ePathTypeLLDBUserPlugins: + fspec = HostInfo::GetUserPluginDir(); + break; + case ePathTypeLLDBTempSystemDir: + fspec = HostInfo::GetProcessTempDir(); + break; + case ePathTypeGlobalLLDBTempSystemDir: + fspec = HostInfo::GetGlobalTempDir(); + break; + case ePathTypeClangDir: + fspec = GetClangResourceDir(); + break; + } + + SBFileSpec sb_fspec; + sb_fspec.SetFileSpec(fspec); + return sb_fspec; +} + +SBFileSpec SBHostOS::GetUserHomeDirectory() { + LLDB_INSTRUMENT(); + + FileSpec homedir; + FileSystem::Instance().GetHomeDirectory(homedir); + FileSystem::Instance().Resolve(homedir); + + SBFileSpec sb_fspec; + sb_fspec.SetFileSpec(homedir); + + return sb_fspec; +} + +lldb::thread_t SBHostOS::ThreadCreate(const char *name, + lldb::thread_func_t thread_function, + void *thread_arg, SBError *error_ptr) { + LLDB_INSTRUMENT_VA(name, thread_function, thread_arg, error_ptr); + return LLDB_INVALID_HOST_THREAD; +} + +void SBHostOS::ThreadCreated(const char *name) { LLDB_INSTRUMENT_VA(name); } + +bool SBHostOS::ThreadCancel(lldb::thread_t thread, SBError *error_ptr) { + LLDB_INSTRUMENT_VA(thread, error_ptr); + return false; +} + +bool SBHostOS::ThreadDetach(lldb::thread_t thread, SBError *error_ptr) { + LLDB_INSTRUMENT_VA(thread, error_ptr); + return false; +} + +bool SBHostOS::ThreadJoin(lldb::thread_t thread, lldb::thread_result_t *result, + SBError *error_ptr) { + LLDB_INSTRUMENT_VA(thread, result, error_ptr); + return false; +} diff --git a/contrib/llvm-project/lldb/source/API/SBInstruction.cpp b/contrib/llvm-project/lldb/source/API/SBInstruction.cpp new file mode 100644 index 000000000000..30703eea6fa6 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBInstruction.cpp @@ -0,0 +1,350 @@ +//===-- SBInstruction.cpp -------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBInstruction.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBAddress.h" +#include "lldb/API/SBFrame.h" +#include "lldb/API/SBFile.h" + +#include "lldb/API/SBInstruction.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBTarget.h" +#include "lldb/Core/Disassembler.h" +#include "lldb/Core/EmulateInstruction.h" +#include "lldb/Core/Module.h" +#include "lldb/Host/HostInfo.h" +#include "lldb/Host/StreamFile.h" +#include "lldb/Target/ExecutionContext.h" +#include "lldb/Target/StackFrame.h" +#include "lldb/Target/Target.h" +#include "lldb/Utility/ArchSpec.h" +#include "lldb/Utility/DataBufferHeap.h" +#include "lldb/Utility/DataExtractor.h" + +#include <memory> + +// We recently fixed a leak in one of the Instruction subclasses where the +// instruction will only hold a weak reference to the disassembler to avoid a +// cycle that was keeping both objects alive (leak) and we need the +// InstructionImpl class to make sure our public API behaves as users would +// expect. Calls in our public API allow clients to do things like: +// +// 1 lldb::SBInstruction inst; +// 2 inst = target.ReadInstructions(pc, 1).GetInstructionAtIndex(0) +// 3 if (inst.DoesBranch()) +// 4 ... +// +// There was a temporary lldb::DisassemblerSP object created in the +// SBInstructionList that was returned by lldb.target.ReadInstructions() that +// will go away after line 2 but the "inst" object should be able to still +// answer questions about itself. So we make sure that any SBInstruction +// objects that are given out have a strong reference to the disassembler and +// the instruction so that the object can live and successfully respond to all +// queries. +class InstructionImpl { +public: + InstructionImpl(const lldb::DisassemblerSP &disasm_sp, + const lldb::InstructionSP &inst_sp) + : m_disasm_sp(disasm_sp), m_inst_sp(inst_sp) {} + + lldb::InstructionSP GetSP() const { return m_inst_sp; } + + bool IsValid() const { return (bool)m_inst_sp; } + +protected: + lldb::DisassemblerSP m_disasm_sp; // Can be empty/invalid + lldb::InstructionSP m_inst_sp; +}; + +using namespace lldb; +using namespace lldb_private; + +SBInstruction::SBInstruction() { LLDB_INSTRUMENT_VA(this); } + +SBInstruction::SBInstruction(const lldb::DisassemblerSP &disasm_sp, + const lldb::InstructionSP &inst_sp) + : m_opaque_sp(new InstructionImpl(disasm_sp, inst_sp)) {} + +SBInstruction::SBInstruction(const SBInstruction &rhs) + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const SBInstruction &SBInstruction::operator=(const SBInstruction &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; +} + +SBInstruction::~SBInstruction() = default; + +bool SBInstruction::IsValid() { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBInstruction::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp && m_opaque_sp->IsValid(); +} + +SBAddress SBInstruction::GetAddress() { + LLDB_INSTRUMENT_VA(this); + + SBAddress sb_addr; + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp && inst_sp->GetAddress().IsValid()) + sb_addr.SetAddress(inst_sp->GetAddress()); + return sb_addr; +} + +const char *SBInstruction::GetMnemonic(SBTarget target) { + LLDB_INSTRUMENT_VA(this, target); + + lldb::InstructionSP inst_sp(GetOpaque()); + if (!inst_sp) + return nullptr; + + ExecutionContext exe_ctx; + TargetSP target_sp(target.GetSP()); + std::unique_lock<std::recursive_mutex> lock; + if (target_sp) { + lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex()); + + target_sp->CalculateExecutionContext(exe_ctx); + exe_ctx.SetProcessSP(target_sp->GetProcessSP()); + } + return ConstString(inst_sp->GetMnemonic(&exe_ctx)).GetCString(); +} + +const char *SBInstruction::GetOperands(SBTarget target) { + LLDB_INSTRUMENT_VA(this, target); + + lldb::InstructionSP inst_sp(GetOpaque()); + if (!inst_sp) + return nullptr; + + ExecutionContext exe_ctx; + TargetSP target_sp(target.GetSP()); + std::unique_lock<std::recursive_mutex> lock; + if (target_sp) { + lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex()); + + target_sp->CalculateExecutionContext(exe_ctx); + exe_ctx.SetProcessSP(target_sp->GetProcessSP()); + } + return ConstString(inst_sp->GetOperands(&exe_ctx)).GetCString(); +} + +const char *SBInstruction::GetComment(SBTarget target) { + LLDB_INSTRUMENT_VA(this, target); + + lldb::InstructionSP inst_sp(GetOpaque()); + if (!inst_sp) + return nullptr; + + ExecutionContext exe_ctx; + TargetSP target_sp(target.GetSP()); + std::unique_lock<std::recursive_mutex> lock; + if (target_sp) { + lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex()); + + target_sp->CalculateExecutionContext(exe_ctx); + exe_ctx.SetProcessSP(target_sp->GetProcessSP()); + } + return ConstString(inst_sp->GetComment(&exe_ctx)).GetCString(); +} + +lldb::InstructionControlFlowKind SBInstruction::GetControlFlowKind(lldb::SBTarget target) { + LLDB_INSTRUMENT_VA(this, target); + + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) { + ExecutionContext exe_ctx; + TargetSP target_sp(target.GetSP()); + std::unique_lock<std::recursive_mutex> lock; + if (target_sp) { + lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex()); + + target_sp->CalculateExecutionContext(exe_ctx); + exe_ctx.SetProcessSP(target_sp->GetProcessSP()); + } + return inst_sp->GetControlFlowKind(&exe_ctx); + } + return lldb::eInstructionControlFlowKindUnknown; +} + +size_t SBInstruction::GetByteSize() { + LLDB_INSTRUMENT_VA(this); + + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) + return inst_sp->GetOpcode().GetByteSize(); + return 0; +} + +SBData SBInstruction::GetData(SBTarget target) { + LLDB_INSTRUMENT_VA(this, target); + + lldb::SBData sb_data; + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) { + DataExtractorSP data_extractor_sp(new DataExtractor()); + if (inst_sp->GetData(*data_extractor_sp)) { + sb_data.SetOpaque(data_extractor_sp); + } + } + return sb_data; +} + +bool SBInstruction::DoesBranch() { + LLDB_INSTRUMENT_VA(this); + + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) + return inst_sp->DoesBranch(); + return false; +} + +bool SBInstruction::HasDelaySlot() { + LLDB_INSTRUMENT_VA(this); + + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) + return inst_sp->HasDelaySlot(); + return false; +} + +bool SBInstruction::CanSetBreakpoint() { + LLDB_INSTRUMENT_VA(this); + + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) + return inst_sp->CanSetBreakpoint(); + return false; +} + +lldb::InstructionSP SBInstruction::GetOpaque() { + if (m_opaque_sp) + return m_opaque_sp->GetSP(); + else + return lldb::InstructionSP(); +} + +void SBInstruction::SetOpaque(const lldb::DisassemblerSP &disasm_sp, + const lldb::InstructionSP &inst_sp) { + m_opaque_sp = std::make_shared<InstructionImpl>(disasm_sp, inst_sp); +} + +bool SBInstruction::GetDescription(lldb::SBStream &s) { + LLDB_INSTRUMENT_VA(this, s); + + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) { + SymbolContext sc; + const Address &addr = inst_sp->GetAddress(); + ModuleSP module_sp(addr.GetModule()); + if (module_sp) + module_sp->ResolveSymbolContextForAddress(addr, eSymbolContextEverything, + sc); + // Use the "ref()" instead of the "get()" accessor in case the SBStream + // didn't have a stream already created, one will get created... + FormatEntity::Entry format; + FormatEntity::Parse("${addr}: ", format); + inst_sp->Dump(&s.ref(), 0, true, false, /*show_control_flow_kind=*/false, + nullptr, &sc, nullptr, &format, 0); + return true; + } + return false; +} + +void SBInstruction::Print(FILE *outp) { + LLDB_INSTRUMENT_VA(this, outp); + FileSP out = std::make_shared<NativeFile>(outp, /*take_ownership=*/false); + Print(out); +} + +void SBInstruction::Print(SBFile out) { + LLDB_INSTRUMENT_VA(this, out); + Print(out.m_opaque_sp); +} + +void SBInstruction::Print(FileSP out_sp) { + LLDB_INSTRUMENT_VA(this, out_sp); + + if (!out_sp || !out_sp->IsValid()) + return; + + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) { + SymbolContext sc; + const Address &addr = inst_sp->GetAddress(); + ModuleSP module_sp(addr.GetModule()); + if (module_sp) + module_sp->ResolveSymbolContextForAddress(addr, eSymbolContextEverything, + sc); + StreamFile out_stream(out_sp); + FormatEntity::Entry format; + FormatEntity::Parse("${addr}: ", format); + inst_sp->Dump(&out_stream, 0, true, false, /*show_control_flow_kind=*/false, + nullptr, &sc, nullptr, &format, 0); + } +} + +bool SBInstruction::EmulateWithFrame(lldb::SBFrame &frame, + uint32_t evaluate_options) { + LLDB_INSTRUMENT_VA(this, frame, evaluate_options); + + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) { + lldb::StackFrameSP frame_sp(frame.GetFrameSP()); + + if (frame_sp) { + lldb_private::ExecutionContext exe_ctx; + frame_sp->CalculateExecutionContext(exe_ctx); + lldb_private::Target *target = exe_ctx.GetTargetPtr(); + lldb_private::ArchSpec arch = target->GetArchitecture(); + + return inst_sp->Emulate( + arch, evaluate_options, (void *)frame_sp.get(), + &lldb_private::EmulateInstruction::ReadMemoryFrame, + &lldb_private::EmulateInstruction::WriteMemoryFrame, + &lldb_private::EmulateInstruction::ReadRegisterFrame, + &lldb_private::EmulateInstruction::WriteRegisterFrame); + } + } + return false; +} + +bool SBInstruction::DumpEmulation(const char *triple) { + LLDB_INSTRUMENT_VA(this, triple); + + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp && triple) { + return inst_sp->DumpEmulation(HostInfo::GetAugmentedArchSpec(triple)); + } + return false; +} + +bool SBInstruction::TestEmulation(lldb::SBStream &output_stream, + const char *test_file) { + LLDB_INSTRUMENT_VA(this, output_stream, test_file); + + if (!m_opaque_sp) + SetOpaque(lldb::DisassemblerSP(), + lldb::InstructionSP(new PseudoInstruction())); + + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) + return inst_sp->TestEmulation(output_stream.ref(), test_file); + return false; +} diff --git a/contrib/llvm-project/lldb/source/API/SBInstructionList.cpp b/contrib/llvm-project/lldb/source/API/SBInstructionList.cpp new file mode 100644 index 000000000000..3f37b984cb46 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBInstructionList.cpp @@ -0,0 +1,190 @@ +//===-- SBInstructionList.cpp ---------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBInstructionList.h" +#include "lldb/API/SBAddress.h" +#include "lldb/API/SBFile.h" +#include "lldb/API/SBInstruction.h" +#include "lldb/API/SBStream.h" +#include "lldb/Core/Disassembler.h" +#include "lldb/Core/Module.h" +#include "lldb/Host/StreamFile.h" +#include "lldb/Symbol/SymbolContext.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Stream.h" + +using namespace lldb; +using namespace lldb_private; + +SBInstructionList::SBInstructionList() { LLDB_INSTRUMENT_VA(this); } + +SBInstructionList::SBInstructionList(const SBInstructionList &rhs) + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const SBInstructionList &SBInstructionList:: +operator=(const SBInstructionList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; +} + +SBInstructionList::~SBInstructionList() = default; + +bool SBInstructionList::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBInstructionList::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} + +size_t SBInstructionList::GetSize() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + return m_opaque_sp->GetInstructionList().GetSize(); + return 0; +} + +SBInstruction SBInstructionList::GetInstructionAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBInstruction inst; + if (m_opaque_sp && idx < m_opaque_sp->GetInstructionList().GetSize()) + inst.SetOpaque( + m_opaque_sp, + m_opaque_sp->GetInstructionList().GetInstructionAtIndex(idx)); + return inst; +} + +size_t SBInstructionList::GetInstructionsCount(const SBAddress &start, + const SBAddress &end, + bool canSetBreakpoint) { + LLDB_INSTRUMENT_VA(this, start, end, canSetBreakpoint); + + size_t num_instructions = GetSize(); + size_t i = 0; + SBAddress addr; + size_t lower_index = 0; + size_t upper_index = 0; + size_t instructions_to_skip = 0; + for (i = 0; i < num_instructions; ++i) { + addr = GetInstructionAtIndex(i).GetAddress(); + if (start == addr) + lower_index = i; + if (end == addr) + upper_index = i; + } + if (canSetBreakpoint) + for (i = lower_index; i <= upper_index; ++i) { + SBInstruction insn = GetInstructionAtIndex(i); + if (!insn.CanSetBreakpoint()) + ++instructions_to_skip; + } + return upper_index - lower_index - instructions_to_skip; +} + +void SBInstructionList::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_sp.reset(); +} + +void SBInstructionList::AppendInstruction(SBInstruction insn) { + LLDB_INSTRUMENT_VA(this, insn); +} + +void SBInstructionList::SetDisassembler(const lldb::DisassemblerSP &opaque_sp) { + m_opaque_sp = opaque_sp; +} + +void SBInstructionList::Print(FILE *out) { + LLDB_INSTRUMENT_VA(this, out); + if (out == nullptr) + return; + StreamFile stream(out, false); + GetDescription(stream); +} + +void SBInstructionList::Print(SBFile out) { + LLDB_INSTRUMENT_VA(this, out); + if (!out.IsValid()) + return; + StreamFile stream(out.m_opaque_sp); + GetDescription(stream); +} + +void SBInstructionList::Print(FileSP out_sp) { + LLDB_INSTRUMENT_VA(this, out_sp); + if (!out_sp || !out_sp->IsValid()) + return; + StreamFile stream(out_sp); + GetDescription(stream); +} + +bool SBInstructionList::GetDescription(lldb::SBStream &stream) { + LLDB_INSTRUMENT_VA(this, stream); + return GetDescription(stream.ref()); +} + +bool SBInstructionList::GetDescription(Stream &sref) { + + if (m_opaque_sp) { + size_t num_instructions = GetSize(); + if (num_instructions) { + // Call the ref() to make sure a stream is created if one deesn't exist + // already inside description... + const uint32_t max_opcode_byte_size = + m_opaque_sp->GetInstructionList().GetMaxOpcocdeByteSize(); + FormatEntity::Entry format; + FormatEntity::Parse("${addr}: ", format); + SymbolContext sc; + SymbolContext prev_sc; + for (size_t i = 0; i < num_instructions; ++i) { + Instruction *inst = + m_opaque_sp->GetInstructionList().GetInstructionAtIndex(i).get(); + if (inst == nullptr) + break; + + const Address &addr = inst->GetAddress(); + prev_sc = sc; + ModuleSP module_sp(addr.GetModule()); + if (module_sp) { + module_sp->ResolveSymbolContextForAddress( + addr, eSymbolContextEverything, sc); + } + + inst->Dump(&sref, max_opcode_byte_size, true, false, + /*show_control_flow_kind=*/false, nullptr, &sc, &prev_sc, + &format, 0); + sref.EOL(); + } + return true; + } + } + return false; +} + +bool SBInstructionList::DumpEmulationForAllInstructions(const char *triple) { + LLDB_INSTRUMENT_VA(this, triple); + + if (m_opaque_sp) { + size_t len = GetSize(); + for (size_t i = 0; i < len; ++i) { + if (!GetInstructionAtIndex((uint32_t)i).DumpEmulation(triple)) + return false; + } + } + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBLanguageRuntime.cpp b/contrib/llvm-project/lldb/source/API/SBLanguageRuntime.cpp new file mode 100644 index 000000000000..958652ab6f13 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBLanguageRuntime.cpp @@ -0,0 +1,68 @@ +//===-- SBLanguageRuntime.cpp ---------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBLanguageRuntime.h" +#include "lldb/Target/Language.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +lldb::LanguageType +SBLanguageRuntime::GetLanguageTypeFromString(const char *string) { + LLDB_INSTRUMENT_VA(string); + + return Language::GetLanguageTypeFromString(llvm::StringRef(string)); +} + +const char * +SBLanguageRuntime::GetNameForLanguageType(lldb::LanguageType language) { + LLDB_INSTRUMENT_VA(language); + + return Language::GetNameForLanguageType(language); +} + +bool SBLanguageRuntime::LanguageIsCPlusPlus(lldb::LanguageType language) { + return Language::LanguageIsCPlusPlus(language); +} + +bool SBLanguageRuntime::LanguageIsObjC(lldb::LanguageType language) { + return Language::LanguageIsObjC(language); +} + +bool SBLanguageRuntime::LanguageIsCFamily(lldb::LanguageType language) { + return Language::LanguageIsCFamily(language); +} + +bool SBLanguageRuntime::SupportsExceptionBreakpointsOnThrow( + lldb::LanguageType language) { + if (Language *lang_plugin = Language::FindPlugin(language)) + return lang_plugin->SupportsExceptionBreakpointsOnThrow(); + return false; +} + +bool SBLanguageRuntime::SupportsExceptionBreakpointsOnCatch( + lldb::LanguageType language) { + if (Language *lang_plugin = Language::FindPlugin(language)) + return lang_plugin->SupportsExceptionBreakpointsOnCatch(); + return false; +} + +const char * +SBLanguageRuntime::GetThrowKeywordForLanguage(lldb::LanguageType language) { + if (Language *lang_plugin = Language::FindPlugin(language)) + return ConstString(lang_plugin->GetThrowKeyword()).AsCString(); + return nullptr; +} + +const char * +SBLanguageRuntime::GetCatchKeywordForLanguage(lldb::LanguageType language) { + if (Language *lang_plugin = Language::FindPlugin(language)) + return ConstString(lang_plugin->GetCatchKeyword()).AsCString(); + return nullptr; +} diff --git a/contrib/llvm-project/lldb/source/API/SBLaunchInfo.cpp b/contrib/llvm-project/lldb/source/API/SBLaunchInfo.cpp new file mode 100644 index 000000000000..d6b52e8a67a4 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBLaunchInfo.cpp @@ -0,0 +1,406 @@ +//===-- SBLaunchInfo.cpp --------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBLaunchInfo.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBEnvironment.h" +#include "lldb/API/SBError.h" +#include "lldb/API/SBFileSpec.h" +#include "lldb/API/SBListener.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStructuredData.h" +#include "lldb/Core/StructuredDataImpl.h" +#include "lldb/Host/ProcessLaunchInfo.h" +#include "lldb/Utility/Listener.h" +#include "lldb/Utility/ScriptedMetadata.h" + +using namespace lldb; +using namespace lldb_private; + +class lldb_private::SBLaunchInfoImpl : public ProcessLaunchInfo { +public: + SBLaunchInfoImpl() : m_envp(GetEnvironment().getEnvp()) {} + + const char *const *GetEnvp() const { return m_envp; } + void RegenerateEnvp() { m_envp = GetEnvironment().getEnvp(); } + + SBLaunchInfoImpl &operator=(const ProcessLaunchInfo &rhs) { + ProcessLaunchInfo::operator=(rhs); + RegenerateEnvp(); + return *this; + } + +private: + Environment::Envp m_envp; +}; + +SBLaunchInfo::SBLaunchInfo(const char **argv) + : m_opaque_sp(new SBLaunchInfoImpl()) { + LLDB_INSTRUMENT_VA(this, argv); + + m_opaque_sp->GetFlags().Reset(eLaunchFlagDebug | eLaunchFlagDisableASLR); + if (argv && argv[0]) + m_opaque_sp->GetArguments().SetArguments(argv); +} + +SBLaunchInfo::SBLaunchInfo(const SBLaunchInfo &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_sp = rhs.m_opaque_sp; +} + +SBLaunchInfo &SBLaunchInfo::operator=(const SBLaunchInfo &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_sp = rhs.m_opaque_sp; + return *this; +} + +SBLaunchInfo::~SBLaunchInfo() = default; + +const lldb_private::ProcessLaunchInfo &SBLaunchInfo::ref() const { + return *m_opaque_sp; +} + +void SBLaunchInfo::set_ref(const ProcessLaunchInfo &info) { + *m_opaque_sp = info; +} + +lldb::pid_t SBLaunchInfo::GetProcessID() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetProcessID(); +} + +uint32_t SBLaunchInfo::GetUserID() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetUserID(); +} + +uint32_t SBLaunchInfo::GetGroupID() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetGroupID(); +} + +bool SBLaunchInfo::UserIDIsValid() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->UserIDIsValid(); +} + +bool SBLaunchInfo::GroupIDIsValid() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GroupIDIsValid(); +} + +void SBLaunchInfo::SetUserID(uint32_t uid) { + LLDB_INSTRUMENT_VA(this, uid); + + m_opaque_sp->SetUserID(uid); +} + +void SBLaunchInfo::SetGroupID(uint32_t gid) { + LLDB_INSTRUMENT_VA(this, gid); + + m_opaque_sp->SetGroupID(gid); +} + +SBFileSpec SBLaunchInfo::GetExecutableFile() { + LLDB_INSTRUMENT_VA(this); + + return SBFileSpec(m_opaque_sp->GetExecutableFile()); +} + +void SBLaunchInfo::SetExecutableFile(SBFileSpec exe_file, + bool add_as_first_arg) { + LLDB_INSTRUMENT_VA(this, exe_file, add_as_first_arg); + + m_opaque_sp->SetExecutableFile(exe_file.ref(), add_as_first_arg); +} + +SBListener SBLaunchInfo::GetListener() { + LLDB_INSTRUMENT_VA(this); + + return SBListener(m_opaque_sp->GetListener()); +} + +void SBLaunchInfo::SetListener(SBListener &listener) { + LLDB_INSTRUMENT_VA(this, listener); + + m_opaque_sp->SetListener(listener.GetSP()); +} + +uint32_t SBLaunchInfo::GetNumArguments() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetArguments().GetArgumentCount(); +} + +const char *SBLaunchInfo::GetArgumentAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + return ConstString(m_opaque_sp->GetArguments().GetArgumentAtIndex(idx)) + .GetCString(); +} + +void SBLaunchInfo::SetArguments(const char **argv, bool append) { + LLDB_INSTRUMENT_VA(this, argv, append); + + if (append) { + if (argv) + m_opaque_sp->GetArguments().AppendArguments(argv); + } else { + if (argv) + m_opaque_sp->GetArguments().SetArguments(argv); + else + m_opaque_sp->GetArguments().Clear(); + } +} + +uint32_t SBLaunchInfo::GetNumEnvironmentEntries() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetEnvironment().size(); +} + +const char *SBLaunchInfo::GetEnvironmentEntryAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + if (idx > GetNumEnvironmentEntries()) + return nullptr; + return ConstString(m_opaque_sp->GetEnvp()[idx]).GetCString(); +} + +void SBLaunchInfo::SetEnvironmentEntries(const char **envp, bool append) { + LLDB_INSTRUMENT_VA(this, envp, append); + SetEnvironment(SBEnvironment(Environment(envp)), append); +} + +void SBLaunchInfo::SetEnvironment(const SBEnvironment &env, bool append) { + LLDB_INSTRUMENT_VA(this, env, append); + Environment &refEnv = env.ref(); + if (append) { + for (auto &KV : refEnv) + m_opaque_sp->GetEnvironment().insert_or_assign(KV.first(), KV.second); + } else + m_opaque_sp->GetEnvironment() = refEnv; + m_opaque_sp->RegenerateEnvp(); +} + +SBEnvironment SBLaunchInfo::GetEnvironment() { + LLDB_INSTRUMENT_VA(this); + return SBEnvironment(Environment(m_opaque_sp->GetEnvironment())); +} + +void SBLaunchInfo::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_sp->Clear(); +} + +const char *SBLaunchInfo::GetWorkingDirectory() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetWorkingDirectory().GetPathAsConstString().AsCString(); +} + +void SBLaunchInfo::SetWorkingDirectory(const char *working_dir) { + LLDB_INSTRUMENT_VA(this, working_dir); + + m_opaque_sp->SetWorkingDirectory(FileSpec(working_dir)); +} + +uint32_t SBLaunchInfo::GetLaunchFlags() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetFlags().Get(); +} + +void SBLaunchInfo::SetLaunchFlags(uint32_t flags) { + LLDB_INSTRUMENT_VA(this, flags); + + m_opaque_sp->GetFlags().Reset(flags); +} + +const char *SBLaunchInfo::GetProcessPluginName() { + LLDB_INSTRUMENT_VA(this); + + return ConstString(m_opaque_sp->GetProcessPluginName()).GetCString(); +} + +void SBLaunchInfo::SetProcessPluginName(const char *plugin_name) { + LLDB_INSTRUMENT_VA(this, plugin_name); + + return m_opaque_sp->SetProcessPluginName(plugin_name); +} + +const char *SBLaunchInfo::GetShell() { + LLDB_INSTRUMENT_VA(this); + + // Constify this string so that it is saved in the string pool. Otherwise it + // would be freed when this function goes out of scope. + ConstString shell(m_opaque_sp->GetShell().GetPath().c_str()); + return shell.AsCString(); +} + +void SBLaunchInfo::SetShell(const char *path) { + LLDB_INSTRUMENT_VA(this, path); + + m_opaque_sp->SetShell(FileSpec(path)); +} + +bool SBLaunchInfo::GetShellExpandArguments() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetShellExpandArguments(); +} + +void SBLaunchInfo::SetShellExpandArguments(bool expand) { + LLDB_INSTRUMENT_VA(this, expand); + + m_opaque_sp->SetShellExpandArguments(expand); +} + +uint32_t SBLaunchInfo::GetResumeCount() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetResumeCount(); +} + +void SBLaunchInfo::SetResumeCount(uint32_t c) { + LLDB_INSTRUMENT_VA(this, c); + + m_opaque_sp->SetResumeCount(c); +} + +bool SBLaunchInfo::AddCloseFileAction(int fd) { + LLDB_INSTRUMENT_VA(this, fd); + + return m_opaque_sp->AppendCloseFileAction(fd); +} + +bool SBLaunchInfo::AddDuplicateFileAction(int fd, int dup_fd) { + LLDB_INSTRUMENT_VA(this, fd, dup_fd); + + return m_opaque_sp->AppendDuplicateFileAction(fd, dup_fd); +} + +bool SBLaunchInfo::AddOpenFileAction(int fd, const char *path, bool read, + bool write) { + LLDB_INSTRUMENT_VA(this, fd, path, read, write); + + return m_opaque_sp->AppendOpenFileAction(fd, FileSpec(path), read, write); +} + +bool SBLaunchInfo::AddSuppressFileAction(int fd, bool read, bool write) { + LLDB_INSTRUMENT_VA(this, fd, read, write); + + return m_opaque_sp->AppendSuppressFileAction(fd, read, write); +} + +void SBLaunchInfo::SetLaunchEventData(const char *data) { + LLDB_INSTRUMENT_VA(this, data); + + m_opaque_sp->SetLaunchEventData(data); +} + +const char *SBLaunchInfo::GetLaunchEventData() const { + LLDB_INSTRUMENT_VA(this); + + return ConstString(m_opaque_sp->GetLaunchEventData()).GetCString(); +} + +void SBLaunchInfo::SetDetachOnError(bool enable) { + LLDB_INSTRUMENT_VA(this, enable); + + m_opaque_sp->SetDetachOnError(enable); +} + +bool SBLaunchInfo::GetDetachOnError() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetDetachOnError(); +} + +const char *SBLaunchInfo::GetScriptedProcessClassName() const { + LLDB_INSTRUMENT_VA(this); + + ScriptedMetadataSP metadata_sp = m_opaque_sp->GetScriptedMetadata(); + + if (!metadata_sp || !*metadata_sp) + return nullptr; + + // Constify this string so that it is saved in the string pool. Otherwise it + // would be freed when this function goes out of scope. + ConstString class_name(metadata_sp->GetClassName().data()); + return class_name.AsCString(); +} + +void SBLaunchInfo::SetScriptedProcessClassName(const char *class_name) { + LLDB_INSTRUMENT_VA(this, class_name); + ScriptedMetadataSP metadata_sp = m_opaque_sp->GetScriptedMetadata(); + StructuredData::DictionarySP dict_sp = + metadata_sp ? metadata_sp->GetArgsSP() : nullptr; + metadata_sp = std::make_shared<ScriptedMetadata>(class_name, dict_sp); + m_opaque_sp->SetScriptedMetadata(metadata_sp); +} + +lldb::SBStructuredData SBLaunchInfo::GetScriptedProcessDictionary() const { + LLDB_INSTRUMENT_VA(this); + + ScriptedMetadataSP metadata_sp = m_opaque_sp->GetScriptedMetadata(); + + SBStructuredData data; + if (!metadata_sp) + return data; + + lldb_private::StructuredData::DictionarySP dict_sp = metadata_sp->GetArgsSP(); + data.m_impl_up->SetObjectSP(dict_sp); + + return data; +} + +void SBLaunchInfo::SetScriptedProcessDictionary(lldb::SBStructuredData dict) { + LLDB_INSTRUMENT_VA(this, dict); + if (!dict.IsValid() || !dict.m_impl_up) + return; + + StructuredData::ObjectSP obj_sp = dict.m_impl_up->GetObjectSP(); + + if (!obj_sp) + return; + + StructuredData::DictionarySP dict_sp = + std::make_shared<StructuredData::Dictionary>(obj_sp); + if (!dict_sp || dict_sp->GetType() == lldb::eStructuredDataTypeInvalid) + return; + + ScriptedMetadataSP metadata_sp = m_opaque_sp->GetScriptedMetadata(); + llvm::StringRef class_name = metadata_sp ? metadata_sp->GetClassName() : ""; + metadata_sp = std::make_shared<ScriptedMetadata>(class_name, dict_sp); + m_opaque_sp->SetScriptedMetadata(metadata_sp); +} + +SBListener SBLaunchInfo::GetShadowListener() { + LLDB_INSTRUMENT_VA(this); + + lldb::ListenerSP shadow_sp = m_opaque_sp->GetShadowListener(); + if (!shadow_sp) + return SBListener(); + return SBListener(shadow_sp); +} + +void SBLaunchInfo::SetShadowListener(SBListener &listener) { + LLDB_INSTRUMENT_VA(this, listener); + + m_opaque_sp->SetShadowListener(listener.GetSP()); +} diff --git a/contrib/llvm-project/lldb/source/API/SBLineEntry.cpp b/contrib/llvm-project/lldb/source/API/SBLineEntry.cpp new file mode 100644 index 000000000000..216ea6d18eab --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBLineEntry.cpp @@ -0,0 +1,196 @@ +//===-- SBLineEntry.cpp ---------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBLineEntry.h" +#include "Utils.h" +#include "lldb/API/SBStream.h" +#include "lldb/Host/PosixApi.h" +#include "lldb/Symbol/LineEntry.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/StreamString.h" + +#include <climits> + +using namespace lldb; +using namespace lldb_private; + +SBLineEntry::SBLineEntry() { LLDB_INSTRUMENT_VA(this); } + +SBLineEntry::SBLineEntry(const SBLineEntry &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBLineEntry::SBLineEntry(const lldb_private::LineEntry *lldb_object_ptr) { + if (lldb_object_ptr) + m_opaque_up = std::make_unique<LineEntry>(*lldb_object_ptr); +} + +const SBLineEntry &SBLineEntry::operator=(const SBLineEntry &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +void SBLineEntry::SetLineEntry(const lldb_private::LineEntry &lldb_object_ref) { + m_opaque_up = std::make_unique<LineEntry>(lldb_object_ref); +} + +SBLineEntry::~SBLineEntry() = default; + +SBAddress SBLineEntry::GetStartAddress() const { + LLDB_INSTRUMENT_VA(this); + + SBAddress sb_address; + if (m_opaque_up) + sb_address.SetAddress(m_opaque_up->range.GetBaseAddress()); + + return sb_address; +} + +SBAddress SBLineEntry::GetEndAddress() const { + LLDB_INSTRUMENT_VA(this); + + SBAddress sb_address; + if (m_opaque_up) { + sb_address.SetAddress(m_opaque_up->range.GetBaseAddress()); + sb_address.OffsetAddress(m_opaque_up->range.GetByteSize()); + } + return sb_address; +} + +SBAddress SBLineEntry::GetSameLineContiguousAddressRangeEnd( + bool include_inlined_functions) const { + LLDB_INSTRUMENT_VA(this); + + SBAddress sb_address; + if (m_opaque_up) { + AddressRange line_range = m_opaque_up->GetSameLineContiguousAddressRange( + include_inlined_functions); + + sb_address.SetAddress(line_range.GetBaseAddress()); + sb_address.OffsetAddress(line_range.GetByteSize()); + } + return sb_address; +} + +bool SBLineEntry::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBLineEntry::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up.get() && m_opaque_up->IsValid(); +} + +SBFileSpec SBLineEntry::GetFileSpec() const { + LLDB_INSTRUMENT_VA(this); + + SBFileSpec sb_file_spec; + if (m_opaque_up.get() && m_opaque_up->GetFile()) + sb_file_spec.SetFileSpec(m_opaque_up->GetFile()); + + return sb_file_spec; +} + +uint32_t SBLineEntry::GetLine() const { + LLDB_INSTRUMENT_VA(this); + + uint32_t line = 0; + if (m_opaque_up) + line = m_opaque_up->line; + + return line; +} + +uint32_t SBLineEntry::GetColumn() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + return m_opaque_up->column; + return 0; +} + +void SBLineEntry::SetFileSpec(lldb::SBFileSpec filespec) { + LLDB_INSTRUMENT_VA(this, filespec); + + if (filespec.IsValid()) + ref().file_sp = std::make_shared<SupportFile>(filespec.ref()); + else + ref().file_sp = std::make_shared<SupportFile>(); +} +void SBLineEntry::SetLine(uint32_t line) { + LLDB_INSTRUMENT_VA(this, line); + + ref().line = line; +} + +void SBLineEntry::SetColumn(uint32_t column) { + LLDB_INSTRUMENT_VA(this, column); + + ref().line = column; +} + +bool SBLineEntry::operator==(const SBLineEntry &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + lldb_private::LineEntry *lhs_ptr = m_opaque_up.get(); + lldb_private::LineEntry *rhs_ptr = rhs.m_opaque_up.get(); + + if (lhs_ptr && rhs_ptr) + return lldb_private::LineEntry::Compare(*lhs_ptr, *rhs_ptr) == 0; + + return lhs_ptr == rhs_ptr; +} + +bool SBLineEntry::operator!=(const SBLineEntry &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + lldb_private::LineEntry *lhs_ptr = m_opaque_up.get(); + lldb_private::LineEntry *rhs_ptr = rhs.m_opaque_up.get(); + + if (lhs_ptr && rhs_ptr) + return lldb_private::LineEntry::Compare(*lhs_ptr, *rhs_ptr) != 0; + + return lhs_ptr != rhs_ptr; +} + +const lldb_private::LineEntry *SBLineEntry::operator->() const { + return m_opaque_up.get(); +} + +lldb_private::LineEntry &SBLineEntry::ref() { + if (m_opaque_up == nullptr) + m_opaque_up = std::make_unique<lldb_private::LineEntry>(); + return *m_opaque_up; +} + +const lldb_private::LineEntry &SBLineEntry::ref() const { return *m_opaque_up; } + +bool SBLineEntry::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + if (m_opaque_up) { + char file_path[PATH_MAX * 2]; + m_opaque_up->GetFile().GetPath(file_path, sizeof(file_path)); + strm.Printf("%s:%u", file_path, GetLine()); + if (GetColumn() > 0) + strm.Printf(":%u", GetColumn()); + } else + strm.PutCString("No value"); + + return true; +} + +lldb_private::LineEntry *SBLineEntry::get() { return m_opaque_up.get(); } diff --git a/contrib/llvm-project/lldb/source/API/SBListener.cpp b/contrib/llvm-project/lldb/source/API/SBListener.cpp new file mode 100644 index 000000000000..a4c847bec857 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBListener.cpp @@ -0,0 +1,295 @@ +//===-- SBListener.cpp ----------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBListener.h" +#include "lldb/API/SBBroadcaster.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBStream.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Utility/Broadcaster.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Listener.h" +#include "lldb/Utility/StreamString.h" + +using namespace lldb; +using namespace lldb_private; + +SBListener::SBListener() { LLDB_INSTRUMENT_VA(this); } + +SBListener::SBListener(const char *name) + : m_opaque_sp(Listener::MakeListener(name)) { + LLDB_INSTRUMENT_VA(this, name); +} + +SBListener::SBListener(const SBListener &rhs) : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const lldb::SBListener &SBListener::operator=(const lldb::SBListener &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + m_unused_ptr = nullptr; + } + return *this; +} + +SBListener::SBListener(const lldb::ListenerSP &listener_sp) + : m_opaque_sp(listener_sp) {} + +SBListener::~SBListener() = default; + +bool SBListener::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBListener::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp != nullptr; +} + +void SBListener::AddEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(this, event); + + EventSP &event_sp = event.GetSP(); + if (event_sp) + m_opaque_sp->AddEvent(event_sp); +} + +void SBListener::Clear() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + m_opaque_sp->Clear(); +} + +uint32_t SBListener::StartListeningForEventClass(SBDebugger &debugger, + const char *broadcaster_class, + uint32_t event_mask) { + LLDB_INSTRUMENT_VA(this, debugger, broadcaster_class, event_mask); + + if (m_opaque_sp) { + Debugger *lldb_debugger = debugger.get(); + if (!lldb_debugger) + return 0; + BroadcastEventSpec event_spec(ConstString(broadcaster_class), event_mask); + return m_opaque_sp->StartListeningForEventSpec( + lldb_debugger->GetBroadcasterManager(), event_spec); + } else + return 0; +} + +bool SBListener::StopListeningForEventClass(SBDebugger &debugger, + const char *broadcaster_class, + uint32_t event_mask) { + LLDB_INSTRUMENT_VA(this, debugger, broadcaster_class, event_mask); + + if (m_opaque_sp) { + Debugger *lldb_debugger = debugger.get(); + if (!lldb_debugger) + return false; + BroadcastEventSpec event_spec(ConstString(broadcaster_class), event_mask); + return m_opaque_sp->StopListeningForEventSpec( + lldb_debugger->GetBroadcasterManager(), event_spec); + } else + return false; +} + +uint32_t SBListener::StartListeningForEvents(const SBBroadcaster &broadcaster, + uint32_t event_mask) { + LLDB_INSTRUMENT_VA(this, broadcaster, event_mask); + + uint32_t acquired_event_mask = 0; + if (m_opaque_sp && broadcaster.IsValid()) { + acquired_event_mask = + m_opaque_sp->StartListeningForEvents(broadcaster.get(), event_mask); + } + + return acquired_event_mask; +} + +bool SBListener::StopListeningForEvents(const SBBroadcaster &broadcaster, + uint32_t event_mask) { + LLDB_INSTRUMENT_VA(this, broadcaster, event_mask); + + if (m_opaque_sp && broadcaster.IsValid()) { + return m_opaque_sp->StopListeningForEvents(broadcaster.get(), event_mask); + } + return false; +} + +bool SBListener::WaitForEvent(uint32_t timeout_secs, SBEvent &event) { + LLDB_INSTRUMENT_VA(this, timeout_secs, event); + + bool success = false; + + if (m_opaque_sp) { + Timeout<std::micro> timeout(std::nullopt); + if (timeout_secs != UINT32_MAX) { + assert(timeout_secs != 0); // Take this out after all calls with timeout + // set to zero have been removed.... + timeout = std::chrono::seconds(timeout_secs); + } + EventSP event_sp; + if (m_opaque_sp->GetEvent(event_sp, timeout)) { + event.reset(event_sp); + success = true; + } + } + + if (!success) + event.reset(nullptr); + return success; +} + +bool SBListener::WaitForEventForBroadcaster(uint32_t num_seconds, + const SBBroadcaster &broadcaster, + SBEvent &event) { + LLDB_INSTRUMENT_VA(this, num_seconds, broadcaster, event); + + if (m_opaque_sp && broadcaster.IsValid()) { + Timeout<std::micro> timeout(std::nullopt); + if (num_seconds != UINT32_MAX) + timeout = std::chrono::seconds(num_seconds); + EventSP event_sp; + if (m_opaque_sp->GetEventForBroadcaster(broadcaster.get(), event_sp, + timeout)) { + event.reset(event_sp); + return true; + } + } + event.reset(nullptr); + return false; +} + +bool SBListener::WaitForEventForBroadcasterWithType( + uint32_t num_seconds, const SBBroadcaster &broadcaster, + uint32_t event_type_mask, SBEvent &event) { + LLDB_INSTRUMENT_VA(this, num_seconds, broadcaster, event_type_mask, event); + + if (m_opaque_sp && broadcaster.IsValid()) { + Timeout<std::micro> timeout(std::nullopt); + if (num_seconds != UINT32_MAX) + timeout = std::chrono::seconds(num_seconds); + EventSP event_sp; + if (m_opaque_sp->GetEventForBroadcasterWithType( + broadcaster.get(), event_type_mask, event_sp, timeout)) { + event.reset(event_sp); + return true; + } + } + event.reset(nullptr); + return false; +} + +bool SBListener::PeekAtNextEvent(SBEvent &event) { + LLDB_INSTRUMENT_VA(this, event); + + if (m_opaque_sp) { + event.reset(m_opaque_sp->PeekAtNextEvent()); + return event.IsValid(); + } + event.reset(nullptr); + return false; +} + +bool SBListener::PeekAtNextEventForBroadcaster(const SBBroadcaster &broadcaster, + SBEvent &event) { + LLDB_INSTRUMENT_VA(this, broadcaster, event); + + if (m_opaque_sp && broadcaster.IsValid()) { + event.reset(m_opaque_sp->PeekAtNextEventForBroadcaster(broadcaster.get())); + return event.IsValid(); + } + event.reset(nullptr); + return false; +} + +bool SBListener::PeekAtNextEventForBroadcasterWithType( + const SBBroadcaster &broadcaster, uint32_t event_type_mask, + SBEvent &event) { + LLDB_INSTRUMENT_VA(this, broadcaster, event_type_mask, event); + + if (m_opaque_sp && broadcaster.IsValid()) { + event.reset(m_opaque_sp->PeekAtNextEventForBroadcasterWithType( + broadcaster.get(), event_type_mask)); + return event.IsValid(); + } + event.reset(nullptr); + return false; +} + +bool SBListener::GetNextEvent(SBEvent &event) { + LLDB_INSTRUMENT_VA(this, event); + + if (m_opaque_sp) { + EventSP event_sp; + if (m_opaque_sp->GetEvent(event_sp, std::chrono::seconds(0))) { + event.reset(event_sp); + return true; + } + } + event.reset(nullptr); + return false; +} + +bool SBListener::GetNextEventForBroadcaster(const SBBroadcaster &broadcaster, + SBEvent &event) { + LLDB_INSTRUMENT_VA(this, broadcaster, event); + + if (m_opaque_sp && broadcaster.IsValid()) { + EventSP event_sp; + if (m_opaque_sp->GetEventForBroadcaster(broadcaster.get(), event_sp, + std::chrono::seconds(0))) { + event.reset(event_sp); + return true; + } + } + event.reset(nullptr); + return false; +} + +bool SBListener::GetNextEventForBroadcasterWithType( + const SBBroadcaster &broadcaster, uint32_t event_type_mask, + SBEvent &event) { + LLDB_INSTRUMENT_VA(this, broadcaster, event_type_mask, event); + + if (m_opaque_sp && broadcaster.IsValid()) { + EventSP event_sp; + if (m_opaque_sp->GetEventForBroadcasterWithType(broadcaster.get(), + event_type_mask, event_sp, + std::chrono::seconds(0))) { + event.reset(event_sp); + return true; + } + } + event.reset(nullptr); + return false; +} + +bool SBListener::HandleBroadcastEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(this, event); + + if (m_opaque_sp) + return m_opaque_sp->HandleBroadcastEvent(event.GetSP()); + return false; +} + +lldb::ListenerSP SBListener::GetSP() { return m_opaque_sp; } + +Listener *SBListener::operator->() const { return m_opaque_sp.get(); } + +Listener *SBListener::get() const { return m_opaque_sp.get(); } + +void SBListener::reset(ListenerSP listener_sp) { + m_opaque_sp = listener_sp; + m_unused_ptr = nullptr; +} diff --git a/contrib/llvm-project/lldb/source/API/SBMemoryRegionInfo.cpp b/contrib/llvm-project/lldb/source/API/SBMemoryRegionInfo.cpp new file mode 100644 index 000000000000..cd25be5d5276 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBMemoryRegionInfo.cpp @@ -0,0 +1,177 @@ +//===-- SBMemoryRegionInfo.cpp --------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBMemoryRegionInfo.h" +#include "Utils.h" +#include "lldb/API/SBDefines.h" +#include "lldb/API/SBError.h" +#include "lldb/API/SBStream.h" +#include "lldb/Target/MemoryRegionInfo.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/StreamString.h" +#include <optional> + +using namespace lldb; +using namespace lldb_private; + +SBMemoryRegionInfo::SBMemoryRegionInfo() : m_opaque_up(new MemoryRegionInfo()) { + LLDB_INSTRUMENT_VA(this); +} + +SBMemoryRegionInfo::SBMemoryRegionInfo(const char *name, lldb::addr_t begin, + lldb::addr_t end, uint32_t permissions, + bool mapped, bool stack_memory) + : SBMemoryRegionInfo() { + LLDB_INSTRUMENT_VA(this, name, begin, end, permissions, mapped, stack_memory); + m_opaque_up->SetName(name); + m_opaque_up->GetRange().SetRangeBase(begin); + m_opaque_up->GetRange().SetRangeEnd(end); + m_opaque_up->SetLLDBPermissions(permissions); + m_opaque_up->SetMapped(mapped ? MemoryRegionInfo::eYes + : MemoryRegionInfo::eNo); + m_opaque_up->SetIsStackMemory(stack_memory ? MemoryRegionInfo::eYes + : MemoryRegionInfo::eNo); +} + +SBMemoryRegionInfo::SBMemoryRegionInfo(const MemoryRegionInfo *lldb_object_ptr) + : m_opaque_up(new MemoryRegionInfo()) { + if (lldb_object_ptr) + ref() = *lldb_object_ptr; +} + +SBMemoryRegionInfo::SBMemoryRegionInfo(const SBMemoryRegionInfo &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + m_opaque_up = clone(rhs.m_opaque_up); +} + +const SBMemoryRegionInfo &SBMemoryRegionInfo:: +operator=(const SBMemoryRegionInfo &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +SBMemoryRegionInfo::~SBMemoryRegionInfo() = default; + +void SBMemoryRegionInfo::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_up->Clear(); +} + +bool SBMemoryRegionInfo::operator==(const SBMemoryRegionInfo &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return ref() == rhs.ref(); +} + +bool SBMemoryRegionInfo::operator!=(const SBMemoryRegionInfo &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return ref() != rhs.ref(); +} + +MemoryRegionInfo &SBMemoryRegionInfo::ref() { return *m_opaque_up; } + +const MemoryRegionInfo &SBMemoryRegionInfo::ref() const { return *m_opaque_up; } + +lldb::addr_t SBMemoryRegionInfo::GetRegionBase() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetRange().GetRangeBase(); +} + +lldb::addr_t SBMemoryRegionInfo::GetRegionEnd() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetRange().GetRangeEnd(); +} + +bool SBMemoryRegionInfo::IsReadable() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetReadable() == MemoryRegionInfo::eYes; +} + +bool SBMemoryRegionInfo::IsWritable() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetWritable() == MemoryRegionInfo::eYes; +} + +bool SBMemoryRegionInfo::IsExecutable() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetExecutable() == MemoryRegionInfo::eYes; +} + +bool SBMemoryRegionInfo::IsMapped() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetMapped() == MemoryRegionInfo::eYes; +} + +const char *SBMemoryRegionInfo::GetName() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetName().AsCString(); +} + +bool SBMemoryRegionInfo::HasDirtyMemoryPageList() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetDirtyPageList().has_value(); +} + +uint32_t SBMemoryRegionInfo::GetNumDirtyPages() { + LLDB_INSTRUMENT_VA(this); + + uint32_t num_dirty_pages = 0; + const std::optional<std::vector<addr_t>> &dirty_page_list = + m_opaque_up->GetDirtyPageList(); + if (dirty_page_list) + num_dirty_pages = dirty_page_list->size(); + + return num_dirty_pages; +} + +addr_t SBMemoryRegionInfo::GetDirtyPageAddressAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + addr_t dirty_page_addr = LLDB_INVALID_ADDRESS; + const std::optional<std::vector<addr_t>> &dirty_page_list = + m_opaque_up->GetDirtyPageList(); + if (dirty_page_list && idx < dirty_page_list->size()) + dirty_page_addr = (*dirty_page_list)[idx]; + + return dirty_page_addr; +} + +int SBMemoryRegionInfo::GetPageSize() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetPageSize(); +} + +bool SBMemoryRegionInfo::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + const addr_t load_addr = m_opaque_up->GetRange().base; + + strm.Printf("[0x%16.16" PRIx64 "-0x%16.16" PRIx64 " ", load_addr, + load_addr + m_opaque_up->GetRange().size); + strm.Printf(m_opaque_up->GetReadable() ? "R" : "-"); + strm.Printf(m_opaque_up->GetWritable() ? "W" : "-"); + strm.Printf(m_opaque_up->GetExecutable() ? "X" : "-"); + strm.Printf("]"); + + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBMemoryRegionInfoList.cpp b/contrib/llvm-project/lldb/source/API/SBMemoryRegionInfoList.cpp new file mode 100644 index 000000000000..f8381d1098a0 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBMemoryRegionInfoList.cpp @@ -0,0 +1,151 @@ +//===-- SBMemoryRegionInfoList.cpp ----------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBMemoryRegionInfoList.h" +#include "lldb/API/SBMemoryRegionInfo.h" +#include "lldb/API/SBStream.h" +#include "lldb/Target/MemoryRegionInfo.h" +#include "lldb/Utility/Instrumentation.h" + +#include <vector> + +using namespace lldb; +using namespace lldb_private; + +class MemoryRegionInfoListImpl { +public: + MemoryRegionInfoListImpl() : m_regions() {} + + MemoryRegionInfoListImpl(const MemoryRegionInfoListImpl &rhs) = default; + + MemoryRegionInfoListImpl &operator=(const MemoryRegionInfoListImpl &rhs) { + if (this == &rhs) + return *this; + m_regions = rhs.m_regions; + return *this; + } + + size_t GetSize() const { return m_regions.size(); } + + void Reserve(size_t capacity) { return m_regions.reserve(capacity); } + + void Append(const MemoryRegionInfo &sb_region) { + m_regions.push_back(sb_region); + } + + void Append(const MemoryRegionInfoListImpl &list) { + Reserve(GetSize() + list.GetSize()); + + for (const auto &val : list.m_regions) + Append(val); + } + + void Clear() { m_regions.clear(); } + + bool GetMemoryRegionContainingAddress(lldb::addr_t addr, + MemoryRegionInfo ®ion_info) { + for (auto ®ion : m_regions) { + if (region.GetRange().Contains(addr)) { + region_info = region; + return true; + } + } + return false; + } + + bool GetMemoryRegionInfoAtIndex(size_t index, + MemoryRegionInfo ®ion_info) { + if (index >= GetSize()) + return false; + region_info = m_regions[index]; + return true; + } + + MemoryRegionInfos &Ref() { return m_regions; } + + const MemoryRegionInfos &Ref() const { return m_regions; } + +private: + MemoryRegionInfos m_regions; +}; + +MemoryRegionInfos &SBMemoryRegionInfoList::ref() { return m_opaque_up->Ref(); } + +const MemoryRegionInfos &SBMemoryRegionInfoList::ref() const { + return m_opaque_up->Ref(); +} + +SBMemoryRegionInfoList::SBMemoryRegionInfoList() + : m_opaque_up(new MemoryRegionInfoListImpl()) { + LLDB_INSTRUMENT_VA(this); +} + +SBMemoryRegionInfoList::SBMemoryRegionInfoList( + const SBMemoryRegionInfoList &rhs) + : m_opaque_up(new MemoryRegionInfoListImpl(*rhs.m_opaque_up)) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBMemoryRegionInfoList::~SBMemoryRegionInfoList() = default; + +const SBMemoryRegionInfoList &SBMemoryRegionInfoList:: +operator=(const SBMemoryRegionInfoList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + *m_opaque_up = *rhs.m_opaque_up; + } + return *this; +} + +uint32_t SBMemoryRegionInfoList::GetSize() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetSize(); +} + +bool SBMemoryRegionInfoList::GetMemoryRegionContainingAddress( + lldb::addr_t addr, SBMemoryRegionInfo ®ion_info) { + LLDB_INSTRUMENT_VA(this, addr, region_info); + + return m_opaque_up->GetMemoryRegionContainingAddress(addr, region_info.ref()); +} + +bool SBMemoryRegionInfoList::GetMemoryRegionAtIndex( + uint32_t idx, SBMemoryRegionInfo ®ion_info) { + LLDB_INSTRUMENT_VA(this, idx, region_info); + + return m_opaque_up->GetMemoryRegionInfoAtIndex(idx, region_info.ref()); +} + +void SBMemoryRegionInfoList::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_up->Clear(); +} + +void SBMemoryRegionInfoList::Append(SBMemoryRegionInfo &sb_region) { + LLDB_INSTRUMENT_VA(this, sb_region); + + m_opaque_up->Append(sb_region.ref()); +} + +void SBMemoryRegionInfoList::Append(SBMemoryRegionInfoList &sb_region_list) { + LLDB_INSTRUMENT_VA(this, sb_region_list); + + m_opaque_up->Append(*sb_region_list); +} + +const MemoryRegionInfoListImpl *SBMemoryRegionInfoList::operator->() const { + return m_opaque_up.get(); +} + +const MemoryRegionInfoListImpl &SBMemoryRegionInfoList::operator*() const { + assert(m_opaque_up.get()); + return *m_opaque_up; +} diff --git a/contrib/llvm-project/lldb/source/API/SBModule.cpp b/contrib/llvm-project/lldb/source/API/SBModule.cpp new file mode 100644 index 000000000000..262e26c6bf43 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBModule.cpp @@ -0,0 +1,673 @@ +//===-- SBModule.cpp ------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBModule.h" +#include "lldb/API/SBAddress.h" +#include "lldb/API/SBFileSpec.h" +#include "lldb/API/SBModuleSpec.h" +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBSymbolContextList.h" +#include "lldb/Core/Module.h" +#include "lldb/Core/Section.h" +#include "lldb/Core/ValueObjectList.h" +#include "lldb/Core/ValueObjectVariable.h" +#include "lldb/Symbol/ObjectFile.h" +#include "lldb/Symbol/SymbolFile.h" +#include "lldb/Symbol/Symtab.h" +#include "lldb/Symbol/TypeSystem.h" +#include "lldb/Symbol/VariableList.h" +#include "lldb/Target/Target.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/StreamString.h" + +using namespace lldb; +using namespace lldb_private; + +SBModule::SBModule() { LLDB_INSTRUMENT_VA(this); } + +SBModule::SBModule(const lldb::ModuleSP &module_sp) : m_opaque_sp(module_sp) {} + +SBModule::SBModule(const SBModuleSpec &module_spec) { + LLDB_INSTRUMENT_VA(this, module_spec); + + ModuleSP module_sp; + Status error = ModuleList::GetSharedModule( + *module_spec.m_opaque_up, module_sp, nullptr, nullptr, nullptr); + if (module_sp) + SetSP(module_sp); +} + +SBModule::SBModule(const SBModule &rhs) : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBModule::SBModule(lldb::SBProcess &process, lldb::addr_t header_addr) { + LLDB_INSTRUMENT_VA(this, process, header_addr); + + ProcessSP process_sp(process.GetSP()); + if (process_sp) { + m_opaque_sp = process_sp->ReadModuleFromMemory(FileSpec(), header_addr); + if (m_opaque_sp) { + Target &target = process_sp->GetTarget(); + bool changed = false; + m_opaque_sp->SetLoadAddress(target, 0, true, changed); + target.GetImages().Append(m_opaque_sp); + } + } +} + +const SBModule &SBModule::operator=(const SBModule &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; +} + +SBModule::~SBModule() = default; + +bool SBModule::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBModule::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} + +void SBModule::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_sp.reset(); +} + +bool SBModule::IsFileBacked() const { + LLDB_INSTRUMENT_VA(this); + + ModuleSP module_sp(GetSP()); + if (!module_sp) + return false; + + ObjectFile *obj_file = module_sp->GetObjectFile(); + if (!obj_file) + return false; + + return !obj_file->IsInMemory(); +} + +SBFileSpec SBModule::GetFileSpec() const { + LLDB_INSTRUMENT_VA(this); + + SBFileSpec file_spec; + ModuleSP module_sp(GetSP()); + if (module_sp) + file_spec.SetFileSpec(module_sp->GetFileSpec()); + + return file_spec; +} + +lldb::SBFileSpec SBModule::GetPlatformFileSpec() const { + LLDB_INSTRUMENT_VA(this); + + SBFileSpec file_spec; + ModuleSP module_sp(GetSP()); + if (module_sp) + file_spec.SetFileSpec(module_sp->GetPlatformFileSpec()); + + return file_spec; +} + +bool SBModule::SetPlatformFileSpec(const lldb::SBFileSpec &platform_file) { + LLDB_INSTRUMENT_VA(this, platform_file); + + bool result = false; + + ModuleSP module_sp(GetSP()); + if (module_sp) { + module_sp->SetPlatformFileSpec(*platform_file); + result = true; + } + + return result; +} + +lldb::SBFileSpec SBModule::GetRemoteInstallFileSpec() { + LLDB_INSTRUMENT_VA(this); + + SBFileSpec sb_file_spec; + ModuleSP module_sp(GetSP()); + if (module_sp) + sb_file_spec.SetFileSpec(module_sp->GetRemoteInstallFileSpec()); + return sb_file_spec; +} + +bool SBModule::SetRemoteInstallFileSpec(lldb::SBFileSpec &file) { + LLDB_INSTRUMENT_VA(this, file); + + ModuleSP module_sp(GetSP()); + if (module_sp) { + module_sp->SetRemoteInstallFileSpec(file.ref()); + return true; + } + return false; +} + +const uint8_t *SBModule::GetUUIDBytes() const { + LLDB_INSTRUMENT_VA(this); + + const uint8_t *uuid_bytes = nullptr; + ModuleSP module_sp(GetSP()); + if (module_sp) + uuid_bytes = module_sp->GetUUID().GetBytes().data(); + + return uuid_bytes; +} + +const char *SBModule::GetUUIDString() const { + LLDB_INSTRUMENT_VA(this); + + ModuleSP module_sp(GetSP()); + if (!module_sp) + return nullptr; + + // We are going to return a "const char *" value through the public API, so + // we need to constify it so it gets added permanently the string pool and + // then we don't need to worry about the lifetime of the string as it will + // never go away once it has been put into the ConstString string pool + const char *uuid_cstr = + ConstString(module_sp->GetUUID().GetAsString()).GetCString(); + // Note: SBModule::GetUUIDString's expected behavior is to return nullptr if + // the string we get is empty, so we must perform this check before returning. + if (uuid_cstr && uuid_cstr[0]) + return uuid_cstr; + return nullptr; +} + +bool SBModule::operator==(const SBModule &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + if (m_opaque_sp) + return m_opaque_sp.get() == rhs.m_opaque_sp.get(); + return false; +} + +bool SBModule::operator!=(const SBModule &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + if (m_opaque_sp) + return m_opaque_sp.get() != rhs.m_opaque_sp.get(); + return false; +} + +ModuleSP SBModule::GetSP() const { return m_opaque_sp; } + +void SBModule::SetSP(const ModuleSP &module_sp) { m_opaque_sp = module_sp; } + +SBAddress SBModule::ResolveFileAddress(lldb::addr_t vm_addr) { + LLDB_INSTRUMENT_VA(this, vm_addr); + + lldb::SBAddress sb_addr; + ModuleSP module_sp(GetSP()); + if (module_sp) { + Address addr; + if (module_sp->ResolveFileAddress(vm_addr, addr)) + sb_addr.ref() = addr; + } + return sb_addr; +} + +SBSymbolContext +SBModule::ResolveSymbolContextForAddress(const SBAddress &addr, + uint32_t resolve_scope) { + LLDB_INSTRUMENT_VA(this, addr, resolve_scope); + + SBSymbolContext sb_sc; + ModuleSP module_sp(GetSP()); + SymbolContextItem scope = static_cast<SymbolContextItem>(resolve_scope); + if (module_sp && addr.IsValid()) + module_sp->ResolveSymbolContextForAddress(addr.ref(), scope, *sb_sc); + return sb_sc; +} + +bool SBModule::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + ModuleSP module_sp(GetSP()); + if (module_sp) { + module_sp->GetDescription(strm.AsRawOstream()); + } else + strm.PutCString("No value"); + + return true; +} + +uint32_t SBModule::GetNumCompileUnits() { + LLDB_INSTRUMENT_VA(this); + + ModuleSP module_sp(GetSP()); + if (module_sp) { + return module_sp->GetNumCompileUnits(); + } + return 0; +} + +SBCompileUnit SBModule::GetCompileUnitAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + SBCompileUnit sb_cu; + ModuleSP module_sp(GetSP()); + if (module_sp) { + CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(index); + sb_cu.reset(cu_sp.get()); + } + return sb_cu; +} + +SBSymbolContextList SBModule::FindCompileUnits(const SBFileSpec &sb_file_spec) { + LLDB_INSTRUMENT_VA(this, sb_file_spec); + + SBSymbolContextList sb_sc_list; + const ModuleSP module_sp(GetSP()); + if (sb_file_spec.IsValid() && module_sp) { + module_sp->FindCompileUnits(*sb_file_spec, *sb_sc_list); + } + return sb_sc_list; +} + +static Symtab *GetUnifiedSymbolTable(const lldb::ModuleSP &module_sp) { + if (module_sp) + return module_sp->GetSymtab(); + return nullptr; +} + +size_t SBModule::GetNumSymbols() { + LLDB_INSTRUMENT_VA(this); + + ModuleSP module_sp(GetSP()); + if (Symtab *symtab = GetUnifiedSymbolTable(module_sp)) + return symtab->GetNumSymbols(); + return 0; +} + +SBSymbol SBModule::GetSymbolAtIndex(size_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBSymbol sb_symbol; + ModuleSP module_sp(GetSP()); + Symtab *symtab = GetUnifiedSymbolTable(module_sp); + if (symtab) + sb_symbol.SetSymbol(symtab->SymbolAtIndex(idx)); + return sb_symbol; +} + +lldb::SBSymbol SBModule::FindSymbol(const char *name, + lldb::SymbolType symbol_type) { + LLDB_INSTRUMENT_VA(this, name, symbol_type); + + SBSymbol sb_symbol; + if (name && name[0]) { + ModuleSP module_sp(GetSP()); + Symtab *symtab = GetUnifiedSymbolTable(module_sp); + if (symtab) + sb_symbol.SetSymbol(symtab->FindFirstSymbolWithNameAndType( + ConstString(name), symbol_type, Symtab::eDebugAny, + Symtab::eVisibilityAny)); + } + return sb_symbol; +} + +lldb::SBSymbolContextList SBModule::FindSymbols(const char *name, + lldb::SymbolType symbol_type) { + LLDB_INSTRUMENT_VA(this, name, symbol_type); + + SBSymbolContextList sb_sc_list; + if (name && name[0]) { + ModuleSP module_sp(GetSP()); + Symtab *symtab = GetUnifiedSymbolTable(module_sp); + if (symtab) { + std::vector<uint32_t> matching_symbol_indexes; + symtab->FindAllSymbolsWithNameAndType(ConstString(name), symbol_type, + matching_symbol_indexes); + const size_t num_matches = matching_symbol_indexes.size(); + if (num_matches) { + SymbolContext sc; + sc.module_sp = module_sp; + SymbolContextList &sc_list = *sb_sc_list; + for (size_t i = 0; i < num_matches; ++i) { + sc.symbol = symtab->SymbolAtIndex(matching_symbol_indexes[i]); + if (sc.symbol) + sc_list.Append(sc); + } + } + } + } + return sb_sc_list; +} + +size_t SBModule::GetNumSections() { + LLDB_INSTRUMENT_VA(this); + + ModuleSP module_sp(GetSP()); + if (module_sp) { + // Give the symbol vendor a chance to add to the unified section list. + module_sp->GetSymbolFile(); + SectionList *section_list = module_sp->GetSectionList(); + if (section_list) + return section_list->GetSize(); + } + return 0; +} + +SBSection SBModule::GetSectionAtIndex(size_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBSection sb_section; + ModuleSP module_sp(GetSP()); + if (module_sp) { + // Give the symbol vendor a chance to add to the unified section list. + module_sp->GetSymbolFile(); + SectionList *section_list = module_sp->GetSectionList(); + + if (section_list) + sb_section.SetSP(section_list->GetSectionAtIndex(idx)); + } + return sb_section; +} + +lldb::SBSymbolContextList SBModule::FindFunctions(const char *name, + uint32_t name_type_mask) { + LLDB_INSTRUMENT_VA(this, name, name_type_mask); + + lldb::SBSymbolContextList sb_sc_list; + ModuleSP module_sp(GetSP()); + if (name && module_sp) { + + ModuleFunctionSearchOptions function_options; + function_options.include_symbols = true; + function_options.include_inlines = true; + FunctionNameType type = static_cast<FunctionNameType>(name_type_mask); + module_sp->FindFunctions(ConstString(name), CompilerDeclContext(), type, + function_options, *sb_sc_list); + } + return sb_sc_list; +} + +SBValueList SBModule::FindGlobalVariables(SBTarget &target, const char *name, + uint32_t max_matches) { + LLDB_INSTRUMENT_VA(this, target, name, max_matches); + + SBValueList sb_value_list; + ModuleSP module_sp(GetSP()); + if (name && module_sp) { + VariableList variable_list; + module_sp->FindGlobalVariables(ConstString(name), CompilerDeclContext(), + max_matches, variable_list); + for (const VariableSP &var_sp : variable_list) { + lldb::ValueObjectSP valobj_sp; + TargetSP target_sp(target.GetSP()); + valobj_sp = ValueObjectVariable::Create(target_sp.get(), var_sp); + if (valobj_sp) + sb_value_list.Append(SBValue(valobj_sp)); + } + } + + return sb_value_list; +} + +lldb::SBValue SBModule::FindFirstGlobalVariable(lldb::SBTarget &target, + const char *name) { + LLDB_INSTRUMENT_VA(this, target, name); + + SBValueList sb_value_list(FindGlobalVariables(target, name, 1)); + if (sb_value_list.IsValid() && sb_value_list.GetSize() > 0) + return sb_value_list.GetValueAtIndex(0); + return SBValue(); +} + +lldb::SBType SBModule::FindFirstType(const char *name_cstr) { + LLDB_INSTRUMENT_VA(this, name_cstr); + + ModuleSP module_sp(GetSP()); + if (name_cstr && module_sp) { + ConstString name(name_cstr); + TypeQuery query(name.GetStringRef(), TypeQueryOptions::e_find_one); + TypeResults results; + module_sp->FindTypes(query, results); + TypeSP type_sp = results.GetFirstType(); + if (type_sp) + return SBType(type_sp); + + auto type_system_or_err = + module_sp->GetTypeSystemForLanguage(eLanguageTypeC); + if (auto err = type_system_or_err.takeError()) { + llvm::consumeError(std::move(err)); + return {}; + } + + if (auto ts = *type_system_or_err) + return SBType(ts->GetBuiltinTypeByName(name)); + } + return {}; +} + +lldb::SBType SBModule::GetBasicType(lldb::BasicType type) { + LLDB_INSTRUMENT_VA(this, type); + + ModuleSP module_sp(GetSP()); + if (module_sp) { + auto type_system_or_err = + module_sp->GetTypeSystemForLanguage(eLanguageTypeC); + if (auto err = type_system_or_err.takeError()) { + llvm::consumeError(std::move(err)); + } else { + if (auto ts = *type_system_or_err) + return SBType(ts->GetBasicTypeFromAST(type)); + } + } + return SBType(); +} + +lldb::SBTypeList SBModule::FindTypes(const char *type) { + LLDB_INSTRUMENT_VA(this, type); + + SBTypeList retval; + + ModuleSP module_sp(GetSP()); + if (type && module_sp) { + TypeList type_list; + TypeQuery query(type); + TypeResults results; + module_sp->FindTypes(query, results); + if (results.GetTypeMap().Empty()) { + ConstString name(type); + auto type_system_or_err = + module_sp->GetTypeSystemForLanguage(eLanguageTypeC); + if (auto err = type_system_or_err.takeError()) { + llvm::consumeError(std::move(err)); + } else { + if (auto ts = *type_system_or_err) + if (CompilerType compiler_type = ts->GetBuiltinTypeByName(name)) + retval.Append(SBType(compiler_type)); + } + } else { + for (const TypeSP &type_sp : results.GetTypeMap().Types()) + retval.Append(SBType(type_sp)); + } + } + return retval; +} + +lldb::SBType SBModule::GetTypeByID(lldb::user_id_t uid) { + LLDB_INSTRUMENT_VA(this, uid); + + ModuleSP module_sp(GetSP()); + if (module_sp) { + if (SymbolFile *symfile = module_sp->GetSymbolFile()) { + Type *type_ptr = symfile->ResolveTypeUID(uid); + if (type_ptr) + return SBType(type_ptr->shared_from_this()); + } + } + return SBType(); +} + +lldb::SBTypeList SBModule::GetTypes(uint32_t type_mask) { + LLDB_INSTRUMENT_VA(this, type_mask); + + SBTypeList sb_type_list; + + ModuleSP module_sp(GetSP()); + if (!module_sp) + return sb_type_list; + SymbolFile *symfile = module_sp->GetSymbolFile(); + if (!symfile) + return sb_type_list; + + TypeClass type_class = static_cast<TypeClass>(type_mask); + TypeList type_list; + symfile->GetTypes(nullptr, type_class, type_list); + sb_type_list.m_opaque_up->Append(type_list); + return sb_type_list; +} + +SBSection SBModule::FindSection(const char *sect_name) { + LLDB_INSTRUMENT_VA(this, sect_name); + + SBSection sb_section; + + ModuleSP module_sp(GetSP()); + if (sect_name && module_sp) { + // Give the symbol vendor a chance to add to the unified section list. + module_sp->GetSymbolFile(); + SectionList *section_list = module_sp->GetSectionList(); + if (section_list) { + ConstString const_sect_name(sect_name); + SectionSP section_sp(section_list->FindSectionByName(const_sect_name)); + if (section_sp) { + sb_section.SetSP(section_sp); + } + } + } + return sb_section; +} + +lldb::ByteOrder SBModule::GetByteOrder() { + LLDB_INSTRUMENT_VA(this); + + ModuleSP module_sp(GetSP()); + if (module_sp) + return module_sp->GetArchitecture().GetByteOrder(); + return eByteOrderInvalid; +} + +const char *SBModule::GetTriple() { + LLDB_INSTRUMENT_VA(this); + + ModuleSP module_sp(GetSP()); + if (!module_sp) + return nullptr; + + std::string triple(module_sp->GetArchitecture().GetTriple().str()); + // Unique the string so we don't run into ownership issues since the const + // strings put the string into the string pool once and the strings never + // comes out + ConstString const_triple(triple.c_str()); + return const_triple.GetCString(); +} + +uint32_t SBModule::GetAddressByteSize() { + LLDB_INSTRUMENT_VA(this); + + ModuleSP module_sp(GetSP()); + if (module_sp) + return module_sp->GetArchitecture().GetAddressByteSize(); + return sizeof(void *); +} + +uint32_t SBModule::GetVersion(uint32_t *versions, uint32_t num_versions) { + LLDB_INSTRUMENT_VA(this, versions, num_versions); + + llvm::VersionTuple version; + if (ModuleSP module_sp = GetSP()) + version = module_sp->GetVersion(); + uint32_t result = 0; + if (!version.empty()) + ++result; + if (version.getMinor()) + ++result; + if (version.getSubminor()) + ++result; + + if (!versions) + return result; + + if (num_versions > 0) + versions[0] = version.empty() ? UINT32_MAX : version.getMajor(); + if (num_versions > 1) + versions[1] = version.getMinor().value_or(UINT32_MAX); + if (num_versions > 2) + versions[2] = version.getSubminor().value_or(UINT32_MAX); + for (uint32_t i = 3; i < num_versions; ++i) + versions[i] = UINT32_MAX; + return result; +} + +lldb::SBFileSpec SBModule::GetSymbolFileSpec() const { + LLDB_INSTRUMENT_VA(this); + + lldb::SBFileSpec sb_file_spec; + ModuleSP module_sp(GetSP()); + if (module_sp) { + if (SymbolFile *symfile = module_sp->GetSymbolFile()) + sb_file_spec.SetFileSpec(symfile->GetObjectFile()->GetFileSpec()); + } + return sb_file_spec; +} + +lldb::SBAddress SBModule::GetObjectFileHeaderAddress() const { + LLDB_INSTRUMENT_VA(this); + + lldb::SBAddress sb_addr; + ModuleSP module_sp(GetSP()); + if (module_sp) { + ObjectFile *objfile_ptr = module_sp->GetObjectFile(); + if (objfile_ptr) + sb_addr.ref() = objfile_ptr->GetBaseAddress(); + } + return sb_addr; +} + +lldb::SBAddress SBModule::GetObjectFileEntryPointAddress() const { + LLDB_INSTRUMENT_VA(this); + + lldb::SBAddress sb_addr; + ModuleSP module_sp(GetSP()); + if (module_sp) { + ObjectFile *objfile_ptr = module_sp->GetObjectFile(); + if (objfile_ptr) + sb_addr.ref() = objfile_ptr->GetEntryPointAddress(); + } + return sb_addr; +} + +uint32_t SBModule::GetNumberAllocatedModules() { + LLDB_INSTRUMENT(); + + return Module::GetNumberAllocatedModules(); +} + +void SBModule::GarbageCollectAllocatedModules() { + LLDB_INSTRUMENT(); + + const bool mandatory = false; + ModuleList::RemoveOrphanSharedModules(mandatory); +} diff --git a/contrib/llvm-project/lldb/source/API/SBModuleSpec.cpp b/contrib/llvm-project/lldb/source/API/SBModuleSpec.cpp new file mode 100644 index 000000000000..fbbcfeac2017 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBModuleSpec.cpp @@ -0,0 +1,258 @@ +//===-- SBModuleSpec.cpp --------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBModuleSpec.h" +#include "Utils.h" +#include "lldb/API/SBStream.h" +#include "lldb/Core/Module.h" +#include "lldb/Core/ModuleSpec.h" +#include "lldb/Host/Host.h" +#include "lldb/Symbol/ObjectFile.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Stream.h" + +using namespace lldb; +using namespace lldb_private; + +SBModuleSpec::SBModuleSpec() : m_opaque_up(new lldb_private::ModuleSpec()) { + LLDB_INSTRUMENT_VA(this); +} + +SBModuleSpec::SBModuleSpec(const SBModuleSpec &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBModuleSpec::SBModuleSpec(const lldb_private::ModuleSpec &module_spec) + : m_opaque_up(new lldb_private::ModuleSpec(module_spec)) { + LLDB_INSTRUMENT_VA(this, module_spec); +} + +const SBModuleSpec &SBModuleSpec::operator=(const SBModuleSpec &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +SBModuleSpec::~SBModuleSpec() = default; + +bool SBModuleSpec::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBModuleSpec::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->operator bool(); +} + +void SBModuleSpec::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_up->Clear(); +} + +SBFileSpec SBModuleSpec::GetFileSpec() { + LLDB_INSTRUMENT_VA(this); + + SBFileSpec sb_spec(m_opaque_up->GetFileSpec()); + return sb_spec; +} + +void SBModuleSpec::SetFileSpec(const lldb::SBFileSpec &sb_spec) { + LLDB_INSTRUMENT_VA(this, sb_spec); + + m_opaque_up->GetFileSpec() = *sb_spec; +} + +lldb::SBFileSpec SBModuleSpec::GetPlatformFileSpec() { + LLDB_INSTRUMENT_VA(this); + + return SBFileSpec(m_opaque_up->GetPlatformFileSpec()); +} + +void SBModuleSpec::SetPlatformFileSpec(const lldb::SBFileSpec &sb_spec) { + LLDB_INSTRUMENT_VA(this, sb_spec); + + m_opaque_up->GetPlatformFileSpec() = *sb_spec; +} + +lldb::SBFileSpec SBModuleSpec::GetSymbolFileSpec() { + LLDB_INSTRUMENT_VA(this); + + return SBFileSpec(m_opaque_up->GetSymbolFileSpec()); +} + +void SBModuleSpec::SetSymbolFileSpec(const lldb::SBFileSpec &sb_spec) { + LLDB_INSTRUMENT_VA(this, sb_spec); + + m_opaque_up->GetSymbolFileSpec() = *sb_spec; +} + +const char *SBModuleSpec::GetObjectName() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetObjectName().GetCString(); +} + +void SBModuleSpec::SetObjectName(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + + m_opaque_up->GetObjectName().SetCString(name); +} + +const char *SBModuleSpec::GetTriple() { + LLDB_INSTRUMENT_VA(this); + + std::string triple(m_opaque_up->GetArchitecture().GetTriple().str()); + // Unique the string so we don't run into ownership issues since the const + // strings put the string into the string pool once and the strings never + // comes out + ConstString const_triple(triple.c_str()); + return const_triple.GetCString(); +} + +void SBModuleSpec::SetTriple(const char *triple) { + LLDB_INSTRUMENT_VA(this, triple); + + m_opaque_up->GetArchitecture().SetTriple(triple); +} + +const uint8_t *SBModuleSpec::GetUUIDBytes() { + LLDB_INSTRUMENT_VA(this) + return m_opaque_up->GetUUID().GetBytes().data(); +} + +size_t SBModuleSpec::GetUUIDLength() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetUUID().GetBytes().size(); +} + +bool SBModuleSpec::SetUUIDBytes(const uint8_t *uuid, size_t uuid_len) { + LLDB_INSTRUMENT_VA(this, uuid, uuid_len) + m_opaque_up->GetUUID() = UUID(uuid, uuid_len); + return m_opaque_up->GetUUID().IsValid(); +} + +bool SBModuleSpec::GetDescription(lldb::SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + m_opaque_up->Dump(description.ref()); + return true; +} + +uint64_t SBModuleSpec::GetObjectOffset() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetObjectOffset(); +} + +void SBModuleSpec::SetObjectOffset(uint64_t object_offset) { + LLDB_INSTRUMENT_VA(this, object_offset); + + m_opaque_up->SetObjectOffset(object_offset); +} + +uint64_t SBModuleSpec::GetObjectSize() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetObjectSize(); +} + +void SBModuleSpec::SetObjectSize(uint64_t object_size) { + LLDB_INSTRUMENT_VA(this, object_size); + + m_opaque_up->SetObjectSize(object_size); +} + +SBModuleSpecList::SBModuleSpecList() : m_opaque_up(new ModuleSpecList()) { + LLDB_INSTRUMENT_VA(this); +} + +SBModuleSpecList::SBModuleSpecList(const SBModuleSpecList &rhs) + : m_opaque_up(new ModuleSpecList(*rhs.m_opaque_up)) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBModuleSpecList &SBModuleSpecList::operator=(const SBModuleSpecList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + *m_opaque_up = *rhs.m_opaque_up; + return *this; +} + +SBModuleSpecList::~SBModuleSpecList() = default; + +SBModuleSpecList SBModuleSpecList::GetModuleSpecifications(const char *path) { + LLDB_INSTRUMENT_VA(path); + + SBModuleSpecList specs; + FileSpec file_spec(path); + FileSystem::Instance().Resolve(file_spec); + Host::ResolveExecutableInBundle(file_spec); + ObjectFile::GetModuleSpecifications(file_spec, 0, 0, *specs.m_opaque_up); + return specs; +} + +void SBModuleSpecList::Append(const SBModuleSpec &spec) { + LLDB_INSTRUMENT_VA(this, spec); + + m_opaque_up->Append(*spec.m_opaque_up); +} + +void SBModuleSpecList::Append(const SBModuleSpecList &spec_list) { + LLDB_INSTRUMENT_VA(this, spec_list); + + m_opaque_up->Append(*spec_list.m_opaque_up); +} + +size_t SBModuleSpecList::GetSize() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetSize(); +} + +SBModuleSpec SBModuleSpecList::GetSpecAtIndex(size_t i) { + LLDB_INSTRUMENT_VA(this, i); + + SBModuleSpec sb_module_spec; + m_opaque_up->GetModuleSpecAtIndex(i, *sb_module_spec.m_opaque_up); + return sb_module_spec; +} + +SBModuleSpec +SBModuleSpecList::FindFirstMatchingSpec(const SBModuleSpec &match_spec) { + LLDB_INSTRUMENT_VA(this, match_spec); + + SBModuleSpec sb_module_spec; + m_opaque_up->FindMatchingModuleSpec(*match_spec.m_opaque_up, + *sb_module_spec.m_opaque_up); + return sb_module_spec; +} + +SBModuleSpecList +SBModuleSpecList::FindMatchingSpecs(const SBModuleSpec &match_spec) { + LLDB_INSTRUMENT_VA(this, match_spec); + + SBModuleSpecList specs; + m_opaque_up->FindMatchingModuleSpecs(*match_spec.m_opaque_up, + *specs.m_opaque_up); + return specs; +} + +bool SBModuleSpecList::GetDescription(lldb::SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + m_opaque_up->Dump(description.ref()); + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBPlatform.cpp b/contrib/llvm-project/lldb/source/API/SBPlatform.cpp new file mode 100644 index 000000000000..3623fd35bcdf --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBPlatform.cpp @@ -0,0 +1,736 @@ +//===-- SBPlatform.cpp ----------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBPlatform.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBEnvironment.h" +#include "lldb/API/SBError.h" +#include "lldb/API/SBFileSpec.h" +#include "lldb/API/SBLaunchInfo.h" +#include "lldb/API/SBModuleSpec.h" +#include "lldb/API/SBPlatform.h" +#include "lldb/API/SBProcessInfoList.h" +#include "lldb/API/SBTarget.h" +#include "lldb/API/SBUnixSignals.h" +#include "lldb/Host/File.h" +#include "lldb/Target/Platform.h" +#include "lldb/Target/Target.h" +#include "lldb/Utility/ArchSpec.h" +#include "lldb/Utility/Args.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Status.h" + +#include "llvm/Support/FileSystem.h" + +#include <functional> + +using namespace lldb; +using namespace lldb_private; + +// PlatformConnectOptions +struct PlatformConnectOptions { + PlatformConnectOptions(const char *url = nullptr) { + if (url && url[0]) + m_url = url; + } + + ~PlatformConnectOptions() = default; + + std::string m_url; + std::string m_rsync_options; + std::string m_rsync_remote_path_prefix; + bool m_rsync_enabled = false; + bool m_rsync_omit_hostname_from_remote_path = false; + ConstString m_local_cache_directory; +}; + +// PlatformShellCommand +struct PlatformShellCommand { + PlatformShellCommand(llvm::StringRef shell_interpreter, + llvm::StringRef shell_command) { + if (!shell_interpreter.empty()) + m_shell = shell_interpreter.str(); + + if (!m_shell.empty() && !shell_command.empty()) + m_command = shell_command.str(); + } + + PlatformShellCommand(llvm::StringRef shell_command = llvm::StringRef()) { + if (!shell_command.empty()) + m_command = shell_command.str(); + } + + ~PlatformShellCommand() = default; + + std::string m_shell; + std::string m_command; + std::string m_working_dir; + std::string m_output; + int m_status = 0; + int m_signo = 0; + Timeout<std::ratio<1>> m_timeout = std::nullopt; +}; +// SBPlatformConnectOptions +SBPlatformConnectOptions::SBPlatformConnectOptions(const char *url) + : m_opaque_ptr(new PlatformConnectOptions(url)) { + LLDB_INSTRUMENT_VA(this, url); +} + +SBPlatformConnectOptions::SBPlatformConnectOptions( + const SBPlatformConnectOptions &rhs) + : m_opaque_ptr(new PlatformConnectOptions()) { + LLDB_INSTRUMENT_VA(this, rhs); + + *m_opaque_ptr = *rhs.m_opaque_ptr; +} + +SBPlatformConnectOptions::~SBPlatformConnectOptions() { delete m_opaque_ptr; } + +SBPlatformConnectOptions & +SBPlatformConnectOptions::operator=(const SBPlatformConnectOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + *m_opaque_ptr = *rhs.m_opaque_ptr; + return *this; +} + +const char *SBPlatformConnectOptions::GetURL() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr->m_url.empty()) + return nullptr; + return ConstString(m_opaque_ptr->m_url.c_str()).GetCString(); +} + +void SBPlatformConnectOptions::SetURL(const char *url) { + LLDB_INSTRUMENT_VA(this, url); + + if (url && url[0]) + m_opaque_ptr->m_url = url; + else + m_opaque_ptr->m_url.clear(); +} + +bool SBPlatformConnectOptions::GetRsyncEnabled() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_ptr->m_rsync_enabled; +} + +void SBPlatformConnectOptions::EnableRsync( + const char *options, const char *remote_path_prefix, + bool omit_hostname_from_remote_path) { + LLDB_INSTRUMENT_VA(this, options, remote_path_prefix, + omit_hostname_from_remote_path); + + m_opaque_ptr->m_rsync_enabled = true; + m_opaque_ptr->m_rsync_omit_hostname_from_remote_path = + omit_hostname_from_remote_path; + if (remote_path_prefix && remote_path_prefix[0]) + m_opaque_ptr->m_rsync_remote_path_prefix = remote_path_prefix; + else + m_opaque_ptr->m_rsync_remote_path_prefix.clear(); + + if (options && options[0]) + m_opaque_ptr->m_rsync_options = options; + else + m_opaque_ptr->m_rsync_options.clear(); +} + +void SBPlatformConnectOptions::DisableRsync() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_ptr->m_rsync_enabled = false; +} + +const char *SBPlatformConnectOptions::GetLocalCacheDirectory() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_ptr->m_local_cache_directory.GetCString(); +} + +void SBPlatformConnectOptions::SetLocalCacheDirectory(const char *path) { + LLDB_INSTRUMENT_VA(this, path); + + if (path && path[0]) + m_opaque_ptr->m_local_cache_directory.SetCString(path); + else + m_opaque_ptr->m_local_cache_directory = ConstString(); +} + +// SBPlatformShellCommand +SBPlatformShellCommand::SBPlatformShellCommand(const char *shell_interpreter, + const char *shell_command) + : m_opaque_ptr(new PlatformShellCommand(shell_interpreter, shell_command)) { + LLDB_INSTRUMENT_VA(this, shell_interpreter, shell_command); +} + +SBPlatformShellCommand::SBPlatformShellCommand(const char *shell_command) + : m_opaque_ptr(new PlatformShellCommand(shell_command)) { + LLDB_INSTRUMENT_VA(this, shell_command); +} + +SBPlatformShellCommand::SBPlatformShellCommand( + const SBPlatformShellCommand &rhs) + : m_opaque_ptr(new PlatformShellCommand()) { + LLDB_INSTRUMENT_VA(this, rhs); + + *m_opaque_ptr = *rhs.m_opaque_ptr; +} + +SBPlatformShellCommand & +SBPlatformShellCommand::operator=(const SBPlatformShellCommand &rhs) { + + LLDB_INSTRUMENT_VA(this, rhs); + + *m_opaque_ptr = *rhs.m_opaque_ptr; + return *this; +} + +SBPlatformShellCommand::~SBPlatformShellCommand() { delete m_opaque_ptr; } + +void SBPlatformShellCommand::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_ptr->m_output = std::string(); + m_opaque_ptr->m_status = 0; + m_opaque_ptr->m_signo = 0; +} + +const char *SBPlatformShellCommand::GetShell() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr->m_shell.empty()) + return nullptr; + return ConstString(m_opaque_ptr->m_shell.c_str()).GetCString(); +} + +void SBPlatformShellCommand::SetShell(const char *shell_interpreter) { + LLDB_INSTRUMENT_VA(this, shell_interpreter); + + if (shell_interpreter && shell_interpreter[0]) + m_opaque_ptr->m_shell = shell_interpreter; + else + m_opaque_ptr->m_shell.clear(); +} + +const char *SBPlatformShellCommand::GetCommand() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr->m_command.empty()) + return nullptr; + return ConstString(m_opaque_ptr->m_command.c_str()).GetCString(); +} + +void SBPlatformShellCommand::SetCommand(const char *shell_command) { + LLDB_INSTRUMENT_VA(this, shell_command); + + if (shell_command && shell_command[0]) + m_opaque_ptr->m_command = shell_command; + else + m_opaque_ptr->m_command.clear(); +} + +const char *SBPlatformShellCommand::GetWorkingDirectory() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr->m_working_dir.empty()) + return nullptr; + return ConstString(m_opaque_ptr->m_working_dir.c_str()).GetCString(); +} + +void SBPlatformShellCommand::SetWorkingDirectory(const char *path) { + LLDB_INSTRUMENT_VA(this, path); + + if (path && path[0]) + m_opaque_ptr->m_working_dir = path; + else + m_opaque_ptr->m_working_dir.clear(); +} + +uint32_t SBPlatformShellCommand::GetTimeoutSeconds() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr->m_timeout) + return m_opaque_ptr->m_timeout->count(); + return UINT32_MAX; +} + +void SBPlatformShellCommand::SetTimeoutSeconds(uint32_t sec) { + LLDB_INSTRUMENT_VA(this, sec); + + if (sec == UINT32_MAX) + m_opaque_ptr->m_timeout = std::nullopt; + else + m_opaque_ptr->m_timeout = std::chrono::seconds(sec); +} + +int SBPlatformShellCommand::GetSignal() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_ptr->m_signo; +} + +int SBPlatformShellCommand::GetStatus() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_ptr->m_status; +} + +const char *SBPlatformShellCommand::GetOutput() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr->m_output.empty()) + return nullptr; + return ConstString(m_opaque_ptr->m_output.c_str()).GetCString(); +} + +// SBPlatform +SBPlatform::SBPlatform() { LLDB_INSTRUMENT_VA(this); } + +SBPlatform::SBPlatform(const char *platform_name) { + LLDB_INSTRUMENT_VA(this, platform_name); + + m_opaque_sp = Platform::Create(platform_name); +} + +SBPlatform::SBPlatform(const SBPlatform &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_sp = rhs.m_opaque_sp; +} + +SBPlatform &SBPlatform::operator=(const SBPlatform &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_sp = rhs.m_opaque_sp; + return *this; +} + +SBPlatform::~SBPlatform() = default; + +SBPlatform SBPlatform::GetHostPlatform() { + LLDB_INSTRUMENT(); + + SBPlatform host_platform; + host_platform.m_opaque_sp = Platform::GetHostPlatform(); + return host_platform; +} + +bool SBPlatform::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBPlatform::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} + +void SBPlatform::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_sp.reset(); +} + +const char *SBPlatform::GetName() { + LLDB_INSTRUMENT_VA(this); + + PlatformSP platform_sp(GetSP()); + if (platform_sp) + return ConstString(platform_sp->GetName()).AsCString(); + return nullptr; +} + +lldb::PlatformSP SBPlatform::GetSP() const { return m_opaque_sp; } + +void SBPlatform::SetSP(const lldb::PlatformSP &platform_sp) { + m_opaque_sp = platform_sp; +} + +const char *SBPlatform::GetWorkingDirectory() { + LLDB_INSTRUMENT_VA(this); + + PlatformSP platform_sp(GetSP()); + if (platform_sp) + return platform_sp->GetWorkingDirectory().GetPathAsConstString().AsCString(); + return nullptr; +} + +bool SBPlatform::SetWorkingDirectory(const char *path) { + LLDB_INSTRUMENT_VA(this, path); + + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + if (path) + platform_sp->SetWorkingDirectory(FileSpec(path)); + else + platform_sp->SetWorkingDirectory(FileSpec()); + return true; + } + return false; +} + +SBError SBPlatform::ConnectRemote(SBPlatformConnectOptions &connect_options) { + LLDB_INSTRUMENT_VA(this, connect_options); + + SBError sb_error; + PlatformSP platform_sp(GetSP()); + if (platform_sp && connect_options.GetURL()) { + Args args; + args.AppendArgument(connect_options.GetURL()); + sb_error.ref() = platform_sp->ConnectRemote(args); + } else { + sb_error.SetErrorString("invalid platform"); + } + return sb_error; +} + +void SBPlatform::DisconnectRemote() { + LLDB_INSTRUMENT_VA(this); + + PlatformSP platform_sp(GetSP()); + if (platform_sp) + platform_sp->DisconnectRemote(); +} + +bool SBPlatform::IsConnected() { + LLDB_INSTRUMENT_VA(this); + + PlatformSP platform_sp(GetSP()); + if (platform_sp) + return platform_sp->IsConnected(); + return false; +} + +const char *SBPlatform::GetTriple() { + LLDB_INSTRUMENT_VA(this); + + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + ArchSpec arch(platform_sp->GetSystemArchitecture()); + if (arch.IsValid()) { + // Const-ify the string so we don't need to worry about the lifetime of + // the string + return ConstString(arch.GetTriple().getTriple().c_str()).GetCString(); + } + } + return nullptr; +} + +const char *SBPlatform::GetOSBuild() { + LLDB_INSTRUMENT_VA(this); + + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + std::string s = platform_sp->GetOSBuildString().value_or(""); + if (!s.empty()) { + // Const-ify the string so we don't need to worry about the lifetime of + // the string + return ConstString(s).GetCString(); + } + } + return nullptr; +} + +const char *SBPlatform::GetOSDescription() { + LLDB_INSTRUMENT_VA(this); + + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + std::string s = platform_sp->GetOSKernelDescription().value_or(""); + if (!s.empty()) { + // Const-ify the string so we don't need to worry about the lifetime of + // the string + return ConstString(s.c_str()).GetCString(); + } + } + return nullptr; +} + +const char *SBPlatform::GetHostname() { + LLDB_INSTRUMENT_VA(this); + + PlatformSP platform_sp(GetSP()); + if (platform_sp) + return ConstString(platform_sp->GetHostname()).GetCString(); + return nullptr; +} + +uint32_t SBPlatform::GetOSMajorVersion() { + LLDB_INSTRUMENT_VA(this); + + llvm::VersionTuple version; + if (PlatformSP platform_sp = GetSP()) + version = platform_sp->GetOSVersion(); + return version.empty() ? UINT32_MAX : version.getMajor(); +} + +uint32_t SBPlatform::GetOSMinorVersion() { + LLDB_INSTRUMENT_VA(this); + + llvm::VersionTuple version; + if (PlatformSP platform_sp = GetSP()) + version = platform_sp->GetOSVersion(); + return version.getMinor().value_or(UINT32_MAX); +} + +uint32_t SBPlatform::GetOSUpdateVersion() { + LLDB_INSTRUMENT_VA(this); + + llvm::VersionTuple version; + if (PlatformSP platform_sp = GetSP()) + version = platform_sp->GetOSVersion(); + return version.getSubminor().value_or(UINT32_MAX); +} + +void SBPlatform::SetSDKRoot(const char *sysroot) { + LLDB_INSTRUMENT_VA(this, sysroot); + if (PlatformSP platform_sp = GetSP()) + platform_sp->SetSDKRootDirectory(llvm::StringRef(sysroot).str()); +} + +SBError SBPlatform::Get(SBFileSpec &src, SBFileSpec &dst) { + LLDB_INSTRUMENT_VA(this, src, dst); + + SBError sb_error; + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + sb_error.ref() = platform_sp->GetFile(src.ref(), dst.ref()); + } else { + sb_error.SetErrorString("invalid platform"); + } + return sb_error; +} + +SBError SBPlatform::Put(SBFileSpec &src, SBFileSpec &dst) { + LLDB_INSTRUMENT_VA(this, src, dst); + return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { + if (src.Exists()) { + uint32_t permissions = FileSystem::Instance().GetPermissions(src.ref()); + if (permissions == 0) { + if (FileSystem::Instance().IsDirectory(src.ref())) + permissions = eFilePermissionsDirectoryDefault; + else + permissions = eFilePermissionsFileDefault; + } + + return platform_sp->PutFile(src.ref(), dst.ref(), permissions); + } + + Status error; + error.SetErrorStringWithFormat("'src' argument doesn't exist: '%s'", + src.ref().GetPath().c_str()); + return error; + }); +} + +SBError SBPlatform::Install(SBFileSpec &src, SBFileSpec &dst) { + LLDB_INSTRUMENT_VA(this, src, dst); + return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { + if (src.Exists()) + return platform_sp->Install(src.ref(), dst.ref()); + + Status error; + error.SetErrorStringWithFormat("'src' argument doesn't exist: '%s'", + src.ref().GetPath().c_str()); + return error; + }); +} + +SBError SBPlatform::Run(SBPlatformShellCommand &shell_command) { + LLDB_INSTRUMENT_VA(this, shell_command); + return ExecuteConnected( + [&](const lldb::PlatformSP &platform_sp) { + const char *command = shell_command.GetCommand(); + if (!command) + return Status("invalid shell command (empty)"); + + if (shell_command.GetWorkingDirectory() == nullptr) { + std::string platform_working_dir = + platform_sp->GetWorkingDirectory().GetPath(); + if (!platform_working_dir.empty()) + shell_command.SetWorkingDirectory(platform_working_dir.c_str()); + } + return platform_sp->RunShellCommand( + shell_command.m_opaque_ptr->m_shell, command, + FileSpec(shell_command.GetWorkingDirectory()), + &shell_command.m_opaque_ptr->m_status, + &shell_command.m_opaque_ptr->m_signo, + &shell_command.m_opaque_ptr->m_output, + shell_command.m_opaque_ptr->m_timeout); + }); +} + +SBError SBPlatform::Launch(SBLaunchInfo &launch_info) { + LLDB_INSTRUMENT_VA(this, launch_info); + return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { + ProcessLaunchInfo info = launch_info.ref(); + Status error = platform_sp->LaunchProcess(info); + launch_info.set_ref(info); + return error; + }); +} + +SBProcess SBPlatform::Attach(SBAttachInfo &attach_info, + const SBDebugger &debugger, SBTarget &target, + SBError &error) { + LLDB_INSTRUMENT_VA(this, attach_info, debugger, target, error); + + if (PlatformSP platform_sp = GetSP()) { + if (platform_sp->IsConnected()) { + ProcessAttachInfo &info = attach_info.ref(); + Status status; + ProcessSP process_sp = platform_sp->Attach(info, debugger.ref(), + target.GetSP().get(), status); + error.SetError(status); + return SBProcess(process_sp); + } + + error.SetErrorString("not connected"); + return {}; + } + + error.SetErrorString("invalid platform"); + return {}; +} + +SBProcessInfoList SBPlatform::GetAllProcesses(SBError &error) { + if (PlatformSP platform_sp = GetSP()) { + if (platform_sp->IsConnected()) { + ProcessInstanceInfoList list = platform_sp->GetAllProcesses(); + return SBProcessInfoList(list); + } + error.SetErrorString("not connected"); + return {}; + } + + error.SetErrorString("invalid platform"); + return {}; +} + +SBError SBPlatform::Kill(const lldb::pid_t pid) { + LLDB_INSTRUMENT_VA(this, pid); + return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { + return platform_sp->KillProcess(pid); + }); +} + +SBError SBPlatform::ExecuteConnected( + const std::function<Status(const lldb::PlatformSP &)> &func) { + SBError sb_error; + const auto platform_sp(GetSP()); + if (platform_sp) { + if (platform_sp->IsConnected()) + sb_error.ref() = func(platform_sp); + else + sb_error.SetErrorString("not connected"); + } else + sb_error.SetErrorString("invalid platform"); + + return sb_error; +} + +SBError SBPlatform::MakeDirectory(const char *path, uint32_t file_permissions) { + LLDB_INSTRUMENT_VA(this, path, file_permissions); + + SBError sb_error; + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + sb_error.ref() = + platform_sp->MakeDirectory(FileSpec(path), file_permissions); + } else { + sb_error.SetErrorString("invalid platform"); + } + return sb_error; +} + +uint32_t SBPlatform::GetFilePermissions(const char *path) { + LLDB_INSTRUMENT_VA(this, path); + + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + uint32_t file_permissions = 0; + platform_sp->GetFilePermissions(FileSpec(path), file_permissions); + return file_permissions; + } + return 0; +} + +SBError SBPlatform::SetFilePermissions(const char *path, + uint32_t file_permissions) { + LLDB_INSTRUMENT_VA(this, path, file_permissions); + + SBError sb_error; + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + sb_error.ref() = + platform_sp->SetFilePermissions(FileSpec(path), file_permissions); + } else { + sb_error.SetErrorString("invalid platform"); + } + return sb_error; +} + +SBUnixSignals SBPlatform::GetUnixSignals() const { + LLDB_INSTRUMENT_VA(this); + + if (auto platform_sp = GetSP()) + return SBUnixSignals{platform_sp}; + + return SBUnixSignals(); +} + +SBEnvironment SBPlatform::GetEnvironment() { + LLDB_INSTRUMENT_VA(this); + PlatformSP platform_sp(GetSP()); + + if (platform_sp) { + return SBEnvironment(platform_sp->GetEnvironment()); + } + + return SBEnvironment(); +} + +SBError SBPlatform::SetLocateModuleCallback( + lldb::SBPlatformLocateModuleCallback callback, void *callback_baton) { + LLDB_INSTRUMENT_VA(this, callback, callback_baton); + PlatformSP platform_sp(GetSP()); + if (!platform_sp) + return SBError("invalid platform"); + + if (!callback) { + // Clear the callback. + platform_sp->SetLocateModuleCallback(nullptr); + return SBError(); + } + + // Platform.h does not accept lldb::SBPlatformLocateModuleCallback directly + // because of the SBModuleSpec and SBFileSpec dependencies. Use a lambda to + // convert ModuleSpec/FileSpec <--> SBModuleSpec/SBFileSpec for the callback + // arguments. + platform_sp->SetLocateModuleCallback( + [callback, callback_baton](const ModuleSpec &module_spec, + FileSpec &module_file_spec, + FileSpec &symbol_file_spec) { + SBModuleSpec module_spec_sb(module_spec); + SBFileSpec module_file_spec_sb; + SBFileSpec symbol_file_spec_sb; + + SBError error = callback(callback_baton, module_spec_sb, + module_file_spec_sb, symbol_file_spec_sb); + + if (error.Success()) { + module_file_spec = module_file_spec_sb.ref(); + symbol_file_spec = symbol_file_spec_sb.ref(); + } + + return error.ref(); + }); + return SBError(); +} diff --git a/contrib/llvm-project/lldb/source/API/SBProcess.cpp b/contrib/llvm-project/lldb/source/API/SBProcess.cpp new file mode 100644 index 000000000000..b88f897ff528 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBProcess.cpp @@ -0,0 +1,1467 @@ +//===-- SBProcess.cpp -----------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBProcess.h" +#include "lldb/Utility/Instrumentation.h" + +#include <cinttypes> + +#include "lldb/lldb-defines.h" +#include "lldb/lldb-types.h" + +#include "lldb/Core/AddressRangeListImpl.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Core/Module.h" +#include "lldb/Core/PluginManager.h" +#include "lldb/Core/StructuredDataImpl.h" +#include "lldb/Host/StreamFile.h" +#include "lldb/Target/MemoryRegionInfo.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/RegisterContext.h" +#include "lldb/Target/SystemRuntime.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" +#include "lldb/Utility/Args.h" +#include "lldb/Utility/LLDBLog.h" +#include "lldb/Utility/ProcessInfo.h" +#include "lldb/Utility/State.h" +#include "lldb/Utility/Stream.h" + +#include "lldb/API/SBBroadcaster.h" +#include "lldb/API/SBCommandReturnObject.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBFile.h" +#include "lldb/API/SBFileSpec.h" +#include "lldb/API/SBMemoryRegionInfo.h" +#include "lldb/API/SBMemoryRegionInfoList.h" +#include "lldb/API/SBSaveCoreOptions.h" +#include "lldb/API/SBScriptObject.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStringList.h" +#include "lldb/API/SBStructuredData.h" +#include "lldb/API/SBThread.h" +#include "lldb/API/SBThreadCollection.h" +#include "lldb/API/SBTrace.h" +#include "lldb/API/SBUnixSignals.h" + +using namespace lldb; +using namespace lldb_private; + +SBProcess::SBProcess() { LLDB_INSTRUMENT_VA(this); } + +// SBProcess constructor + +SBProcess::SBProcess(const SBProcess &rhs) : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBProcess::SBProcess(const lldb::ProcessSP &process_sp) + : m_opaque_wp(process_sp) { + LLDB_INSTRUMENT_VA(this, process_sp); +} + +const SBProcess &SBProcess::operator=(const SBProcess &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_wp = rhs.m_opaque_wp; + return *this; +} + +// Destructor +SBProcess::~SBProcess() = default; + +const char *SBProcess::GetBroadcasterClassName() { + LLDB_INSTRUMENT(); + + return ConstString(Process::GetStaticBroadcasterClass()).AsCString(); +} + +const char *SBProcess::GetPluginName() { + LLDB_INSTRUMENT_VA(this); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + return ConstString(process_sp->GetPluginName()).GetCString(); + } + return "<Unknown>"; +} + +const char *SBProcess::GetShortPluginName() { + LLDB_INSTRUMENT_VA(this); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + return ConstString(process_sp->GetPluginName()).GetCString(); + } + return "<Unknown>"; +} + +lldb::ProcessSP SBProcess::GetSP() const { return m_opaque_wp.lock(); } + +void SBProcess::SetSP(const ProcessSP &process_sp) { m_opaque_wp = process_sp; } + +void SBProcess::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_wp.reset(); +} + +bool SBProcess::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBProcess::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + ProcessSP process_sp(m_opaque_wp.lock()); + return ((bool)process_sp && process_sp->IsValid()); +} + +bool SBProcess::RemoteLaunch(char const **argv, char const **envp, + const char *stdin_path, const char *stdout_path, + const char *stderr_path, + const char *working_directory, + uint32_t launch_flags, bool stop_at_entry, + lldb::SBError &error) { + LLDB_INSTRUMENT_VA(this, argv, envp, stdin_path, stdout_path, stderr_path, + working_directory, launch_flags, stop_at_entry, error); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + if (process_sp->GetState() == eStateConnected) { + if (stop_at_entry) + launch_flags |= eLaunchFlagStopAtEntry; + ProcessLaunchInfo launch_info(FileSpec(stdin_path), FileSpec(stdout_path), + FileSpec(stderr_path), + FileSpec(working_directory), launch_flags); + Module *exe_module = process_sp->GetTarget().GetExecutableModulePointer(); + if (exe_module) + launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true); + if (argv) + launch_info.GetArguments().AppendArguments(argv); + if (envp) + launch_info.GetEnvironment() = Environment(envp); + error.SetError(process_sp->Launch(launch_info)); + } else { + error.SetErrorString("must be in eStateConnected to call RemoteLaunch"); + } + } else { + error.SetErrorString("unable to attach pid"); + } + + return error.Success(); +} + +bool SBProcess::RemoteAttachToProcessWithID(lldb::pid_t pid, + lldb::SBError &error) { + LLDB_INSTRUMENT_VA(this, pid, error); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + if (process_sp->GetState() == eStateConnected) { + ProcessAttachInfo attach_info; + attach_info.SetProcessID(pid); + error.SetError(process_sp->Attach(attach_info)); + } else { + error.SetErrorString( + "must be in eStateConnected to call RemoteAttachToProcessWithID"); + } + } else { + error.SetErrorString("unable to attach pid"); + } + + return error.Success(); +} + +uint32_t SBProcess::GetNumThreads() { + LLDB_INSTRUMENT_VA(this); + + uint32_t num_threads = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + + const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + num_threads = process_sp->GetThreadList().GetSize(can_update); + } + + return num_threads; +} + +SBThread SBProcess::GetSelectedThread() const { + LLDB_INSTRUMENT_VA(this); + + SBThread sb_thread; + ThreadSP thread_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + thread_sp = process_sp->GetThreadList().GetSelectedThread(); + sb_thread.SetThread(thread_sp); + } + + return sb_thread; +} + +SBThread SBProcess::CreateOSPluginThread(lldb::tid_t tid, + lldb::addr_t context) { + LLDB_INSTRUMENT_VA(this, tid, context); + + SBThread sb_thread; + ThreadSP thread_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + thread_sp = process_sp->CreateOSPluginThread(tid, context); + sb_thread.SetThread(thread_sp); + } + + return sb_thread; +} + +SBTarget SBProcess::GetTarget() const { + LLDB_INSTRUMENT_VA(this); + + SBTarget sb_target; + TargetSP target_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + target_sp = process_sp->GetTarget().shared_from_this(); + sb_target.SetSP(target_sp); + } + + return sb_target; +} + +size_t SBProcess::PutSTDIN(const char *src, size_t src_len) { + LLDB_INSTRUMENT_VA(this, src, src_len); + + size_t ret_val = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Status error; + ret_val = process_sp->PutSTDIN(src, src_len, error); + } + + return ret_val; +} + +size_t SBProcess::GetSTDOUT(char *dst, size_t dst_len) const { + LLDB_INSTRUMENT_VA(this, dst, dst_len); + + size_t bytes_read = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Status error; + bytes_read = process_sp->GetSTDOUT(dst, dst_len, error); + } + + return bytes_read; +} + +size_t SBProcess::GetSTDERR(char *dst, size_t dst_len) const { + LLDB_INSTRUMENT_VA(this, dst, dst_len); + + size_t bytes_read = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Status error; + bytes_read = process_sp->GetSTDERR(dst, dst_len, error); + } + + return bytes_read; +} + +size_t SBProcess::GetAsyncProfileData(char *dst, size_t dst_len) const { + LLDB_INSTRUMENT_VA(this, dst, dst_len); + + size_t bytes_read = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Status error; + bytes_read = process_sp->GetAsyncProfileData(dst, dst_len, error); + } + + return bytes_read; +} + +void SBProcess::ReportEventState(const SBEvent &event, SBFile out) const { + LLDB_INSTRUMENT_VA(this, event, out); + + return ReportEventState(event, out.m_opaque_sp); +} + +void SBProcess::ReportEventState(const SBEvent &event, FILE *out) const { + LLDB_INSTRUMENT_VA(this, event, out); + FileSP outfile = std::make_shared<NativeFile>(out, false); + return ReportEventState(event, outfile); +} + +void SBProcess::ReportEventState(const SBEvent &event, FileSP out) const { + + LLDB_INSTRUMENT_VA(this, event, out); + + if (!out || !out->IsValid()) + return; + + ProcessSP process_sp(GetSP()); + if (process_sp) { + StreamFile stream(out); + const StateType event_state = SBProcess::GetStateFromEvent(event); + stream.Printf("Process %" PRIu64 " %s\n", process_sp->GetID(), + SBDebugger::StateAsCString(event_state)); + } +} + +void SBProcess::AppendEventStateReport(const SBEvent &event, + SBCommandReturnObject &result) { + LLDB_INSTRUMENT_VA(this, event, result); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + const StateType event_state = SBProcess::GetStateFromEvent(event); + char message[1024]; + ::snprintf(message, sizeof(message), "Process %" PRIu64 " %s\n", + process_sp->GetID(), SBDebugger::StateAsCString(event_state)); + + result.AppendMessage(message); + } +} + +bool SBProcess::SetSelectedThread(const SBThread &thread) { + LLDB_INSTRUMENT_VA(this, thread); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + return process_sp->GetThreadList().SetSelectedThreadByID( + thread.GetThreadID()); + } + return false; +} + +bool SBProcess::SetSelectedThreadByID(lldb::tid_t tid) { + LLDB_INSTRUMENT_VA(this, tid); + + bool ret_val = false; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + ret_val = process_sp->GetThreadList().SetSelectedThreadByID(tid); + } + + return ret_val; +} + +bool SBProcess::SetSelectedThreadByIndexID(uint32_t index_id) { + LLDB_INSTRUMENT_VA(this, index_id); + + bool ret_val = false; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + ret_val = process_sp->GetThreadList().SetSelectedThreadByIndexID(index_id); + } + + return ret_val; +} + +SBThread SBProcess::GetThreadAtIndex(size_t index) { + LLDB_INSTRUMENT_VA(this, index); + + SBThread sb_thread; + ThreadSP thread_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + thread_sp = process_sp->GetThreadList().GetThreadAtIndex(index, can_update); + sb_thread.SetThread(thread_sp); + } + + return sb_thread; +} + +uint32_t SBProcess::GetNumQueues() { + LLDB_INSTRUMENT_VA(this); + + uint32_t num_queues = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + num_queues = process_sp->GetQueueList().GetSize(); + } + } + + return num_queues; +} + +SBQueue SBProcess::GetQueueAtIndex(size_t index) { + LLDB_INSTRUMENT_VA(this, index); + + SBQueue sb_queue; + QueueSP queue_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + queue_sp = process_sp->GetQueueList().GetQueueAtIndex(index); + sb_queue.SetQueue(queue_sp); + } + } + + return sb_queue; +} + +uint32_t SBProcess::GetStopID(bool include_expression_stops) { + LLDB_INSTRUMENT_VA(this, include_expression_stops); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + if (include_expression_stops) + return process_sp->GetStopID(); + else + return process_sp->GetLastNaturalStopID(); + } + return 0; +} + +SBEvent SBProcess::GetStopEventForStopID(uint32_t stop_id) { + LLDB_INSTRUMENT_VA(this, stop_id); + + SBEvent sb_event; + EventSP event_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + event_sp = process_sp->GetStopEventForStopID(stop_id); + sb_event.reset(event_sp); + } + + return sb_event; +} + +void SBProcess::ForceScriptedState(StateType new_state) { + LLDB_INSTRUMENT_VA(this, new_state); + + if (ProcessSP process_sp = GetSP()) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + process_sp->ForceScriptedState(new_state); + } +} + +StateType SBProcess::GetState() { + LLDB_INSTRUMENT_VA(this); + + StateType ret_val = eStateInvalid; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + ret_val = process_sp->GetState(); + } + + return ret_val; +} + +int SBProcess::GetExitStatus() { + LLDB_INSTRUMENT_VA(this); + + int exit_status = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + exit_status = process_sp->GetExitStatus(); + } + + return exit_status; +} + +const char *SBProcess::GetExitDescription() { + LLDB_INSTRUMENT_VA(this); + + ProcessSP process_sp(GetSP()); + if (!process_sp) + return nullptr; + + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + return ConstString(process_sp->GetExitDescription()).GetCString(); +} + +lldb::pid_t SBProcess::GetProcessID() { + LLDB_INSTRUMENT_VA(this); + + lldb::pid_t ret_val = LLDB_INVALID_PROCESS_ID; + ProcessSP process_sp(GetSP()); + if (process_sp) + ret_val = process_sp->GetID(); + + return ret_val; +} + +uint32_t SBProcess::GetUniqueID() { + LLDB_INSTRUMENT_VA(this); + + uint32_t ret_val = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) + ret_val = process_sp->GetUniqueID(); + return ret_val; +} + +ByteOrder SBProcess::GetByteOrder() const { + LLDB_INSTRUMENT_VA(this); + + ByteOrder byteOrder = eByteOrderInvalid; + ProcessSP process_sp(GetSP()); + if (process_sp) + byteOrder = process_sp->GetTarget().GetArchitecture().GetByteOrder(); + + return byteOrder; +} + +uint32_t SBProcess::GetAddressByteSize() const { + LLDB_INSTRUMENT_VA(this); + + uint32_t size = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) + size = process_sp->GetTarget().GetArchitecture().GetAddressByteSize(); + + return size; +} + +SBError SBProcess::Continue() { + LLDB_INSTRUMENT_VA(this); + + SBError sb_error; + ProcessSP process_sp(GetSP()); + + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + + if (process_sp->GetTarget().GetDebugger().GetAsyncExecution()) + sb_error.ref() = process_sp->Resume(); + else + sb_error.ref() = process_sp->ResumeSynchronous(nullptr); + } else + sb_error.SetErrorString("SBProcess is invalid"); + + return sb_error; +} + +SBError SBProcess::Destroy() { + LLDB_INSTRUMENT_VA(this); + + SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->Destroy(false)); + } else + sb_error.SetErrorString("SBProcess is invalid"); + + return sb_error; +} + +SBError SBProcess::Stop() { + LLDB_INSTRUMENT_VA(this); + + SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->Halt()); + } else + sb_error.SetErrorString("SBProcess is invalid"); + + return sb_error; +} + +SBError SBProcess::Kill() { + LLDB_INSTRUMENT_VA(this); + + SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->Destroy(true)); + } else + sb_error.SetErrorString("SBProcess is invalid"); + + return sb_error; +} + +SBError SBProcess::Detach() { + LLDB_INSTRUMENT_VA(this); + + // FIXME: This should come from a process default. + bool keep_stopped = false; + return Detach(keep_stopped); +} + +SBError SBProcess::Detach(bool keep_stopped) { + LLDB_INSTRUMENT_VA(this, keep_stopped); + + SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->Detach(keep_stopped)); + } else + sb_error.SetErrorString("SBProcess is invalid"); + + return sb_error; +} + +SBError SBProcess::Signal(int signo) { + LLDB_INSTRUMENT_VA(this, signo); + + SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->Signal(signo)); + } else + sb_error.SetErrorString("SBProcess is invalid"); + + return sb_error; +} + +SBUnixSignals SBProcess::GetUnixSignals() { + LLDB_INSTRUMENT_VA(this); + + if (auto process_sp = GetSP()) + return SBUnixSignals{process_sp}; + + return SBUnixSignals{}; +} + +void SBProcess::SendAsyncInterrupt() { + LLDB_INSTRUMENT_VA(this); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + process_sp->SendAsyncInterrupt(); + } +} + +SBThread SBProcess::GetThreadByID(tid_t tid) { + LLDB_INSTRUMENT_VA(this, tid); + + SBThread sb_thread; + ThreadSP thread_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + thread_sp = process_sp->GetThreadList().FindThreadByID(tid, can_update); + sb_thread.SetThread(thread_sp); + } + + return sb_thread; +} + +SBThread SBProcess::GetThreadByIndexID(uint32_t index_id) { + LLDB_INSTRUMENT_VA(this, index_id); + + SBThread sb_thread; + ThreadSP thread_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + thread_sp = + process_sp->GetThreadList().FindThreadByIndexID(index_id, can_update); + sb_thread.SetThread(thread_sp); + } + + return sb_thread; +} + +StateType SBProcess::GetStateFromEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + StateType ret_val = Process::ProcessEventData::GetStateFromEvent(event.get()); + + return ret_val; +} + +bool SBProcess::GetRestartedFromEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + bool ret_val = Process::ProcessEventData::GetRestartedFromEvent(event.get()); + + return ret_val; +} + +size_t SBProcess::GetNumRestartedReasonsFromEvent(const lldb::SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return Process::ProcessEventData::GetNumRestartedReasons(event.get()); +} + +const char * +SBProcess::GetRestartedReasonAtIndexFromEvent(const lldb::SBEvent &event, + size_t idx) { + LLDB_INSTRUMENT_VA(event, idx); + + return ConstString(Process::ProcessEventData::GetRestartedReasonAtIndex( + event.get(), idx)) + .GetCString(); +} + +SBProcess SBProcess::GetProcessFromEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + ProcessSP process_sp = + Process::ProcessEventData::GetProcessFromEvent(event.get()); + if (!process_sp) { + // StructuredData events also know the process they come from. Try that. + process_sp = EventDataStructuredData::GetProcessFromEvent(event.get()); + } + + return SBProcess(process_sp); +} + +bool SBProcess::GetInterruptedFromEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return Process::ProcessEventData::GetInterruptedFromEvent(event.get()); +} + +lldb::SBStructuredData +SBProcess::GetStructuredDataFromEvent(const lldb::SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return SBStructuredData(event.GetSP()); +} + +bool SBProcess::EventIsProcessEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return Process::ProcessEventData::GetEventDataFromEvent(event.get()) != + nullptr; +} + +bool SBProcess::EventIsStructuredDataEvent(const lldb::SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + EventSP event_sp = event.GetSP(); + EventData *event_data = event_sp ? event_sp->GetData() : nullptr; + return event_data && (event_data->GetFlavor() == + EventDataStructuredData::GetFlavorString()); +} + +SBBroadcaster SBProcess::GetBroadcaster() const { + LLDB_INSTRUMENT_VA(this); + + ProcessSP process_sp(GetSP()); + + SBBroadcaster broadcaster(process_sp.get(), false); + + return broadcaster; +} + +const char *SBProcess::GetBroadcasterClass() { + LLDB_INSTRUMENT(); + + return ConstString(Process::GetStaticBroadcasterClass()).AsCString(); +} + +lldb::SBAddressRangeList SBProcess::FindRangesInMemory( + const void *buf, uint64_t size, const SBAddressRangeList &ranges, + uint32_t alignment, uint32_t max_matches, SBError &error) { + LLDB_INSTRUMENT_VA(this, buf, size, ranges, alignment, max_matches, error); + + lldb::SBAddressRangeList matches; + + ProcessSP process_sp(GetSP()); + if (!process_sp) { + error.SetErrorString("SBProcess is invalid"); + return matches; + } + Process::StopLocker stop_locker; + if (!stop_locker.TryLock(&process_sp->GetRunLock())) { + error.SetErrorString("process is running"); + return matches; + } + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + matches.m_opaque_up->ref() = process_sp->FindRangesInMemory( + reinterpret_cast<const uint8_t *>(buf), size, ranges.ref().ref(), + alignment, max_matches, error.ref()); + return matches; +} + +lldb::addr_t SBProcess::FindInMemory(const void *buf, uint64_t size, + const SBAddressRange &range, + uint32_t alignment, SBError &error) { + LLDB_INSTRUMENT_VA(this, buf, size, range, alignment, error); + + ProcessSP process_sp(GetSP()); + + if (!process_sp) { + error.SetErrorString("SBProcess is invalid"); + return LLDB_INVALID_ADDRESS; + } + + Process::StopLocker stop_locker; + if (!stop_locker.TryLock(&process_sp->GetRunLock())) { + error.SetErrorString("process is running"); + return LLDB_INVALID_ADDRESS; + } + + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + return process_sp->FindInMemory(reinterpret_cast<const uint8_t *>(buf), size, + range.ref(), alignment, error.ref()); +} + +size_t SBProcess::ReadMemory(addr_t addr, void *dst, size_t dst_len, + SBError &sb_error) { + LLDB_INSTRUMENT_VA(this, addr, dst, dst_len, sb_error); + + if (!dst) { + sb_error.SetErrorStringWithFormat( + "no buffer provided to read %zu bytes into", dst_len); + return 0; + } + + size_t bytes_read = 0; + ProcessSP process_sp(GetSP()); + + + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + bytes_read = process_sp->ReadMemory(addr, dst, dst_len, sb_error.ref()); + } else { + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + + return bytes_read; +} + +size_t SBProcess::ReadCStringFromMemory(addr_t addr, void *buf, size_t size, + lldb::SBError &sb_error) { + LLDB_INSTRUMENT_VA(this, addr, buf, size, sb_error); + + size_t bytes_read = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + bytes_read = process_sp->ReadCStringFromMemory(addr, (char *)buf, size, + sb_error.ref()); + } else { + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return bytes_read; +} + +uint64_t SBProcess::ReadUnsignedFromMemory(addr_t addr, uint32_t byte_size, + lldb::SBError &sb_error) { + LLDB_INSTRUMENT_VA(this, addr, byte_size, sb_error); + + uint64_t value = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + value = process_sp->ReadUnsignedIntegerFromMemory(addr, byte_size, 0, + sb_error.ref()); + } else { + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return value; +} + +lldb::addr_t SBProcess::ReadPointerFromMemory(addr_t addr, + lldb::SBError &sb_error) { + LLDB_INSTRUMENT_VA(this, addr, sb_error); + + lldb::addr_t ptr = LLDB_INVALID_ADDRESS; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + ptr = process_sp->ReadPointerFromMemory(addr, sb_error.ref()); + } else { + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return ptr; +} + +size_t SBProcess::WriteMemory(addr_t addr, const void *src, size_t src_len, + SBError &sb_error) { + LLDB_INSTRUMENT_VA(this, addr, src, src_len, sb_error); + + size_t bytes_written = 0; + + ProcessSP process_sp(GetSP()); + + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + bytes_written = + process_sp->WriteMemory(addr, src, src_len, sb_error.ref()); + } else { + sb_error.SetErrorString("process is running"); + } + } + + return bytes_written; +} + +void SBProcess::GetStatus(SBStream &status) { + LLDB_INSTRUMENT_VA(this, status); + + ProcessSP process_sp(GetSP()); + if (process_sp) + process_sp->GetStatus(status.ref()); +} + +bool SBProcess::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + char path[PATH_MAX]; + GetTarget().GetExecutable().GetPath(path, sizeof(path)); + Module *exe_module = process_sp->GetTarget().GetExecutableModulePointer(); + const char *exe_name = nullptr; + if (exe_module) + exe_name = exe_module->GetFileSpec().GetFilename().AsCString(); + + strm.Printf("SBProcess: pid = %" PRIu64 ", state = %s, threads = %d%s%s", + process_sp->GetID(), lldb_private::StateAsCString(GetState()), + GetNumThreads(), exe_name ? ", executable = " : "", + exe_name ? exe_name : ""); + } else + strm.PutCString("No value"); + + return true; +} + +SBStructuredData SBProcess::GetExtendedCrashInformation() { + LLDB_INSTRUMENT_VA(this); + SBStructuredData data; + ProcessSP process_sp(GetSP()); + if (!process_sp) + return data; + + PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); + + if (!platform_sp) + return data; + + auto expected_data = + platform_sp->FetchExtendedCrashInformation(*process_sp.get()); + + if (!expected_data) + return data; + + StructuredData::ObjectSP fetched_data = *expected_data; + data.m_impl_up->SetObjectSP(fetched_data); + return data; +} + +uint32_t +SBProcess::GetNumSupportedHardwareWatchpoints(lldb::SBError &sb_error) const { + LLDB_INSTRUMENT_VA(this, sb_error); + + uint32_t num = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + std::optional<uint32_t> actual_num = process_sp->GetWatchpointSlotCount(); + if (actual_num) { + num = *actual_num; + } else { + sb_error.SetErrorString("Unable to determine number of watchpoints"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return num; +} + +uint32_t SBProcess::LoadImage(lldb::SBFileSpec &sb_remote_image_spec, + lldb::SBError &sb_error) { + LLDB_INSTRUMENT_VA(this, sb_remote_image_spec, sb_error); + + return LoadImage(SBFileSpec(), sb_remote_image_spec, sb_error); +} + +uint32_t SBProcess::LoadImage(const lldb::SBFileSpec &sb_local_image_spec, + const lldb::SBFileSpec &sb_remote_image_spec, + lldb::SBError &sb_error) { + LLDB_INSTRUMENT_VA(this, sb_local_image_spec, sb_remote_image_spec, sb_error); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); + return platform_sp->LoadImage(process_sp.get(), *sb_local_image_spec, + *sb_remote_image_spec, sb_error.ref()); + } else { + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("process is invalid"); + } + return LLDB_INVALID_IMAGE_TOKEN; +} + +uint32_t SBProcess::LoadImageUsingPaths(const lldb::SBFileSpec &image_spec, + SBStringList &paths, + lldb::SBFileSpec &loaded_path, + lldb::SBError &error) { + LLDB_INSTRUMENT_VA(this, image_spec, paths, loaded_path, error); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); + size_t num_paths = paths.GetSize(); + std::vector<std::string> paths_vec; + paths_vec.reserve(num_paths); + for (size_t i = 0; i < num_paths; i++) + paths_vec.push_back(paths.GetStringAtIndex(i)); + FileSpec loaded_spec; + + uint32_t token = platform_sp->LoadImageUsingPaths( + process_sp.get(), *image_spec, paths_vec, error.ref(), &loaded_spec); + if (token != LLDB_INVALID_IMAGE_TOKEN) + loaded_path = loaded_spec; + return token; + } else { + error.SetErrorString("process is running"); + } + } else { + error.SetErrorString("process is invalid"); + } + + return LLDB_INVALID_IMAGE_TOKEN; +} + +lldb::SBError SBProcess::UnloadImage(uint32_t image_token) { + LLDB_INSTRUMENT_VA(this, image_token); + + lldb::SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); + sb_error.SetError( + platform_sp->UnloadImage(process_sp.get(), image_token)); + } else { + sb_error.SetErrorString("process is running"); + } + } else + sb_error.SetErrorString("invalid process"); + return sb_error; +} + +lldb::SBError SBProcess::SendEventData(const char *event_data) { + LLDB_INSTRUMENT_VA(this, event_data); + + lldb::SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->SendEventData(event_data)); + } else { + sb_error.SetErrorString("process is running"); + } + } else + sb_error.SetErrorString("invalid process"); + return sb_error; +} + +uint32_t SBProcess::GetNumExtendedBacktraceTypes() { + LLDB_INSTRUMENT_VA(this); + + ProcessSP process_sp(GetSP()); + if (process_sp && process_sp->GetSystemRuntime()) { + SystemRuntime *runtime = process_sp->GetSystemRuntime(); + return runtime->GetExtendedBacktraceTypes().size(); + } + return 0; +} + +const char *SBProcess::GetExtendedBacktraceTypeAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + ProcessSP process_sp(GetSP()); + if (process_sp && process_sp->GetSystemRuntime()) { + SystemRuntime *runtime = process_sp->GetSystemRuntime(); + const std::vector<ConstString> &names = + runtime->GetExtendedBacktraceTypes(); + if (idx < names.size()) { + return names[idx].AsCString(); + } + } + return nullptr; +} + +SBThreadCollection SBProcess::GetHistoryThreads(addr_t addr) { + LLDB_INSTRUMENT_VA(this, addr); + + ProcessSP process_sp(GetSP()); + SBThreadCollection threads; + if (process_sp) { + threads = SBThreadCollection(process_sp->GetHistoryThreads(addr)); + } + return threads; +} + +bool SBProcess::IsInstrumentationRuntimePresent( + InstrumentationRuntimeType type) { + LLDB_INSTRUMENT_VA(this, type); + + ProcessSP process_sp(GetSP()); + if (!process_sp) + return false; + + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + + InstrumentationRuntimeSP runtime_sp = + process_sp->GetInstrumentationRuntime(type); + + if (!runtime_sp.get()) + return false; + + return runtime_sp->IsActive(); +} + +lldb::SBError SBProcess::SaveCore(const char *file_name) { + LLDB_INSTRUMENT_VA(this, file_name); + SBSaveCoreOptions options; + options.SetOutputFile(SBFileSpec(file_name)); + options.SetStyle(SaveCoreStyle::eSaveCoreFull); + return SaveCore(options); +} + +lldb::SBError SBProcess::SaveCore(const char *file_name, + const char *flavor, + SaveCoreStyle core_style) { + LLDB_INSTRUMENT_VA(this, file_name, flavor, core_style); + SBSaveCoreOptions options; + options.SetOutputFile(SBFileSpec(file_name)); + options.SetStyle(core_style); + SBError error = options.SetPluginName(flavor); + if (error.Fail()) + return error; + return SaveCore(options); +} + +lldb::SBError SBProcess::SaveCore(SBSaveCoreOptions &options) { + + LLDB_INSTRUMENT_VA(this, options); + + lldb::SBError error; + ProcessSP process_sp(GetSP()); + if (!process_sp) { + error.SetErrorString("SBProcess is invalid"); + return error; + } + + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + + if (process_sp->GetState() != eStateStopped) { + error.SetErrorString("the process is not stopped"); + return error; + } + + error.ref() = PluginManager::SaveCore(process_sp, options.ref()); + + return error; +} + +lldb::SBError +SBProcess::GetMemoryRegionInfo(lldb::addr_t load_addr, + SBMemoryRegionInfo &sb_region_info) { + LLDB_INSTRUMENT_VA(this, load_addr, sb_region_info); + + lldb::SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + + sb_error.ref() = + process_sp->GetMemoryRegionInfo(load_addr, sb_region_info.ref()); + } else { + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return sb_error; +} + +lldb::SBMemoryRegionInfoList SBProcess::GetMemoryRegions() { + LLDB_INSTRUMENT_VA(this); + + lldb::SBMemoryRegionInfoList sb_region_list; + + ProcessSP process_sp(GetSP()); + Process::StopLocker stop_locker; + if (process_sp && stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + + process_sp->GetMemoryRegions(sb_region_list.ref()); + } + + return sb_region_list; +} + +lldb::SBProcessInfo SBProcess::GetProcessInfo() { + LLDB_INSTRUMENT_VA(this); + + lldb::SBProcessInfo sb_proc_info; + ProcessSP process_sp(GetSP()); + ProcessInstanceInfo proc_info; + if (process_sp && process_sp->GetProcessInfo(proc_info)) { + sb_proc_info.SetProcessInfo(proc_info); + } + return sb_proc_info; +} + +lldb::SBFileSpec SBProcess::GetCoreFile() { + LLDB_INSTRUMENT_VA(this); + + ProcessSP process_sp(GetSP()); + FileSpec core_file; + if (process_sp) { + core_file = process_sp->GetCoreFile(); + } + return SBFileSpec(core_file); +} + +addr_t SBProcess::GetAddressMask(AddressMaskType type, + AddressMaskRange addr_range) { + LLDB_INSTRUMENT_VA(this, type, addr_range); + + if (ProcessSP process_sp = GetSP()) { + switch (type) { + case eAddressMaskTypeCode: + if (addr_range == eAddressMaskRangeHigh) + return process_sp->GetHighmemCodeAddressMask(); + else + return process_sp->GetCodeAddressMask(); + case eAddressMaskTypeData: + if (addr_range == eAddressMaskRangeHigh) + return process_sp->GetHighmemDataAddressMask(); + else + return process_sp->GetDataAddressMask(); + case eAddressMaskTypeAny: + if (addr_range == eAddressMaskRangeHigh) + return process_sp->GetHighmemDataAddressMask(); + else + return process_sp->GetDataAddressMask(); + } + } + return LLDB_INVALID_ADDRESS_MASK; +} + +void SBProcess::SetAddressMask(AddressMaskType type, addr_t mask, + AddressMaskRange addr_range) { + LLDB_INSTRUMENT_VA(this, type, mask, addr_range); + + if (ProcessSP process_sp = GetSP()) { + switch (type) { + case eAddressMaskTypeCode: + if (addr_range == eAddressMaskRangeAll) { + process_sp->SetCodeAddressMask(mask); + process_sp->SetHighmemCodeAddressMask(mask); + } else if (addr_range == eAddressMaskRangeHigh) { + process_sp->SetHighmemCodeAddressMask(mask); + } else { + process_sp->SetCodeAddressMask(mask); + } + break; + case eAddressMaskTypeData: + if (addr_range == eAddressMaskRangeAll) { + process_sp->SetDataAddressMask(mask); + process_sp->SetHighmemDataAddressMask(mask); + } else if (addr_range == eAddressMaskRangeHigh) { + process_sp->SetHighmemDataAddressMask(mask); + } else { + process_sp->SetDataAddressMask(mask); + } + break; + case eAddressMaskTypeAll: + if (addr_range == eAddressMaskRangeAll) { + process_sp->SetCodeAddressMask(mask); + process_sp->SetDataAddressMask(mask); + process_sp->SetHighmemCodeAddressMask(mask); + process_sp->SetHighmemDataAddressMask(mask); + } else if (addr_range == eAddressMaskRangeHigh) { + process_sp->SetHighmemCodeAddressMask(mask); + process_sp->SetHighmemDataAddressMask(mask); + } else { + process_sp->SetCodeAddressMask(mask); + process_sp->SetDataAddressMask(mask); + } + break; + } + } +} + +void SBProcess::SetAddressableBits(AddressMaskType type, uint32_t num_bits, + AddressMaskRange addr_range) { + LLDB_INSTRUMENT_VA(this, type, num_bits, addr_range); + + SetAddressMask(type, AddressableBits::AddressableBitToMask(num_bits), + addr_range); +} + +addr_t SBProcess::FixAddress(addr_t addr, AddressMaskType type) { + LLDB_INSTRUMENT_VA(this, addr, type); + + if (ProcessSP process_sp = GetSP()) { + if (type == eAddressMaskTypeAny) + return process_sp->FixAnyAddress(addr); + else if (type == eAddressMaskTypeData) + return process_sp->FixDataAddress(addr); + else if (type == eAddressMaskTypeCode) + return process_sp->FixCodeAddress(addr); + } + return addr; +} + +lldb::addr_t SBProcess::AllocateMemory(size_t size, uint32_t permissions, + lldb::SBError &sb_error) { + LLDB_INSTRUMENT_VA(this, size, permissions, sb_error); + + lldb::addr_t addr = LLDB_INVALID_ADDRESS; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + addr = process_sp->AllocateMemory(size, permissions, sb_error.ref()); + } else { + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return addr; +} + +lldb::SBError SBProcess::DeallocateMemory(lldb::addr_t ptr) { + LLDB_INSTRUMENT_VA(this, ptr); + + lldb::SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard<std::recursive_mutex> guard( + process_sp->GetTarget().GetAPIMutex()); + Status error = process_sp->DeallocateMemory(ptr); + sb_error.SetError(error); + } else { + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return sb_error; +} + +lldb::SBScriptObject SBProcess::GetScriptedImplementation() { + LLDB_INSTRUMENT_VA(this); + ProcessSP process_sp(GetSP()); + return lldb::SBScriptObject((process_sp) ? process_sp->GetImplementation() + : nullptr, + eScriptLanguageDefault); +} diff --git a/contrib/llvm-project/lldb/source/API/SBProcessInfo.cpp b/contrib/llvm-project/lldb/source/API/SBProcessInfo.cpp new file mode 100644 index 000000000000..895fba95afba --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBProcessInfo.cpp @@ -0,0 +1,187 @@ +//===-- SBProcessInfo.cpp -------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBProcessInfo.h" +#include "Utils.h" +#include "lldb/API/SBFileSpec.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/ProcessInfo.h" + +using namespace lldb; +using namespace lldb_private; + +SBProcessInfo::SBProcessInfo() { LLDB_INSTRUMENT_VA(this); } + +SBProcessInfo::SBProcessInfo(const SBProcessInfo &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBProcessInfo::~SBProcessInfo() = default; + +SBProcessInfo &SBProcessInfo::operator=(const SBProcessInfo &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +ProcessInstanceInfo &SBProcessInfo::ref() { + if (m_opaque_up == nullptr) { + m_opaque_up = std::make_unique<ProcessInstanceInfo>(); + } + return *m_opaque_up; +} + +void SBProcessInfo::SetProcessInfo(const ProcessInstanceInfo &proc_info_ref) { + ref() = proc_info_ref; +} + +bool SBProcessInfo::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBProcessInfo::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up != nullptr; +} + +const char *SBProcessInfo::GetName() { + LLDB_INSTRUMENT_VA(this); + + if (!m_opaque_up) + return nullptr; + + return ConstString(m_opaque_up->GetName()).GetCString(); +} + +SBFileSpec SBProcessInfo::GetExecutableFile() { + LLDB_INSTRUMENT_VA(this); + + SBFileSpec file_spec; + if (m_opaque_up) { + file_spec.SetFileSpec(m_opaque_up->GetExecutableFile()); + } + return file_spec; +} + +lldb::pid_t SBProcessInfo::GetProcessID() { + LLDB_INSTRUMENT_VA(this); + + lldb::pid_t proc_id = LLDB_INVALID_PROCESS_ID; + if (m_opaque_up) { + proc_id = m_opaque_up->GetProcessID(); + } + return proc_id; +} + +uint32_t SBProcessInfo::GetUserID() { + LLDB_INSTRUMENT_VA(this); + + uint32_t user_id = UINT32_MAX; + if (m_opaque_up) { + user_id = m_opaque_up->GetUserID(); + } + return user_id; +} + +uint32_t SBProcessInfo::GetGroupID() { + LLDB_INSTRUMENT_VA(this); + + uint32_t group_id = UINT32_MAX; + if (m_opaque_up) { + group_id = m_opaque_up->GetGroupID(); + } + return group_id; +} + +bool SBProcessInfo::UserIDIsValid() { + LLDB_INSTRUMENT_VA(this); + + bool is_valid = false; + if (m_opaque_up) { + is_valid = m_opaque_up->UserIDIsValid(); + } + return is_valid; +} + +bool SBProcessInfo::GroupIDIsValid() { + LLDB_INSTRUMENT_VA(this); + + bool is_valid = false; + if (m_opaque_up) { + is_valid = m_opaque_up->GroupIDIsValid(); + } + return is_valid; +} + +uint32_t SBProcessInfo::GetEffectiveUserID() { + LLDB_INSTRUMENT_VA(this); + + uint32_t user_id = UINT32_MAX; + if (m_opaque_up) { + user_id = m_opaque_up->GetEffectiveUserID(); + } + return user_id; +} + +uint32_t SBProcessInfo::GetEffectiveGroupID() { + LLDB_INSTRUMENT_VA(this); + + uint32_t group_id = UINT32_MAX; + if (m_opaque_up) { + group_id = m_opaque_up->GetEffectiveGroupID(); + } + return group_id; +} + +bool SBProcessInfo::EffectiveUserIDIsValid() { + LLDB_INSTRUMENT_VA(this); + + bool is_valid = false; + if (m_opaque_up) { + is_valid = m_opaque_up->EffectiveUserIDIsValid(); + } + return is_valid; +} + +bool SBProcessInfo::EffectiveGroupIDIsValid() { + LLDB_INSTRUMENT_VA(this); + + bool is_valid = false; + if (m_opaque_up) { + is_valid = m_opaque_up->EffectiveGroupIDIsValid(); + } + return is_valid; +} + +lldb::pid_t SBProcessInfo::GetParentProcessID() { + LLDB_INSTRUMENT_VA(this); + + lldb::pid_t proc_id = LLDB_INVALID_PROCESS_ID; + if (m_opaque_up) { + proc_id = m_opaque_up->GetParentProcessID(); + } + return proc_id; +} + +const char *SBProcessInfo::GetTriple() { + LLDB_INSTRUMENT_VA(this); + + if (!m_opaque_up) + return nullptr; + + const auto &arch = m_opaque_up->GetArchitecture(); + if (!arch.IsValid()) + return nullptr; + + return ConstString(arch.GetTriple().getTriple().c_str()).GetCString(); +} diff --git a/contrib/llvm-project/lldb/source/API/SBProcessInfoList.cpp b/contrib/llvm-project/lldb/source/API/SBProcessInfoList.cpp new file mode 100644 index 000000000000..a711bcb58301 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBProcessInfoList.cpp @@ -0,0 +1,74 @@ +//===-- SBProcessInfoList.cpp ---------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBProcessInfoList.h" +#include "lldb/API/SBProcessInfo.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/ProcessInfo.h" + +#include "Utils.h" + +using namespace lldb; +using namespace lldb_private; + +SBProcessInfoList::SBProcessInfoList() = default; + +SBProcessInfoList::~SBProcessInfoList() = default; + +SBProcessInfoList::SBProcessInfoList(const ProcessInfoList &impl) + : m_opaque_up(std::make_unique<ProcessInfoList>(impl)) { + LLDB_INSTRUMENT_VA(this, impl); +} + +SBProcessInfoList::SBProcessInfoList(const lldb::SBProcessInfoList &rhs) { + + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +const lldb::SBProcessInfoList & +SBProcessInfoList::operator=(const lldb::SBProcessInfoList &rhs) { + + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +uint32_t SBProcessInfoList::GetSize() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + return m_opaque_up->GetSize(); + + return 0; +} + +void SBProcessInfoList::Clear() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + m_opaque_up->Clear(); +} + +bool SBProcessInfoList::GetProcessInfoAtIndex(uint32_t idx, + SBProcessInfo &info) { + LLDB_INSTRUMENT_VA(this, idx, info); + + if (m_opaque_up) { + lldb_private::ProcessInstanceInfo process_instance_info; + if (m_opaque_up->GetProcessInfoAtIndex(idx, process_instance_info)) { + info.SetProcessInfo(process_instance_info); + return true; + } + } + + return false; +} diff --git a/contrib/llvm-project/lldb/source/API/SBQueue.cpp b/contrib/llvm-project/lldb/source/API/SBQueue.cpp new file mode 100644 index 000000000000..968d3b77538c --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBQueue.cpp @@ -0,0 +1,318 @@ +//===-- SBQueue.cpp -------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <cinttypes> + +#include "lldb/API/SBQueue.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBQueueItem.h" +#include "lldb/API/SBThread.h" + +#include "lldb/Target/Process.h" +#include "lldb/Target/Queue.h" +#include "lldb/Target/QueueItem.h" +#include "lldb/Target/Thread.h" + +using namespace lldb; +using namespace lldb_private; + +namespace lldb_private { + +class QueueImpl { +public: + QueueImpl() = default; + + QueueImpl(const lldb::QueueSP &queue_sp) { m_queue_wp = queue_sp; } + + QueueImpl(const QueueImpl &rhs) { + if (&rhs == this) + return; + m_queue_wp = rhs.m_queue_wp; + m_threads = rhs.m_threads; + m_thread_list_fetched = rhs.m_thread_list_fetched; + m_pending_items = rhs.m_pending_items; + m_pending_items_fetched = rhs.m_pending_items_fetched; + } + + ~QueueImpl() = default; + + bool IsValid() { return m_queue_wp.lock() != nullptr; } + + void Clear() { + m_queue_wp.reset(); + m_thread_list_fetched = false; + m_threads.clear(); + m_pending_items_fetched = false; + m_pending_items.clear(); + } + + void SetQueue(const lldb::QueueSP &queue_sp) { + Clear(); + m_queue_wp = queue_sp; + } + + lldb::queue_id_t GetQueueID() const { + lldb::queue_id_t result = LLDB_INVALID_QUEUE_ID; + lldb::QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) { + result = queue_sp->GetID(); + } + return result; + } + + uint32_t GetIndexID() const { + uint32_t result = LLDB_INVALID_INDEX32; + lldb::QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) { + result = queue_sp->GetIndexID(); + } + return result; + } + + const char *GetName() const { + lldb::QueueSP queue_sp = m_queue_wp.lock(); + if (!queue_sp) + return nullptr; + return ConstString(queue_sp->GetName()).GetCString(); + } + + void FetchThreads() { + if (!m_thread_list_fetched) { + lldb::QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&queue_sp->GetProcess()->GetRunLock())) { + const std::vector<ThreadSP> thread_list(queue_sp->GetThreads()); + m_thread_list_fetched = true; + const uint32_t num_threads = thread_list.size(); + for (uint32_t idx = 0; idx < num_threads; ++idx) { + ThreadSP thread_sp = thread_list[idx]; + if (thread_sp && thread_sp->IsValid()) { + m_threads.push_back(thread_sp); + } + } + } + } + } + } + + void FetchItems() { + if (!m_pending_items_fetched) { + QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&queue_sp->GetProcess()->GetRunLock())) { + const std::vector<QueueItemSP> queue_items( + queue_sp->GetPendingItems()); + m_pending_items_fetched = true; + const uint32_t num_pending_items = queue_items.size(); + for (uint32_t idx = 0; idx < num_pending_items; ++idx) { + QueueItemSP item = queue_items[idx]; + if (item && item->IsValid()) { + m_pending_items.push_back(item); + } + } + } + } + } + } + + uint32_t GetNumThreads() { + uint32_t result = 0; + + FetchThreads(); + if (m_thread_list_fetched) { + result = m_threads.size(); + } + return result; + } + + lldb::SBThread GetThreadAtIndex(uint32_t idx) { + FetchThreads(); + + SBThread sb_thread; + QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp && idx < m_threads.size()) { + ProcessSP process_sp = queue_sp->GetProcess(); + if (process_sp) { + ThreadSP thread_sp = m_threads[idx].lock(); + if (thread_sp) { + sb_thread.SetThread(thread_sp); + } + } + } + return sb_thread; + } + + uint32_t GetNumPendingItems() { + uint32_t result = 0; + + QueueSP queue_sp = m_queue_wp.lock(); + if (!m_pending_items_fetched && queue_sp) { + result = queue_sp->GetNumPendingWorkItems(); + } else { + result = m_pending_items.size(); + } + return result; + } + + lldb::SBQueueItem GetPendingItemAtIndex(uint32_t idx) { + SBQueueItem result; + FetchItems(); + if (m_pending_items_fetched && idx < m_pending_items.size()) { + result.SetQueueItem(m_pending_items[idx]); + } + return result; + } + + uint32_t GetNumRunningItems() { + uint32_t result = 0; + QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) + result = queue_sp->GetNumRunningWorkItems(); + return result; + } + + lldb::SBProcess GetProcess() { + SBProcess result; + QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) { + result.SetSP(queue_sp->GetProcess()); + } + return result; + } + + lldb::QueueKind GetKind() { + lldb::QueueKind kind = eQueueKindUnknown; + QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) + kind = queue_sp->GetKind(); + + return kind; + } + +private: + lldb::QueueWP m_queue_wp; + std::vector<lldb::ThreadWP> + m_threads; // threads currently executing this queue's items + bool m_thread_list_fetched = + false; // have we tried to fetch the threads list already? + std::vector<lldb::QueueItemSP> m_pending_items; // items currently enqueued + bool m_pending_items_fetched = + false; // have we tried to fetch the item list already? +}; +} + +SBQueue::SBQueue() : m_opaque_sp(new QueueImpl()) { LLDB_INSTRUMENT_VA(this); } + +SBQueue::SBQueue(const QueueSP &queue_sp) + : m_opaque_sp(new QueueImpl(queue_sp)) { + LLDB_INSTRUMENT_VA(this, queue_sp); +} + +SBQueue::SBQueue(const SBQueue &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (&rhs == this) + return; + + m_opaque_sp = rhs.m_opaque_sp; +} + +const lldb::SBQueue &SBQueue::operator=(const lldb::SBQueue &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_sp = rhs.m_opaque_sp; + return *this; +} + +SBQueue::~SBQueue() = default; + +bool SBQueue::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBQueue::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->IsValid(); +} + +void SBQueue::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_sp->Clear(); +} + +void SBQueue::SetQueue(const QueueSP &queue_sp) { + m_opaque_sp->SetQueue(queue_sp); +} + +lldb::queue_id_t SBQueue::GetQueueID() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetQueueID(); +} + +uint32_t SBQueue::GetIndexID() const { + LLDB_INSTRUMENT_VA(this); + + uint32_t index_id = m_opaque_sp->GetIndexID(); + return index_id; +} + +const char *SBQueue::GetName() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetName(); +} + +uint32_t SBQueue::GetNumThreads() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetNumThreads(); +} + +SBThread SBQueue::GetThreadAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBThread th = m_opaque_sp->GetThreadAtIndex(idx); + return th; +} + +uint32_t SBQueue::GetNumPendingItems() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetNumPendingItems(); +} + +SBQueueItem SBQueue::GetPendingItemAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + return m_opaque_sp->GetPendingItemAtIndex(idx); +} + +uint32_t SBQueue::GetNumRunningItems() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetNumRunningItems(); +} + +SBProcess SBQueue::GetProcess() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetProcess(); +} + +lldb::QueueKind SBQueue::GetKind() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetKind(); +} diff --git a/contrib/llvm-project/lldb/source/API/SBQueueItem.cpp b/contrib/llvm-project/lldb/source/API/SBQueueItem.cpp new file mode 100644 index 000000000000..b2204452c0fa --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBQueueItem.cpp @@ -0,0 +1,112 @@ +//===-- SBQueueItem.cpp ---------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/lldb-forward.h" + +#include "lldb/API/SBAddress.h" +#include "lldb/API/SBQueueItem.h" +#include "lldb/API/SBThread.h" +#include "lldb/Core/Address.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/QueueItem.h" +#include "lldb/Target/Thread.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +// Constructors +SBQueueItem::SBQueueItem() { LLDB_INSTRUMENT_VA(this); } + +SBQueueItem::SBQueueItem(const QueueItemSP &queue_item_sp) + : m_queue_item_sp(queue_item_sp) { + LLDB_INSTRUMENT_VA(this, queue_item_sp); +} + +// Destructor +SBQueueItem::~SBQueueItem() { m_queue_item_sp.reset(); } + +bool SBQueueItem::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBQueueItem::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_queue_item_sp.get() != nullptr; +} + +void SBQueueItem::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_queue_item_sp.reset(); +} + +void SBQueueItem::SetQueueItem(const QueueItemSP &queue_item_sp) { + LLDB_INSTRUMENT_VA(this, queue_item_sp); + + m_queue_item_sp = queue_item_sp; +} + +lldb::QueueItemKind SBQueueItem::GetKind() const { + LLDB_INSTRUMENT_VA(this); + + QueueItemKind result = eQueueItemKindUnknown; + if (m_queue_item_sp) { + result = m_queue_item_sp->GetKind(); + } + return result; +} + +void SBQueueItem::SetKind(lldb::QueueItemKind kind) { + LLDB_INSTRUMENT_VA(this, kind); + + if (m_queue_item_sp) { + m_queue_item_sp->SetKind(kind); + } +} + +SBAddress SBQueueItem::GetAddress() const { + LLDB_INSTRUMENT_VA(this); + + SBAddress result; + if (m_queue_item_sp) { + result.SetAddress(m_queue_item_sp->GetAddress()); + } + return result; +} + +void SBQueueItem::SetAddress(SBAddress addr) { + LLDB_INSTRUMENT_VA(this, addr); + + if (m_queue_item_sp) { + m_queue_item_sp->SetAddress(addr.ref()); + } +} + +SBThread SBQueueItem::GetExtendedBacktraceThread(const char *type) { + LLDB_INSTRUMENT_VA(this, type); + + SBThread result; + if (m_queue_item_sp) { + ProcessSP process_sp = m_queue_item_sp->GetProcessSP(); + Process::StopLocker stop_locker; + if (process_sp && stop_locker.TryLock(&process_sp->GetRunLock())) { + ThreadSP thread_sp; + ConstString type_const(type); + thread_sp = m_queue_item_sp->GetExtendedBacktraceThread(type_const); + if (thread_sp) { + // Save this in the Process' ExtendedThreadList so a strong pointer + // retains the object + process_sp->GetExtendedThreadList().AddThread(thread_sp); + result.SetThread(thread_sp); + } + } + } + return result; +} diff --git a/contrib/llvm-project/lldb/source/API/SBReproducer.cpp b/contrib/llvm-project/lldb/source/API/SBReproducer.cpp new file mode 100644 index 000000000000..088dd25e3f1f --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBReproducer.cpp @@ -0,0 +1,113 @@ +//===-- SBReproducer.cpp --------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBReproducer.h" +#include "lldb/API/LLDB.h" +#include "lldb/API/SBAddress.h" +#include "lldb/API/SBAttachInfo.h" +#include "lldb/API/SBBlock.h" +#include "lldb/API/SBBreakpoint.h" +#include "lldb/API/SBCommandInterpreter.h" +#include "lldb/API/SBCommandInterpreterRunOptions.h" +#include "lldb/API/SBData.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBDeclaration.h" +#include "lldb/API/SBError.h" +#include "lldb/API/SBFileSpec.h" +#include "lldb/API/SBHostOS.h" +#include "lldb/Host/FileSystem.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Version/Version.h" + +using namespace lldb; +using namespace lldb_private; +using namespace lldb_private::repro; + +SBReplayOptions::SBReplayOptions() {} + +SBReplayOptions::SBReplayOptions(const SBReplayOptions &rhs) {} + +SBReplayOptions::~SBReplayOptions() = default; + +SBReplayOptions &SBReplayOptions::operator=(const SBReplayOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs) + return *this; +} + +void SBReplayOptions::SetVerify(bool verify) { + LLDB_INSTRUMENT_VA(this, verify); +} + +bool SBReplayOptions::GetVerify() const { + LLDB_INSTRUMENT_VA(this); + return false; +} + +void SBReplayOptions::SetCheckVersion(bool check) { + LLDB_INSTRUMENT_VA(this, check); +} + +bool SBReplayOptions::GetCheckVersion() const { + LLDB_INSTRUMENT_VA(this); + return false; +} + +const char *SBReproducer::Capture() { + LLDB_INSTRUMENT() + return "Reproducer capture has been removed"; +} + +const char *SBReproducer::Capture(const char *path) { + LLDB_INSTRUMENT_VA(path) + return "Reproducer capture has been removed"; +} + +const char *SBReproducer::PassiveReplay(const char *path) { + LLDB_INSTRUMENT_VA(path) + return "Reproducer replay has been removed"; +} + +const char *SBReproducer::Replay(const char *path) { + LLDB_INSTRUMENT_VA(path) + return "Reproducer replay has been removed"; +} + +const char *SBReproducer::Replay(const char *path, bool skip_version_check) { + LLDB_INSTRUMENT_VA(path, skip_version_check) + return "Reproducer replay has been removed"; +} + +const char *SBReproducer::Replay(const char *path, + const SBReplayOptions &options) { + LLDB_INSTRUMENT_VA(path, options) + return "Reproducer replay has been removed"; +} + +const char *SBReproducer::Finalize(const char *path) { + LLDB_INSTRUMENT_VA(path) + return "Reproducer finalize has been removed"; +} + +bool SBReproducer::Generate() { + LLDB_INSTRUMENT() + return false; +} + +bool SBReproducer::SetAutoGenerate(bool b) { + LLDB_INSTRUMENT_VA(b) + return false; +} + +const char *SBReproducer::GetPath() { + LLDB_INSTRUMENT() + return "Reproducer GetPath has been removed"; +} + +void SBReproducer::SetWorkingDirectory(const char *path) { + LLDB_INSTRUMENT_VA(path) +} diff --git a/contrib/llvm-project/lldb/source/API/SBSaveCoreOptions.cpp b/contrib/llvm-project/lldb/source/API/SBSaveCoreOptions.cpp new file mode 100644 index 000000000000..19ca83f932bc --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBSaveCoreOptions.cpp @@ -0,0 +1,87 @@ +//===-- SBSaveCoreOptions.cpp -----------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBSaveCoreOptions.h" +#include "lldb/API/SBError.h" +#include "lldb/API/SBFileSpec.h" +#include "lldb/Host/FileSystem.h" +#include "lldb/Symbol/SaveCoreOptions.h" +#include "lldb/Utility/Instrumentation.h" + +#include "Utils.h" + +using namespace lldb; + +SBSaveCoreOptions::SBSaveCoreOptions() { + LLDB_INSTRUMENT_VA(this) + + m_opaque_up = std::make_unique<lldb_private::SaveCoreOptions>(); +} + +SBSaveCoreOptions::SBSaveCoreOptions(const SBSaveCoreOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBSaveCoreOptions::~SBSaveCoreOptions() = default; + +const SBSaveCoreOptions & +SBSaveCoreOptions::operator=(const SBSaveCoreOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +SBError SBSaveCoreOptions::SetPluginName(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + lldb_private::Status error = m_opaque_up->SetPluginName(name); + return SBError(error); +} + +void SBSaveCoreOptions::SetStyle(lldb::SaveCoreStyle style) { + LLDB_INSTRUMENT_VA(this, style); + m_opaque_up->SetStyle(style); +} + +void SBSaveCoreOptions::SetOutputFile(lldb::SBFileSpec file_spec) { + LLDB_INSTRUMENT_VA(this, file_spec); + m_opaque_up->SetOutputFile(file_spec.ref()); +} + +const char *SBSaveCoreOptions::GetPluginName() const { + LLDB_INSTRUMENT_VA(this); + const auto name = m_opaque_up->GetPluginName(); + if (!name) + return nullptr; + return lldb_private::ConstString(name.value()).GetCString(); +} + +SBFileSpec SBSaveCoreOptions::GetOutputFile() const { + LLDB_INSTRUMENT_VA(this); + const auto file_spec = m_opaque_up->GetOutputFile(); + if (file_spec) + return SBFileSpec(file_spec.value()); + return SBFileSpec(); +} + +lldb::SaveCoreStyle SBSaveCoreOptions::GetStyle() const { + LLDB_INSTRUMENT_VA(this); + return m_opaque_up->GetStyle(); +} + +void SBSaveCoreOptions::Clear() { + LLDB_INSTRUMENT_VA(this); + m_opaque_up->Clear(); +} + +lldb_private::SaveCoreOptions &SBSaveCoreOptions::ref() const { + return *m_opaque_up.get(); +} diff --git a/contrib/llvm-project/lldb/source/API/SBScriptObject.cpp b/contrib/llvm-project/lldb/source/API/SBScriptObject.cpp new file mode 100644 index 000000000000..3e067d0ab1ee --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBScriptObject.cpp @@ -0,0 +1,84 @@ +//===-- SBScriptObject.cpp ------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBScriptObject.h" + +#include "Utils.h" + +#include "lldb/Interpreter/ScriptObject.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +SBScriptObject::SBScriptObject(const ScriptObjectPtr ptr, + lldb::ScriptLanguage lang) + : m_opaque_up(std::make_unique<lldb_private::ScriptObject>(ptr, lang)) { + LLDB_INSTRUMENT_VA(this, ptr, lang); +} + +SBScriptObject::SBScriptObject(const SBScriptObject &rhs) + : m_opaque_up(new ScriptObject(nullptr, eScriptLanguageNone)) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} +SBScriptObject::~SBScriptObject() = default; + +const SBScriptObject &SBScriptObject::operator=(const SBScriptObject &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +bool SBScriptObject::operator!=(const SBScriptObject &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return !(m_opaque_up == rhs.m_opaque_up); +} + +bool SBScriptObject::IsValid() const { + LLDB_INSTRUMENT_VA(this); + + return this->operator bool(); +} + +SBScriptObject::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up != nullptr && m_opaque_up->operator bool(); +} + +lldb::ScriptObjectPtr SBScriptObject::GetPointer() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up ? const_cast<void *>(m_opaque_up->GetPointer()) : nullptr; +} + +lldb::ScriptLanguage SBScriptObject::GetLanguage() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up ? m_opaque_up->GetLanguage() : eScriptLanguageNone; +} + +ScriptObject &SBScriptObject::ref() { + if (m_opaque_up == nullptr) + m_opaque_up = std::make_unique<ScriptObject>(nullptr, eScriptLanguageNone); + return *m_opaque_up; +} + +const ScriptObject &SBScriptObject::ref() const { + // This object should already have checked with "IsValid()" prior to calling + // this function. In case you didn't we will assert and die to let you know. + assert(m_opaque_up.get()); + return *m_opaque_up; +} + +ScriptObject *SBScriptObject::get() { return m_opaque_up.get(); } diff --git a/contrib/llvm-project/lldb/source/API/SBSection.cpp b/contrib/llvm-project/lldb/source/API/SBSection.cpp new file mode 100644 index 000000000000..b7b94f3ece1a --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBSection.cpp @@ -0,0 +1,263 @@ +//===-- SBSection.cpp -----------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBSection.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBTarget.h" +#include "lldb/Core/Module.h" +#include "lldb/Core/Section.h" +#include "lldb/Symbol/ObjectFile.h" +#include "lldb/Utility/DataBuffer.h" +#include "lldb/Utility/DataExtractor.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/StreamString.h" + +using namespace lldb; +using namespace lldb_private; + +SBSection::SBSection() { LLDB_INSTRUMENT_VA(this); } + +SBSection::SBSection(const SBSection &rhs) : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBSection::SBSection(const lldb::SectionSP §ion_sp) { + // Don't init with section_sp otherwise this will throw if + // section_sp doesn't contain a valid Section * + if (section_sp) + m_opaque_wp = section_sp; +} + +const SBSection &SBSection::operator=(const SBSection &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_wp = rhs.m_opaque_wp; + return *this; +} + +SBSection::~SBSection() = default; + +bool SBSection::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBSection::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + SectionSP section_sp(GetSP()); + return section_sp && section_sp->GetModule().get() != nullptr; +} + +const char *SBSection::GetName() { + LLDB_INSTRUMENT_VA(this); + + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetName().GetCString(); + return nullptr; +} + +lldb::SBSection SBSection::GetParent() { + LLDB_INSTRUMENT_VA(this); + + lldb::SBSection sb_section; + SectionSP section_sp(GetSP()); + if (section_sp) { + SectionSP parent_section_sp(section_sp->GetParent()); + if (parent_section_sp) + sb_section.SetSP(parent_section_sp); + } + return sb_section; +} + +lldb::SBSection SBSection::FindSubSection(const char *sect_name) { + LLDB_INSTRUMENT_VA(this, sect_name); + + lldb::SBSection sb_section; + if (sect_name) { + SectionSP section_sp(GetSP()); + if (section_sp) { + ConstString const_sect_name(sect_name); + sb_section.SetSP( + section_sp->GetChildren().FindSectionByName(const_sect_name)); + } + } + return sb_section; +} + +size_t SBSection::GetNumSubSections() { + LLDB_INSTRUMENT_VA(this); + + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetChildren().GetSize(); + return 0; +} + +lldb::SBSection SBSection::GetSubSectionAtIndex(size_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + lldb::SBSection sb_section; + SectionSP section_sp(GetSP()); + if (section_sp) + sb_section.SetSP(section_sp->GetChildren().GetSectionAtIndex(idx)); + return sb_section; +} + +lldb::SectionSP SBSection::GetSP() const { return m_opaque_wp.lock(); } + +void SBSection::SetSP(const lldb::SectionSP §ion_sp) { + m_opaque_wp = section_sp; +} + +lldb::addr_t SBSection::GetFileAddress() { + LLDB_INSTRUMENT_VA(this); + + lldb::addr_t file_addr = LLDB_INVALID_ADDRESS; + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetFileAddress(); + return file_addr; +} + +lldb::addr_t SBSection::GetLoadAddress(lldb::SBTarget &sb_target) { + LLDB_INSTRUMENT_VA(this, sb_target); + + TargetSP target_sp(sb_target.GetSP()); + if (target_sp) { + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetLoadBaseAddress(target_sp.get()); + } + return LLDB_INVALID_ADDRESS; +} + +lldb::addr_t SBSection::GetByteSize() { + LLDB_INSTRUMENT_VA(this); + + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetByteSize(); + return 0; +} + +uint64_t SBSection::GetFileOffset() { + LLDB_INSTRUMENT_VA(this); + + SectionSP section_sp(GetSP()); + if (section_sp) { + ModuleSP module_sp(section_sp->GetModule()); + if (module_sp) { + ObjectFile *objfile = module_sp->GetObjectFile(); + if (objfile) + return objfile->GetFileOffset() + section_sp->GetFileOffset(); + } + } + return UINT64_MAX; +} + +uint64_t SBSection::GetFileByteSize() { + LLDB_INSTRUMENT_VA(this); + + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetFileSize(); + return 0; +} + +SBData SBSection::GetSectionData() { + LLDB_INSTRUMENT_VA(this); + + return GetSectionData(0, UINT64_MAX); +} + +SBData SBSection::GetSectionData(uint64_t offset, uint64_t size) { + LLDB_INSTRUMENT_VA(this, offset, size); + + SBData sb_data; + SectionSP section_sp(GetSP()); + if (section_sp) { + DataExtractor section_data; + section_sp->GetSectionData(section_data); + sb_data.SetOpaque( + std::make_shared<DataExtractor>(section_data, offset, size)); + } + return sb_data; +} + +SectionType SBSection::GetSectionType() { + LLDB_INSTRUMENT_VA(this); + + SectionSP section_sp(GetSP()); + if (section_sp.get()) + return section_sp->GetType(); + return eSectionTypeInvalid; +} + +uint32_t SBSection::GetPermissions() const { + LLDB_INSTRUMENT_VA(this); + + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetPermissions(); + return 0; +} + +uint32_t SBSection::GetTargetByteSize() { + LLDB_INSTRUMENT_VA(this); + + SectionSP section_sp(GetSP()); + if (section_sp.get()) + return section_sp->GetTargetByteSize(); + return 0; +} + +uint32_t SBSection::GetAlignment() { + LLDB_INSTRUMENT_VA(this); + + SectionSP section_sp(GetSP()); + if (section_sp.get()) + return (1 << section_sp->GetLog2Align()); + return 0; +} + +bool SBSection::operator==(const SBSection &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + SectionSP lhs_section_sp(GetSP()); + SectionSP rhs_section_sp(rhs.GetSP()); + if (lhs_section_sp && rhs_section_sp) + return lhs_section_sp == rhs_section_sp; + return false; +} + +bool SBSection::operator!=(const SBSection &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + SectionSP lhs_section_sp(GetSP()); + SectionSP rhs_section_sp(rhs.GetSP()); + return lhs_section_sp != rhs_section_sp; +} + +bool SBSection::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + SectionSP section_sp(GetSP()); + if (section_sp) { + const addr_t file_addr = section_sp->GetFileAddress(); + strm.Printf("[0x%16.16" PRIx64 "-0x%16.16" PRIx64 ") ", file_addr, + file_addr + section_sp->GetByteSize()); + section_sp->DumpName(strm.AsRawOstream()); + } else { + strm.PutCString("No value"); + } + + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBSourceManager.cpp b/contrib/llvm-project/lldb/source/API/SBSourceManager.cpp new file mode 100644 index 000000000000..e46f990698d8 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBSourceManager.cpp @@ -0,0 +1,128 @@ +//===-- SBSourceManager.cpp -----------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBSourceManager.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBTarget.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBFileSpec.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Core/SourceManager.h" +#include "lldb/Utility/Stream.h" + +#include "lldb/Target/Target.h" + +namespace lldb_private { +class SourceManagerImpl { +public: + SourceManagerImpl(const lldb::DebuggerSP &debugger_sp) + : m_debugger_wp(debugger_sp) {} + + SourceManagerImpl(const lldb::TargetSP &target_sp) : m_target_wp(target_sp) {} + + SourceManagerImpl(const SourceManagerImpl &rhs) { + if (&rhs == this) + return; + m_debugger_wp = rhs.m_debugger_wp; + m_target_wp = rhs.m_target_wp; + } + + size_t DisplaySourceLinesWithLineNumbers(const lldb_private::FileSpec &file, + uint32_t line, uint32_t column, + uint32_t context_before, + uint32_t context_after, + const char *current_line_cstr, + lldb_private::Stream *s) { + if (!file) + return 0; + + lldb::TargetSP target_sp(m_target_wp.lock()); + if (target_sp) { + return target_sp->GetSourceManager().DisplaySourceLinesWithLineNumbers( + file, line, column, context_before, context_after, current_line_cstr, + s); + } else { + lldb::DebuggerSP debugger_sp(m_debugger_wp.lock()); + if (debugger_sp) { + return debugger_sp->GetSourceManager() + .DisplaySourceLinesWithLineNumbers(file, line, column, + context_before, context_after, + current_line_cstr, s); + } + } + return 0; + } + +private: + lldb::DebuggerWP m_debugger_wp; + lldb::TargetWP m_target_wp; +}; +} + +using namespace lldb; +using namespace lldb_private; + +SBSourceManager::SBSourceManager(const SBDebugger &debugger) { + LLDB_INSTRUMENT_VA(this, debugger); + + m_opaque_up = std::make_unique<SourceManagerImpl>(debugger.get_sp()); +} + +SBSourceManager::SBSourceManager(const SBTarget &target) { + LLDB_INSTRUMENT_VA(this, target); + + m_opaque_up = std::make_unique<SourceManagerImpl>(target.GetSP()); +} + +SBSourceManager::SBSourceManager(const SBSourceManager &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (&rhs == this) + return; + + m_opaque_up = std::make_unique<SourceManagerImpl>(*rhs.m_opaque_up); +} + +const lldb::SBSourceManager &SBSourceManager:: +operator=(const lldb::SBSourceManager &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = std::make_unique<SourceManagerImpl>(*rhs.m_opaque_up); + return *this; +} + +SBSourceManager::~SBSourceManager() = default; + +size_t SBSourceManager::DisplaySourceLinesWithLineNumbers( + const SBFileSpec &file, uint32_t line, uint32_t context_before, + uint32_t context_after, const char *current_line_cstr, SBStream &s) { + LLDB_INSTRUMENT_VA(this, file, line, context_before, context_after, + current_line_cstr, s); + + const uint32_t column = 0; + return DisplaySourceLinesWithLineNumbersAndColumn( + file.ref(), line, column, context_before, context_after, + current_line_cstr, s); +} + +size_t SBSourceManager::DisplaySourceLinesWithLineNumbersAndColumn( + const SBFileSpec &file, uint32_t line, uint32_t column, + uint32_t context_before, uint32_t context_after, + const char *current_line_cstr, SBStream &s) { + LLDB_INSTRUMENT_VA(this, file, line, column, context_before, context_after, + current_line_cstr, s); + + if (m_opaque_up == nullptr) + return 0; + + return m_opaque_up->DisplaySourceLinesWithLineNumbers( + file.ref(), line, column, context_before, context_after, + current_line_cstr, s.get()); +} diff --git a/contrib/llvm-project/lldb/source/API/SBStatisticsOptions.cpp b/contrib/llvm-project/lldb/source/API/SBStatisticsOptions.cpp new file mode 100644 index 000000000000..71d4048573b5 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBStatisticsOptions.cpp @@ -0,0 +1,82 @@ +//===-- SBStatisticsOptions.cpp -------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBStatisticsOptions.h" +#include "lldb/Target/Statistics.h" +#include "lldb/Utility/Instrumentation.h" + +#include "Utils.h" + +using namespace lldb; +using namespace lldb_private; + +SBStatisticsOptions::SBStatisticsOptions() + : m_opaque_up(new StatisticsOptions()) { + LLDB_INSTRUMENT_VA(this); +} + +SBStatisticsOptions::SBStatisticsOptions(const SBStatisticsOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBStatisticsOptions::~SBStatisticsOptions() = default; + +const SBStatisticsOptions & +SBStatisticsOptions::operator=(const SBStatisticsOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +void SBStatisticsOptions::SetSummaryOnly(bool b) { + m_opaque_up->SetSummaryOnly(b); +} + +bool SBStatisticsOptions::GetSummaryOnly() { + return m_opaque_up->GetSummaryOnly(); +} + +void SBStatisticsOptions::SetIncludeTargets(bool b) { + m_opaque_up->SetIncludeTargets(b); +} + +bool SBStatisticsOptions::GetIncludeTargets() const { + return m_opaque_up->GetIncludeTargets(); +} + +void SBStatisticsOptions::SetIncludeModules(bool b) { + m_opaque_up->SetIncludeModules(b); +} + +bool SBStatisticsOptions::GetIncludeModules() const { + return m_opaque_up->GetIncludeModules(); +} + +void SBStatisticsOptions::SetIncludeTranscript(bool b) { + m_opaque_up->SetIncludeTranscript(b); +} + +bool SBStatisticsOptions::GetIncludeTranscript() const { + return m_opaque_up->GetIncludeTranscript(); +} + +void SBStatisticsOptions::SetReportAllAvailableDebugInfo(bool b) { + m_opaque_up->SetLoadAllDebugInfo(b); +} + +bool SBStatisticsOptions::GetReportAllAvailableDebugInfo() { + return m_opaque_up->GetLoadAllDebugInfo(); +} + +const lldb_private::StatisticsOptions &SBStatisticsOptions::ref() const { + return *m_opaque_up; +} diff --git a/contrib/llvm-project/lldb/source/API/SBStream.cpp b/contrib/llvm-project/lldb/source/API/SBStream.cpp new file mode 100644 index 000000000000..fc8f09a7bb9a --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBStream.cpp @@ -0,0 +1,194 @@ +//===-- SBStream.cpp ------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBStream.h" + +#include "lldb/API/SBFile.h" +#include "lldb/Host/FileSystem.h" +#include "lldb/Host/StreamFile.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/LLDBLog.h" +#include "lldb/Utility/Status.h" +#include "lldb/Utility/Stream.h" +#include "lldb/Utility/StreamString.h" + +using namespace lldb; +using namespace lldb_private; + +SBStream::SBStream() : m_opaque_up(new StreamString()) { + LLDB_INSTRUMENT_VA(this); +} + +SBStream::SBStream(SBStream &&rhs) + : m_opaque_up(std::move(rhs.m_opaque_up)), m_is_file(rhs.m_is_file) {} + +SBStream::~SBStream() = default; + +bool SBStream::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBStream::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_up != nullptr); +} + +// If this stream is not redirected to a file, it will maintain a local cache +// for the stream data which can be accessed using this accessor. +const char *SBStream::GetData() { + LLDB_INSTRUMENT_VA(this); + + if (m_is_file || m_opaque_up == nullptr) + return nullptr; + + return ConstString(static_cast<StreamString *>(m_opaque_up.get())->GetData()) + .GetCString(); +} + +// If this stream is not redirected to a file, it will maintain a local cache +// for the stream output whose length can be accessed using this accessor. +size_t SBStream::GetSize() { + LLDB_INSTRUMENT_VA(this); + + if (m_is_file || m_opaque_up == nullptr) + return 0; + + return static_cast<StreamString *>(m_opaque_up.get())->GetSize(); +} + +void SBStream::Print(const char *str) { + LLDB_INSTRUMENT_VA(this, str); + + Printf("%s", str); +} + +void SBStream::Printf(const char *format, ...) { + if (!format) + return; + va_list args; + va_start(args, format); + ref().PrintfVarArg(format, args); + va_end(args); +} + +void SBStream::RedirectToFile(const char *path, bool append) { + LLDB_INSTRUMENT_VA(this, path, append); + + if (path == nullptr) + return; + + std::string local_data; + if (m_opaque_up) { + // See if we have any locally backed data. If so, copy it so we can then + // redirect it to the file so we don't lose the data + if (!m_is_file) + local_data = std::string( + static_cast<StreamString *>(m_opaque_up.get())->GetString()); + } + auto open_options = File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate; + if (append) + open_options |= File::eOpenOptionAppend; + else + open_options |= File::eOpenOptionTruncate; + + llvm::Expected<FileUP> file = + FileSystem::Instance().Open(FileSpec(path), open_options); + if (!file) { + LLDB_LOG_ERROR(GetLog(LLDBLog::API), file.takeError(), + "Cannot open {1}: {0}", path); + return; + } + + m_opaque_up = std::make_unique<StreamFile>(std::move(file.get())); + m_is_file = true; + + // If we had any data locally in our StreamString, then pass that along to + // the to new file we are redirecting to. + if (!local_data.empty()) + m_opaque_up->Write(&local_data[0], local_data.size()); +} + +void SBStream::RedirectToFileHandle(FILE *fh, bool transfer_fh_ownership) { + LLDB_INSTRUMENT_VA(this, fh, transfer_fh_ownership); + FileSP file = std::make_unique<NativeFile>(fh, transfer_fh_ownership); + return RedirectToFile(file); +} + +void SBStream::RedirectToFile(SBFile file) { + LLDB_INSTRUMENT_VA(this, file) + RedirectToFile(file.GetFile()); +} + +void SBStream::RedirectToFile(FileSP file_sp) { + LLDB_INSTRUMENT_VA(this, file_sp); + + if (!file_sp || !file_sp->IsValid()) + return; + + std::string local_data; + if (m_opaque_up) { + // See if we have any locally backed data. If so, copy it so we can then + // redirect it to the file so we don't lose the data + if (!m_is_file) + local_data = std::string( + static_cast<StreamString *>(m_opaque_up.get())->GetString()); + } + + m_opaque_up = std::make_unique<StreamFile>(file_sp); + m_is_file = true; + + // If we had any data locally in our StreamString, then pass that along to + // the to new file we are redirecting to. + if (!local_data.empty()) + m_opaque_up->Write(&local_data[0], local_data.size()); +} + +void SBStream::RedirectToFileDescriptor(int fd, bool transfer_fh_ownership) { + LLDB_INSTRUMENT_VA(this, fd, transfer_fh_ownership); + + std::string local_data; + if (m_opaque_up) { + // See if we have any locally backed data. If so, copy it so we can then + // redirect it to the file so we don't lose the data + if (!m_is_file) + local_data = std::string( + static_cast<StreamString *>(m_opaque_up.get())->GetString()); + } + + m_opaque_up = std::make_unique<StreamFile>(fd, transfer_fh_ownership); + m_is_file = true; + + // If we had any data locally in our StreamString, then pass that along to + // the to new file we are redirecting to. + if (!local_data.empty()) + m_opaque_up->Write(&local_data[0], local_data.size()); +} + +lldb_private::Stream *SBStream::operator->() { return m_opaque_up.get(); } + +lldb_private::Stream *SBStream::get() { return m_opaque_up.get(); } + +lldb_private::Stream &SBStream::ref() { + if (m_opaque_up == nullptr) + m_opaque_up = std::make_unique<StreamString>(); + return *m_opaque_up; +} + +void SBStream::Clear() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) { + // See if we have any locally backed data. If so, copy it so we can then + // redirect it to the file so we don't lose the data + if (m_is_file) + m_opaque_up.reset(); + else + static_cast<StreamString *>(m_opaque_up.get())->Clear(); + } +} diff --git a/contrib/llvm-project/lldb/source/API/SBStringList.cpp b/contrib/llvm-project/lldb/source/API/SBStringList.cpp new file mode 100644 index 000000000000..350c58b61634 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBStringList.cpp @@ -0,0 +1,136 @@ +//===-- SBStringList.cpp --------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBStringList.h" +#include "Utils.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/StringList.h" + +using namespace lldb; +using namespace lldb_private; + +SBStringList::SBStringList() { LLDB_INSTRUMENT_VA(this); } + +SBStringList::SBStringList(const lldb_private::StringList *lldb_strings_ptr) { + if (lldb_strings_ptr) + m_opaque_up = std::make_unique<StringList>(*lldb_strings_ptr); +} + +SBStringList::SBStringList(const SBStringList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +const SBStringList &SBStringList::operator=(const SBStringList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +SBStringList::~SBStringList() = default; + +lldb_private::StringList *SBStringList::operator->() { + if (!IsValid()) + m_opaque_up = std::make_unique<lldb_private::StringList>(); + + return m_opaque_up.get(); +} + +const lldb_private::StringList *SBStringList::operator->() const { + return m_opaque_up.get(); +} + +const lldb_private::StringList &SBStringList::operator*() const { + return *m_opaque_up; +} + +bool SBStringList::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBStringList::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_up != nullptr); +} + +void SBStringList::AppendString(const char *str) { + LLDB_INSTRUMENT_VA(this, str); + + if (str != nullptr) { + if (IsValid()) + m_opaque_up->AppendString(str); + else + m_opaque_up = std::make_unique<lldb_private::StringList>(str); + } +} + +void SBStringList::AppendList(const char **strv, int strc) { + LLDB_INSTRUMENT_VA(this, strv, strc); + + if ((strv != nullptr) && (strc > 0)) { + if (IsValid()) + m_opaque_up->AppendList(strv, strc); + else + m_opaque_up = std::make_unique<lldb_private::StringList>(strv, strc); + } +} + +void SBStringList::AppendList(const SBStringList &strings) { + LLDB_INSTRUMENT_VA(this, strings); + + if (strings.IsValid()) { + if (!IsValid()) + m_opaque_up = std::make_unique<lldb_private::StringList>(); + m_opaque_up->AppendList(*(strings.m_opaque_up)); + } +} + +void SBStringList::AppendList(const StringList &strings) { + if (!IsValid()) + m_opaque_up = std::make_unique<lldb_private::StringList>(); + m_opaque_up->AppendList(strings); +} + +uint32_t SBStringList::GetSize() const { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) { + return m_opaque_up->GetSize(); + } + return 0; +} + +const char *SBStringList::GetStringAtIndex(size_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + if (IsValid()) { + return ConstString(m_opaque_up->GetStringAtIndex(idx)).GetCString(); + } + return nullptr; +} + +const char *SBStringList::GetStringAtIndex(size_t idx) const { + LLDB_INSTRUMENT_VA(this, idx); + + if (IsValid()) { + return ConstString(m_opaque_up->GetStringAtIndex(idx)).GetCString(); + } + return nullptr; +} + +void SBStringList::Clear() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) { + m_opaque_up->Clear(); + } +} diff --git a/contrib/llvm-project/lldb/source/API/SBStructuredData.cpp b/contrib/llvm-project/lldb/source/API/SBStructuredData.cpp new file mode 100644 index 000000000000..b18fc5655fc8 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBStructuredData.cpp @@ -0,0 +1,229 @@ +//===-- SBStructuredData.cpp ----------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBStructuredData.h" + +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBScriptObject.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStringList.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Core/StructuredDataImpl.h" +#include "lldb/Interpreter/ScriptInterpreter.h" +#include "lldb/Target/StructuredDataPlugin.h" +#include "lldb/Utility/Event.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Status.h" +#include "lldb/Utility/Stream.h" +#include "lldb/Utility/StringList.h" +#include "lldb/Utility/StructuredData.h" + +using namespace lldb; +using namespace lldb_private; + +#pragma mark-- +#pragma mark SBStructuredData + +SBStructuredData::SBStructuredData() : m_impl_up(new StructuredDataImpl()) { + LLDB_INSTRUMENT_VA(this); +} + +SBStructuredData::SBStructuredData(const lldb::SBStructuredData &rhs) + : m_impl_up(new StructuredDataImpl(*rhs.m_impl_up)) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBStructuredData::SBStructuredData(const lldb::SBScriptObject obj, + const lldb::SBDebugger &debugger) { + LLDB_INSTRUMENT_VA(this, obj, debugger); + + if (!obj.IsValid()) + return; + + ScriptInterpreter *interpreter = + debugger.m_opaque_sp->GetScriptInterpreter(true, obj.GetLanguage()); + + if (!interpreter) + return; + + StructuredDataImplUP impl_up = std::make_unique<StructuredDataImpl>( + interpreter->CreateStructuredDataFromScriptObject(obj.ref())); + if (impl_up && impl_up->IsValid()) + m_impl_up.reset(impl_up.release()); +} + +SBStructuredData::SBStructuredData(const lldb::EventSP &event_sp) + : m_impl_up(new StructuredDataImpl(event_sp)) { + LLDB_INSTRUMENT_VA(this, event_sp); +} + +SBStructuredData::SBStructuredData(const lldb_private::StructuredDataImpl &impl) + : m_impl_up(new StructuredDataImpl(impl)) { + LLDB_INSTRUMENT_VA(this, impl); +} + +SBStructuredData::~SBStructuredData() = default; + +SBStructuredData &SBStructuredData:: +operator=(const lldb::SBStructuredData &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + *m_impl_up = *rhs.m_impl_up; + return *this; +} + +lldb::SBError SBStructuredData::SetFromJSON(lldb::SBStream &stream) { + LLDB_INSTRUMENT_VA(this, stream); + + lldb::SBError error; + + StructuredData::ObjectSP json_obj = + StructuredData::ParseJSON(stream.GetData()); + m_impl_up->SetObjectSP(json_obj); + + if (!json_obj || json_obj->GetType() != eStructuredDataTypeDictionary) + error.SetErrorString("Invalid Syntax"); + return error; +} + +lldb::SBError SBStructuredData::SetFromJSON(const char *json) { + LLDB_INSTRUMENT_VA(this, json); + lldb::SBStream s; + s.Print(json); + return SetFromJSON(s); +} + +bool SBStructuredData::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} + +SBStructuredData::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_impl_up->IsValid(); +} + +void SBStructuredData::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_impl_up->Clear(); +} + +SBError SBStructuredData::GetAsJSON(lldb::SBStream &stream) const { + LLDB_INSTRUMENT_VA(this, stream); + + SBError error; + error.SetError(m_impl_up->GetAsJSON(stream.ref())); + return error; +} + +lldb::SBError SBStructuredData::GetDescription(lldb::SBStream &stream) const { + LLDB_INSTRUMENT_VA(this, stream); + + Status error = m_impl_up->GetDescription(stream.ref()); + SBError sb_error; + sb_error.SetError(error); + return sb_error; +} + +StructuredDataType SBStructuredData::GetType() const { + LLDB_INSTRUMENT_VA(this); + + return m_impl_up->GetType(); +} + +size_t SBStructuredData::GetSize() const { + LLDB_INSTRUMENT_VA(this); + + return m_impl_up->GetSize(); +} + +bool SBStructuredData::GetKeys(lldb::SBStringList &keys) const { + LLDB_INSTRUMENT_VA(this, keys); + + if (GetType() != eStructuredDataTypeDictionary) + return false; + + StructuredData::ObjectSP obj_sp = m_impl_up->GetObjectSP(); + if (!obj_sp) + return false; + + StructuredData::Dictionary *dict = obj_sp->GetAsDictionary(); + // We claimed we were a dictionary, so this can't be null. + assert(dict); + // The return kind of GetKeys is an Array: + StructuredData::ObjectSP array_sp = dict->GetKeys(); + StructuredData::Array *key_arr = array_sp->GetAsArray(); + assert(key_arr); + + key_arr->ForEach([&keys](StructuredData::Object *object) -> bool { + llvm::StringRef key = object->GetStringValue(""); + keys->AppendString(key); + return true; + }); + return true; +} + +lldb::SBStructuredData SBStructuredData::GetValueForKey(const char *key) const { + LLDB_INSTRUMENT_VA(this, key); + + SBStructuredData result; + result.m_impl_up->SetObjectSP(m_impl_up->GetValueForKey(key)); + return result; +} + +lldb::SBStructuredData SBStructuredData::GetItemAtIndex(size_t idx) const { + LLDB_INSTRUMENT_VA(this, idx); + + SBStructuredData result; + result.m_impl_up->SetObjectSP(m_impl_up->GetItemAtIndex(idx)); + return result; +} + +uint64_t SBStructuredData::GetIntegerValue(uint64_t fail_value) const { + LLDB_INSTRUMENT_VA(this, fail_value); + + return GetUnsignedIntegerValue(fail_value); +} + +uint64_t SBStructuredData::GetUnsignedIntegerValue(uint64_t fail_value) const { + LLDB_INSTRUMENT_VA(this, fail_value); + + return m_impl_up->GetIntegerValue(fail_value); +} + +int64_t SBStructuredData::GetSignedIntegerValue(int64_t fail_value) const { + LLDB_INSTRUMENT_VA(this, fail_value); + + return m_impl_up->GetIntegerValue(fail_value); +} + +double SBStructuredData::GetFloatValue(double fail_value) const { + LLDB_INSTRUMENT_VA(this, fail_value); + + return m_impl_up->GetFloatValue(fail_value); +} + +bool SBStructuredData::GetBooleanValue(bool fail_value) const { + LLDB_INSTRUMENT_VA(this, fail_value); + + return m_impl_up->GetBooleanValue(fail_value); +} + +size_t SBStructuredData::GetStringValue(char *dst, size_t dst_len) const { + LLDB_INSTRUMENT_VA(this, dst, dst_len); + + return m_impl_up->GetStringValue(dst, dst_len); +} + +lldb::SBScriptObject SBStructuredData::GetGenericValue() const { + LLDB_INSTRUMENT_VA(this); + + return {m_impl_up->GetGenericValue(), eScriptLanguageDefault}; +} diff --git a/contrib/llvm-project/lldb/source/API/SBSymbol.cpp b/contrib/llvm-project/lldb/source/API/SBSymbol.cpp new file mode 100644 index 000000000000..3f940538d124 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBSymbol.cpp @@ -0,0 +1,209 @@ +//===-- SBSymbol.cpp ------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBSymbol.h" +#include "lldb/API/SBStream.h" +#include "lldb/Core/Disassembler.h" +#include "lldb/Core/Module.h" +#include "lldb/Symbol/Symbol.h" +#include "lldb/Target/ExecutionContext.h" +#include "lldb/Target/Target.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +SBSymbol::SBSymbol() { LLDB_INSTRUMENT_VA(this); } + +SBSymbol::SBSymbol(lldb_private::Symbol *lldb_object_ptr) + : m_opaque_ptr(lldb_object_ptr) {} + +SBSymbol::SBSymbol(const lldb::SBSymbol &rhs) : m_opaque_ptr(rhs.m_opaque_ptr) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const SBSymbol &SBSymbol::operator=(const SBSymbol &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_ptr = rhs.m_opaque_ptr; + return *this; +} + +SBSymbol::~SBSymbol() { m_opaque_ptr = nullptr; } + +void SBSymbol::SetSymbol(lldb_private::Symbol *lldb_object_ptr) { + m_opaque_ptr = lldb_object_ptr; +} + +bool SBSymbol::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBSymbol::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_ptr != nullptr; +} + +const char *SBSymbol::GetName() const { + LLDB_INSTRUMENT_VA(this); + + const char *name = nullptr; + if (m_opaque_ptr) + name = m_opaque_ptr->GetName().AsCString(); + + return name; +} + +const char *SBSymbol::GetDisplayName() const { + LLDB_INSTRUMENT_VA(this); + + const char *name = nullptr; + if (m_opaque_ptr) + name = m_opaque_ptr->GetMangled().GetDisplayDemangledName().AsCString(); + + return name; +} + +const char *SBSymbol::GetMangledName() const { + LLDB_INSTRUMENT_VA(this); + + const char *name = nullptr; + if (m_opaque_ptr) + name = m_opaque_ptr->GetMangled().GetMangledName().AsCString(); + return name; +} + +bool SBSymbol::operator==(const SBSymbol &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_ptr == rhs.m_opaque_ptr; +} + +bool SBSymbol::operator!=(const SBSymbol &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_ptr != rhs.m_opaque_ptr; +} + +bool SBSymbol::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + if (m_opaque_ptr) { + m_opaque_ptr->GetDescription(&strm, lldb::eDescriptionLevelFull, nullptr); + } else + strm.PutCString("No value"); + + return true; +} + +SBInstructionList SBSymbol::GetInstructions(SBTarget target) { + LLDB_INSTRUMENT_VA(this, target); + + return GetInstructions(target, nullptr); +} + +SBInstructionList SBSymbol::GetInstructions(SBTarget target, + const char *flavor_string) { + LLDB_INSTRUMENT_VA(this, target, flavor_string); + + SBInstructionList sb_instructions; + if (m_opaque_ptr) { + TargetSP target_sp(target.GetSP()); + std::unique_lock<std::recursive_mutex> lock; + if (target_sp && m_opaque_ptr->ValueIsAddress()) { + lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex()); + const Address &symbol_addr = m_opaque_ptr->GetAddressRef(); + ModuleSP module_sp = symbol_addr.GetModule(); + if (module_sp) { + AddressRange symbol_range(symbol_addr, m_opaque_ptr->GetByteSize()); + const bool force_live_memory = true; + sb_instructions.SetDisassembler(Disassembler::DisassembleRange( + module_sp->GetArchitecture(), nullptr, flavor_string, *target_sp, + symbol_range, force_live_memory)); + } + } + } + return sb_instructions; +} + +lldb_private::Symbol *SBSymbol::get() { return m_opaque_ptr; } + +void SBSymbol::reset(lldb_private::Symbol *symbol) { m_opaque_ptr = symbol; } + +SBAddress SBSymbol::GetStartAddress() { + LLDB_INSTRUMENT_VA(this); + + SBAddress addr; + if (m_opaque_ptr && m_opaque_ptr->ValueIsAddress()) { + addr.SetAddress(m_opaque_ptr->GetAddressRef()); + } + return addr; +} + +SBAddress SBSymbol::GetEndAddress() { + LLDB_INSTRUMENT_VA(this); + + SBAddress addr; + if (m_opaque_ptr && m_opaque_ptr->ValueIsAddress()) { + lldb::addr_t range_size = m_opaque_ptr->GetByteSize(); + if (range_size > 0) { + addr.SetAddress(m_opaque_ptr->GetAddressRef()); + addr->Slide(m_opaque_ptr->GetByteSize()); + } + } + return addr; +} + +uint64_t SBSymbol::GetValue() { + LLDB_INSTRUMENT_VA(this); + if (m_opaque_ptr) + return m_opaque_ptr->GetRawValue(); + return 0; +} + +uint64_t SBSymbol::GetSize() { + LLDB_INSTRUMENT_VA(this); + if (m_opaque_ptr && m_opaque_ptr->GetByteSizeIsValid()) + return m_opaque_ptr->GetByteSize(); + return 0; +} + +uint32_t SBSymbol::GetPrologueByteSize() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return m_opaque_ptr->GetPrologueByteSize(); + return 0; +} + +SymbolType SBSymbol::GetType() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return m_opaque_ptr->GetType(); + return eSymbolTypeInvalid; +} + +bool SBSymbol::IsExternal() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return m_opaque_ptr->IsExternal(); + return false; +} + +bool SBSymbol::IsSynthetic() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_ptr) + return m_opaque_ptr->IsSynthetic(); + return false; +} diff --git a/contrib/llvm-project/lldb/source/API/SBSymbolContext.cpp b/contrib/llvm-project/lldb/source/API/SBSymbolContext.cpp new file mode 100644 index 000000000000..484399c89590 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBSymbolContext.cpp @@ -0,0 +1,204 @@ +//===-- SBSymbolContext.cpp -----------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBSymbolContext.h" +#include "Utils.h" +#include "lldb/API/SBStream.h" +#include "lldb/Core/Module.h" +#include "lldb/Symbol/Function.h" +#include "lldb/Symbol/Symbol.h" +#include "lldb/Symbol/SymbolContext.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +SBSymbolContext::SBSymbolContext() { LLDB_INSTRUMENT_VA(this); } + +SBSymbolContext::SBSymbolContext(const SymbolContext &sc) + : m_opaque_up(std::make_unique<SymbolContext>(sc)) { + LLDB_INSTRUMENT_VA(this, sc); +} + +SBSymbolContext::SBSymbolContext(const SBSymbolContext &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBSymbolContext::~SBSymbolContext() = default; + +const SBSymbolContext &SBSymbolContext::operator=(const SBSymbolContext &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +bool SBSymbolContext::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBSymbolContext::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up != nullptr; +} + +SBModule SBSymbolContext::GetModule() { + LLDB_INSTRUMENT_VA(this); + + SBModule sb_module; + ModuleSP module_sp; + if (m_opaque_up) { + module_sp = m_opaque_up->module_sp; + sb_module.SetSP(module_sp); + } + + return sb_module; +} + +SBCompileUnit SBSymbolContext::GetCompileUnit() { + LLDB_INSTRUMENT_VA(this); + + return SBCompileUnit(m_opaque_up ? m_opaque_up->comp_unit : nullptr); +} + +SBFunction SBSymbolContext::GetFunction() { + LLDB_INSTRUMENT_VA(this); + + Function *function = nullptr; + + if (m_opaque_up) + function = m_opaque_up->function; + + SBFunction sb_function(function); + + return sb_function; +} + +SBBlock SBSymbolContext::GetBlock() { + LLDB_INSTRUMENT_VA(this); + + return SBBlock(m_opaque_up ? m_opaque_up->block : nullptr); +} + +SBLineEntry SBSymbolContext::GetLineEntry() { + LLDB_INSTRUMENT_VA(this); + + SBLineEntry sb_line_entry; + if (m_opaque_up) + sb_line_entry.SetLineEntry(m_opaque_up->line_entry); + + return sb_line_entry; +} + +SBSymbol SBSymbolContext::GetSymbol() { + LLDB_INSTRUMENT_VA(this); + + Symbol *symbol = nullptr; + + if (m_opaque_up) + symbol = m_opaque_up->symbol; + + SBSymbol sb_symbol(symbol); + + return sb_symbol; +} + +void SBSymbolContext::SetModule(lldb::SBModule module) { + LLDB_INSTRUMENT_VA(this, module); + + ref().module_sp = module.GetSP(); +} + +void SBSymbolContext::SetCompileUnit(lldb::SBCompileUnit compile_unit) { + LLDB_INSTRUMENT_VA(this, compile_unit); + + ref().comp_unit = compile_unit.get(); +} + +void SBSymbolContext::SetFunction(lldb::SBFunction function) { + LLDB_INSTRUMENT_VA(this, function); + + ref().function = function.get(); +} + +void SBSymbolContext::SetBlock(lldb::SBBlock block) { + LLDB_INSTRUMENT_VA(this, block); + + ref().block = block.GetPtr(); +} + +void SBSymbolContext::SetLineEntry(lldb::SBLineEntry line_entry) { + LLDB_INSTRUMENT_VA(this, line_entry); + + if (line_entry.IsValid()) + ref().line_entry = line_entry.ref(); + else + ref().line_entry.Clear(); +} + +void SBSymbolContext::SetSymbol(lldb::SBSymbol symbol) { + LLDB_INSTRUMENT_VA(this, symbol); + + ref().symbol = symbol.get(); +} + +lldb_private::SymbolContext *SBSymbolContext::operator->() const { + return m_opaque_up.get(); +} + +const lldb_private::SymbolContext &SBSymbolContext::operator*() const { + assert(m_opaque_up.get()); + return *m_opaque_up; +} + +lldb_private::SymbolContext &SBSymbolContext::operator*() { + if (m_opaque_up == nullptr) + m_opaque_up = std::make_unique<SymbolContext>(); + return *m_opaque_up; +} + +lldb_private::SymbolContext &SBSymbolContext::ref() { + if (m_opaque_up == nullptr) + m_opaque_up = std::make_unique<SymbolContext>(); + return *m_opaque_up; +} + +lldb_private::SymbolContext *SBSymbolContext::get() const { + return m_opaque_up.get(); +} + +bool SBSymbolContext::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + if (m_opaque_up) { + m_opaque_up->GetDescription(&strm, lldb::eDescriptionLevelFull, nullptr); + } else + strm.PutCString("No value"); + + return true; +} + +SBSymbolContext +SBSymbolContext::GetParentOfInlinedScope(const SBAddress &curr_frame_pc, + SBAddress &parent_frame_addr) const { + LLDB_INSTRUMENT_VA(this, curr_frame_pc, parent_frame_addr); + + SBSymbolContext sb_sc; + if (m_opaque_up.get() && curr_frame_pc.IsValid()) { + if (m_opaque_up->GetParentOfInlinedScope(curr_frame_pc.ref(), sb_sc.ref(), + parent_frame_addr.ref())) + return sb_sc; + } + return SBSymbolContext(); +} diff --git a/contrib/llvm-project/lldb/source/API/SBSymbolContextList.cpp b/contrib/llvm-project/lldb/source/API/SBSymbolContextList.cpp new file mode 100644 index 000000000000..baa558caebbc --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBSymbolContextList.cpp @@ -0,0 +1,107 @@ +//===-- SBSymbolContextList.cpp -------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBSymbolContextList.h" +#include "Utils.h" +#include "lldb/API/SBStream.h" +#include "lldb/Symbol/SymbolContext.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +SBSymbolContextList::SBSymbolContextList() + : m_opaque_up(new SymbolContextList()) { + LLDB_INSTRUMENT_VA(this); +} + +SBSymbolContextList::SBSymbolContextList(const SBSymbolContextList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBSymbolContextList::~SBSymbolContextList() = default; + +const SBSymbolContextList &SBSymbolContextList:: +operator=(const SBSymbolContextList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +uint32_t SBSymbolContextList::GetSize() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + return m_opaque_up->GetSize(); + return 0; +} + +SBSymbolContext SBSymbolContextList::GetContextAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBSymbolContext sb_sc; + if (m_opaque_up) { + SymbolContext sc; + if (m_opaque_up->GetContextAtIndex(idx, sc)) + sb_sc = sc; + } + return sb_sc; +} + +void SBSymbolContextList::Clear() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + m_opaque_up->Clear(); +} + +void SBSymbolContextList::Append(SBSymbolContext &sc) { + LLDB_INSTRUMENT_VA(this, sc); + + if (sc.IsValid() && m_opaque_up.get()) + m_opaque_up->Append(*sc); +} + +void SBSymbolContextList::Append(SBSymbolContextList &sc_list) { + LLDB_INSTRUMENT_VA(this, sc_list); + + if (sc_list.IsValid() && m_opaque_up.get()) + m_opaque_up->Append(*sc_list); +} + +bool SBSymbolContextList::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBSymbolContextList::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up != nullptr; +} + +lldb_private::SymbolContextList *SBSymbolContextList::operator->() const { + return m_opaque_up.get(); +} + +lldb_private::SymbolContextList &SBSymbolContextList::operator*() const { + assert(m_opaque_up.get()); + return *m_opaque_up; +} + +bool SBSymbolContextList::GetDescription(lldb::SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + if (m_opaque_up) + m_opaque_up->GetDescription(&strm, lldb::eDescriptionLevelFull, nullptr); + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBTarget.cpp b/contrib/llvm-project/lldb/source/API/SBTarget.cpp new file mode 100644 index 000000000000..2c336296f0b8 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBTarget.cpp @@ -0,0 +1,2429 @@ +//===-- SBTarget.cpp ------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBTarget.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/LLDBLog.h" +#include "lldb/lldb-public.h" + +#include "lldb/API/SBBreakpoint.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBEnvironment.h" +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBExpressionOptions.h" +#include "lldb/API/SBFileSpec.h" +#include "lldb/API/SBListener.h" +#include "lldb/API/SBModule.h" +#include "lldb/API/SBModuleSpec.h" +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBSourceManager.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStringList.h" +#include "lldb/API/SBStructuredData.h" +#include "lldb/API/SBSymbolContextList.h" +#include "lldb/API/SBTrace.h" +#include "lldb/Breakpoint/BreakpointID.h" +#include "lldb/Breakpoint/BreakpointIDList.h" +#include "lldb/Breakpoint/BreakpointList.h" +#include "lldb/Breakpoint/BreakpointLocation.h" +#include "lldb/Core/Address.h" +#include "lldb/Core/AddressResolver.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Core/Disassembler.h" +#include "lldb/Core/Module.h" +#include "lldb/Core/ModuleSpec.h" +#include "lldb/Core/PluginManager.h" +#include "lldb/Core/SearchFilter.h" +#include "lldb/Core/Section.h" +#include "lldb/Core/StructuredDataImpl.h" +#include "lldb/Core/ValueObjectConstResult.h" +#include "lldb/Core/ValueObjectList.h" +#include "lldb/Core/ValueObjectVariable.h" +#include "lldb/Host/Host.h" +#include "lldb/Symbol/DeclVendor.h" +#include "lldb/Symbol/ObjectFile.h" +#include "lldb/Symbol/SymbolFile.h" +#include "lldb/Symbol/SymbolVendor.h" +#include "lldb/Symbol/TypeSystem.h" +#include "lldb/Symbol/VariableList.h" +#include "lldb/Target/ABI.h" +#include "lldb/Target/Language.h" +#include "lldb/Target/LanguageRuntime.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/StackFrame.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/TargetList.h" +#include "lldb/Utility/ArchSpec.h" +#include "lldb/Utility/Args.h" +#include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/ProcessInfo.h" +#include "lldb/Utility/RegularExpression.h" + +#include "Commands/CommandObjectBreakpoint.h" +#include "lldb/Interpreter/CommandReturnObject.h" +#include "llvm/Support/PrettyStackTrace.h" +#include "llvm/Support/Regex.h" + +using namespace lldb; +using namespace lldb_private; + +#define DEFAULT_DISASM_BYTE_SIZE 32 + +static Status AttachToProcess(ProcessAttachInfo &attach_info, Target &target) { + std::lock_guard<std::recursive_mutex> guard(target.GetAPIMutex()); + + auto process_sp = target.GetProcessSP(); + if (process_sp) { + const auto state = process_sp->GetState(); + if (process_sp->IsAlive() && state == eStateConnected) { + // If we are already connected, then we have already specified the + // listener, so if a valid listener is supplied, we need to error out to + // let the client know. + if (attach_info.GetListener()) + return Status("process is connected and already has a listener, pass " + "empty listener"); + } + } + + return target.Attach(attach_info, nullptr); +} + +// SBTarget constructor +SBTarget::SBTarget() { LLDB_INSTRUMENT_VA(this); } + +SBTarget::SBTarget(const SBTarget &rhs) : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBTarget::SBTarget(const TargetSP &target_sp) : m_opaque_sp(target_sp) { + LLDB_INSTRUMENT_VA(this, target_sp); +} + +const SBTarget &SBTarget::operator=(const SBTarget &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; +} + +// Destructor +SBTarget::~SBTarget() = default; + +bool SBTarget::EventIsTargetEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return Target::TargetEventData::GetEventDataFromEvent(event.get()) != nullptr; +} + +SBTarget SBTarget::GetTargetFromEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return Target::TargetEventData::GetTargetFromEvent(event.get()); +} + +uint32_t SBTarget::GetNumModulesFromEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + const ModuleList module_list = + Target::TargetEventData::GetModuleListFromEvent(event.get()); + return module_list.GetSize(); +} + +SBModule SBTarget::GetModuleAtIndexFromEvent(const uint32_t idx, + const SBEvent &event) { + LLDB_INSTRUMENT_VA(idx, event); + + const ModuleList module_list = + Target::TargetEventData::GetModuleListFromEvent(event.get()); + return SBModule(module_list.GetModuleAtIndex(idx)); +} + +const char *SBTarget::GetBroadcasterClassName() { + LLDB_INSTRUMENT(); + + return ConstString(Target::GetStaticBroadcasterClass()).AsCString(); +} + +bool SBTarget::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTarget::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr && m_opaque_sp->IsValid(); +} + +SBProcess SBTarget::GetProcess() { + LLDB_INSTRUMENT_VA(this); + + SBProcess sb_process; + ProcessSP process_sp; + TargetSP target_sp(GetSP()); + if (target_sp) { + process_sp = target_sp->GetProcessSP(); + sb_process.SetSP(process_sp); + } + + return sb_process; +} + +SBPlatform SBTarget::GetPlatform() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (!target_sp) + return SBPlatform(); + + SBPlatform platform; + platform.m_opaque_sp = target_sp->GetPlatform(); + + return platform; +} + +SBDebugger SBTarget::GetDebugger() const { + LLDB_INSTRUMENT_VA(this); + + SBDebugger debugger; + TargetSP target_sp(GetSP()); + if (target_sp) + debugger.reset(target_sp->GetDebugger().shared_from_this()); + return debugger; +} + +SBStructuredData SBTarget::GetStatistics() { + LLDB_INSTRUMENT_VA(this); + SBStatisticsOptions options; + return GetStatistics(options); +} + +SBStructuredData SBTarget::GetStatistics(SBStatisticsOptions options) { + LLDB_INSTRUMENT_VA(this); + + SBStructuredData data; + TargetSP target_sp(GetSP()); + if (!target_sp) + return data; + std::string json_str = + llvm::formatv("{0:2}", DebuggerStats::ReportStatistics( + target_sp->GetDebugger(), target_sp.get(), + options.ref())) + .str(); + data.m_impl_up->SetObjectSP(StructuredData::ParseJSON(json_str)); + return data; +} + +void SBTarget::SetCollectingStats(bool v) { + LLDB_INSTRUMENT_VA(this, v); + + TargetSP target_sp(GetSP()); + if (!target_sp) + return; + return DebuggerStats::SetCollectingStats(v); +} + +bool SBTarget::GetCollectingStats() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (!target_sp) + return false; + return DebuggerStats::GetCollectingStats(); +} + +SBProcess SBTarget::LoadCore(const char *core_file) { + LLDB_INSTRUMENT_VA(this, core_file); + + lldb::SBError error; // Ignored + return LoadCore(core_file, error); +} + +SBProcess SBTarget::LoadCore(const char *core_file, lldb::SBError &error) { + LLDB_INSTRUMENT_VA(this, core_file, error); + + SBProcess sb_process; + TargetSP target_sp(GetSP()); + if (target_sp) { + FileSpec filespec(core_file); + FileSystem::Instance().Resolve(filespec); + ProcessSP process_sp(target_sp->CreateProcess( + target_sp->GetDebugger().GetListener(), "", &filespec, false)); + if (process_sp) { + error.SetError(process_sp->LoadCore()); + if (error.Success()) + sb_process.SetSP(process_sp); + } else { + error.SetErrorString("Failed to create the process"); + } + } else { + error.SetErrorString("SBTarget is invalid"); + } + return sb_process; +} + +SBProcess SBTarget::LaunchSimple(char const **argv, char const **envp, + const char *working_directory) { + LLDB_INSTRUMENT_VA(this, argv, envp, working_directory); + + TargetSP target_sp = GetSP(); + if (!target_sp) + return SBProcess(); + + SBLaunchInfo launch_info = GetLaunchInfo(); + + if (Module *exe_module = target_sp->GetExecutableModulePointer()) + launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), + /*add_as_first_arg*/ true); + if (argv) + launch_info.SetArguments(argv, /*append*/ true); + if (envp) + launch_info.SetEnvironmentEntries(envp, /*append*/ false); + if (working_directory) + launch_info.SetWorkingDirectory(working_directory); + + SBError error; + return Launch(launch_info, error); +} + +SBError SBTarget::Install() { + LLDB_INSTRUMENT_VA(this); + + SBError sb_error; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + sb_error.ref() = target_sp->Install(nullptr); + } + return sb_error; +} + +SBProcess SBTarget::Launch(SBListener &listener, char const **argv, + char const **envp, const char *stdin_path, + const char *stdout_path, const char *stderr_path, + const char *working_directory, + uint32_t launch_flags, // See LaunchFlags + bool stop_at_entry, lldb::SBError &error) { + LLDB_INSTRUMENT_VA(this, listener, argv, envp, stdin_path, stdout_path, + stderr_path, working_directory, launch_flags, + stop_at_entry, error); + + SBProcess sb_process; + ProcessSP process_sp; + TargetSP target_sp(GetSP()); + + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + + if (stop_at_entry) + launch_flags |= eLaunchFlagStopAtEntry; + + if (getenv("LLDB_LAUNCH_FLAG_DISABLE_ASLR")) + launch_flags |= eLaunchFlagDisableASLR; + + StateType state = eStateInvalid; + process_sp = target_sp->GetProcessSP(); + if (process_sp) { + state = process_sp->GetState(); + + if (process_sp->IsAlive() && state != eStateConnected) { + if (state == eStateAttaching) + error.SetErrorString("process attach is in progress"); + else + error.SetErrorString("a process is already being debugged"); + return sb_process; + } + } + + if (state == eStateConnected) { + // If we are already connected, then we have already specified the + // listener, so if a valid listener is supplied, we need to error out to + // let the client know. + if (listener.IsValid()) { + error.SetErrorString("process is connected and already has a listener, " + "pass empty listener"); + return sb_process; + } + } + + if (getenv("LLDB_LAUNCH_FLAG_DISABLE_STDIO")) + launch_flags |= eLaunchFlagDisableSTDIO; + + ProcessLaunchInfo launch_info(FileSpec(stdin_path), FileSpec(stdout_path), + FileSpec(stderr_path), + FileSpec(working_directory), launch_flags); + + Module *exe_module = target_sp->GetExecutableModulePointer(); + if (exe_module) + launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true); + if (argv) { + launch_info.GetArguments().AppendArguments(argv); + } else { + auto default_launch_info = target_sp->GetProcessLaunchInfo(); + launch_info.GetArguments().AppendArguments( + default_launch_info.GetArguments()); + } + if (envp) { + launch_info.GetEnvironment() = Environment(envp); + } else { + auto default_launch_info = target_sp->GetProcessLaunchInfo(); + launch_info.GetEnvironment() = default_launch_info.GetEnvironment(); + } + + if (listener.IsValid()) + launch_info.SetListener(listener.GetSP()); + + error.SetError(target_sp->Launch(launch_info, nullptr)); + + sb_process.SetSP(target_sp->GetProcessSP()); + } else { + error.SetErrorString("SBTarget is invalid"); + } + + return sb_process; +} + +SBProcess SBTarget::Launch(SBLaunchInfo &sb_launch_info, SBError &error) { + LLDB_INSTRUMENT_VA(this, sb_launch_info, error); + + SBProcess sb_process; + TargetSP target_sp(GetSP()); + + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + StateType state = eStateInvalid; + { + ProcessSP process_sp = target_sp->GetProcessSP(); + if (process_sp) { + state = process_sp->GetState(); + + if (process_sp->IsAlive() && state != eStateConnected) { + if (state == eStateAttaching) + error.SetErrorString("process attach is in progress"); + else + error.SetErrorString("a process is already being debugged"); + return sb_process; + } + } + } + + lldb_private::ProcessLaunchInfo launch_info = sb_launch_info.ref(); + + if (!launch_info.GetExecutableFile()) { + Module *exe_module = target_sp->GetExecutableModulePointer(); + if (exe_module) + launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true); + } + + const ArchSpec &arch_spec = target_sp->GetArchitecture(); + if (arch_spec.IsValid()) + launch_info.GetArchitecture() = arch_spec; + + error.SetError(target_sp->Launch(launch_info, nullptr)); + sb_launch_info.set_ref(launch_info); + sb_process.SetSP(target_sp->GetProcessSP()); + } else { + error.SetErrorString("SBTarget is invalid"); + } + + return sb_process; +} + +lldb::SBProcess SBTarget::Attach(SBAttachInfo &sb_attach_info, SBError &error) { + LLDB_INSTRUMENT_VA(this, sb_attach_info, error); + + SBProcess sb_process; + TargetSP target_sp(GetSP()); + + if (target_sp) { + ProcessAttachInfo &attach_info = sb_attach_info.ref(); + if (attach_info.ProcessIDIsValid() && !attach_info.UserIDIsValid() && + !attach_info.IsScriptedProcess()) { + PlatformSP platform_sp = target_sp->GetPlatform(); + // See if we can pre-verify if a process exists or not + if (platform_sp && platform_sp->IsConnected()) { + lldb::pid_t attach_pid = attach_info.GetProcessID(); + ProcessInstanceInfo instance_info; + if (platform_sp->GetProcessInfo(attach_pid, instance_info)) { + attach_info.SetUserID(instance_info.GetEffectiveUserID()); + } else { + error.ref().SetErrorStringWithFormat( + "no process found with process ID %" PRIu64, attach_pid); + return sb_process; + } + } + } + error.SetError(AttachToProcess(attach_info, *target_sp)); + if (error.Success()) + sb_process.SetSP(target_sp->GetProcessSP()); + } else { + error.SetErrorString("SBTarget is invalid"); + } + + return sb_process; +} + +lldb::SBProcess SBTarget::AttachToProcessWithID( + SBListener &listener, + lldb::pid_t pid, // The process ID to attach to + SBError &error // An error explaining what went wrong if attach fails +) { + LLDB_INSTRUMENT_VA(this, listener, pid, error); + + SBProcess sb_process; + TargetSP target_sp(GetSP()); + + if (target_sp) { + ProcessAttachInfo attach_info; + attach_info.SetProcessID(pid); + if (listener.IsValid()) + attach_info.SetListener(listener.GetSP()); + + ProcessInstanceInfo instance_info; + if (target_sp->GetPlatform()->GetProcessInfo(pid, instance_info)) + attach_info.SetUserID(instance_info.GetEffectiveUserID()); + + error.SetError(AttachToProcess(attach_info, *target_sp)); + if (error.Success()) + sb_process.SetSP(target_sp->GetProcessSP()); + } else + error.SetErrorString("SBTarget is invalid"); + + return sb_process; +} + +lldb::SBProcess SBTarget::AttachToProcessWithName( + SBListener &listener, + const char *name, // basename of process to attach to + bool wait_for, // if true wait for a new instance of "name" to be launched + SBError &error // An error explaining what went wrong if attach fails +) { + LLDB_INSTRUMENT_VA(this, listener, name, wait_for, error); + + SBProcess sb_process; + TargetSP target_sp(GetSP()); + + if (name && target_sp) { + ProcessAttachInfo attach_info; + attach_info.GetExecutableFile().SetFile(name, FileSpec::Style::native); + attach_info.SetWaitForLaunch(wait_for); + if (listener.IsValid()) + attach_info.SetListener(listener.GetSP()); + + error.SetError(AttachToProcess(attach_info, *target_sp)); + if (error.Success()) + sb_process.SetSP(target_sp->GetProcessSP()); + } else + error.SetErrorString("SBTarget is invalid"); + + return sb_process; +} + +lldb::SBProcess SBTarget::ConnectRemote(SBListener &listener, const char *url, + const char *plugin_name, + SBError &error) { + LLDB_INSTRUMENT_VA(this, listener, url, plugin_name, error); + + SBProcess sb_process; + ProcessSP process_sp; + TargetSP target_sp(GetSP()); + + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + if (listener.IsValid()) + process_sp = + target_sp->CreateProcess(listener.m_opaque_sp, plugin_name, nullptr, + true); + else + process_sp = target_sp->CreateProcess( + target_sp->GetDebugger().GetListener(), plugin_name, nullptr, true); + + if (process_sp) { + sb_process.SetSP(process_sp); + error.SetError(process_sp->ConnectRemote(url)); + } else { + error.SetErrorString("unable to create lldb_private::Process"); + } + } else { + error.SetErrorString("SBTarget is invalid"); + } + + return sb_process; +} + +SBFileSpec SBTarget::GetExecutable() { + LLDB_INSTRUMENT_VA(this); + + SBFileSpec exe_file_spec; + TargetSP target_sp(GetSP()); + if (target_sp) { + Module *exe_module = target_sp->GetExecutableModulePointer(); + if (exe_module) + exe_file_spec.SetFileSpec(exe_module->GetFileSpec()); + } + + return exe_file_spec; +} + +bool SBTarget::operator==(const SBTarget &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_sp.get() == rhs.m_opaque_sp.get(); +} + +bool SBTarget::operator!=(const SBTarget &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_sp.get() != rhs.m_opaque_sp.get(); +} + +lldb::TargetSP SBTarget::GetSP() const { return m_opaque_sp; } + +void SBTarget::SetSP(const lldb::TargetSP &target_sp) { + m_opaque_sp = target_sp; +} + +lldb::SBAddress SBTarget::ResolveLoadAddress(lldb::addr_t vm_addr) { + LLDB_INSTRUMENT_VA(this, vm_addr); + + lldb::SBAddress sb_addr; + Address &addr = sb_addr.ref(); + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + if (target_sp->ResolveLoadAddress(vm_addr, addr)) + return sb_addr; + } + + // We have a load address that isn't in a section, just return an address + // with the offset filled in (the address) and the section set to NULL + addr.SetRawAddress(vm_addr); + return sb_addr; +} + +lldb::SBAddress SBTarget::ResolveFileAddress(lldb::addr_t file_addr) { + LLDB_INSTRUMENT_VA(this, file_addr); + + lldb::SBAddress sb_addr; + Address &addr = sb_addr.ref(); + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + if (target_sp->ResolveFileAddress(file_addr, addr)) + return sb_addr; + } + + addr.SetRawAddress(file_addr); + return sb_addr; +} + +lldb::SBAddress SBTarget::ResolvePastLoadAddress(uint32_t stop_id, + lldb::addr_t vm_addr) { + LLDB_INSTRUMENT_VA(this, stop_id, vm_addr); + + lldb::SBAddress sb_addr; + Address &addr = sb_addr.ref(); + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + if (target_sp->ResolveLoadAddress(vm_addr, addr)) + return sb_addr; + } + + // We have a load address that isn't in a section, just return an address + // with the offset filled in (the address) and the section set to NULL + addr.SetRawAddress(vm_addr); + return sb_addr; +} + +SBSymbolContext +SBTarget::ResolveSymbolContextForAddress(const SBAddress &addr, + uint32_t resolve_scope) { + LLDB_INSTRUMENT_VA(this, addr, resolve_scope); + + SBSymbolContext sc; + SymbolContextItem scope = static_cast<SymbolContextItem>(resolve_scope); + if (addr.IsValid()) { + TargetSP target_sp(GetSP()); + if (target_sp) + target_sp->GetImages().ResolveSymbolContextForAddress(addr.ref(), scope, + sc.ref()); + } + return sc; +} + +size_t SBTarget::ReadMemory(const SBAddress addr, void *buf, size_t size, + lldb::SBError &error) { + LLDB_INSTRUMENT_VA(this, addr, buf, size, error); + + SBError sb_error; + size_t bytes_read = 0; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + bytes_read = + target_sp->ReadMemory(addr.ref(), buf, size, sb_error.ref(), true); + } else { + sb_error.SetErrorString("invalid target"); + } + + return bytes_read; +} + +SBBreakpoint SBTarget::BreakpointCreateByLocation(const char *file, + uint32_t line) { + LLDB_INSTRUMENT_VA(this, file, line); + + return SBBreakpoint( + BreakpointCreateByLocation(SBFileSpec(file, false), line)); +} + +SBBreakpoint +SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec, + uint32_t line) { + LLDB_INSTRUMENT_VA(this, sb_file_spec, line); + + return BreakpointCreateByLocation(sb_file_spec, line, 0); +} + +SBBreakpoint +SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec, + uint32_t line, lldb::addr_t offset) { + LLDB_INSTRUMENT_VA(this, sb_file_spec, line, offset); + + SBFileSpecList empty_list; + return BreakpointCreateByLocation(sb_file_spec, line, offset, empty_list); +} + +SBBreakpoint +SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec, + uint32_t line, lldb::addr_t offset, + SBFileSpecList &sb_module_list) { + LLDB_INSTRUMENT_VA(this, sb_file_spec, line, offset, sb_module_list); + + return BreakpointCreateByLocation(sb_file_spec, line, 0, offset, + sb_module_list); +} + +SBBreakpoint SBTarget::BreakpointCreateByLocation( + const SBFileSpec &sb_file_spec, uint32_t line, uint32_t column, + lldb::addr_t offset, SBFileSpecList &sb_module_list) { + LLDB_INSTRUMENT_VA(this, sb_file_spec, line, column, offset, sb_module_list); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp && line != 0) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + + const LazyBool check_inlines = eLazyBoolCalculate; + const LazyBool skip_prologue = eLazyBoolCalculate; + const bool internal = false; + const bool hardware = false; + const LazyBool move_to_nearest_code = eLazyBoolCalculate; + const FileSpecList *module_list = nullptr; + if (sb_module_list.GetSize() > 0) { + module_list = sb_module_list.get(); + } + sb_bp = target_sp->CreateBreakpoint( + module_list, *sb_file_spec, line, column, offset, check_inlines, + skip_prologue, internal, hardware, move_to_nearest_code); + } + + return sb_bp; +} + +SBBreakpoint SBTarget::BreakpointCreateByLocation( + const SBFileSpec &sb_file_spec, uint32_t line, uint32_t column, + lldb::addr_t offset, SBFileSpecList &sb_module_list, + bool move_to_nearest_code) { + LLDB_INSTRUMENT_VA(this, sb_file_spec, line, column, offset, sb_module_list, + move_to_nearest_code); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp && line != 0) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + + const LazyBool check_inlines = eLazyBoolCalculate; + const LazyBool skip_prologue = eLazyBoolCalculate; + const bool internal = false; + const bool hardware = false; + const FileSpecList *module_list = nullptr; + if (sb_module_list.GetSize() > 0) { + module_list = sb_module_list.get(); + } + sb_bp = target_sp->CreateBreakpoint( + module_list, *sb_file_spec, line, column, offset, check_inlines, + skip_prologue, internal, hardware, + move_to_nearest_code ? eLazyBoolYes : eLazyBoolNo); + } + + return sb_bp; +} + +SBBreakpoint SBTarget::BreakpointCreateByName(const char *symbol_name, + const char *module_name) { + LLDB_INSTRUMENT_VA(this, symbol_name, module_name); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp.get()) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + + const bool internal = false; + const bool hardware = false; + const LazyBool skip_prologue = eLazyBoolCalculate; + const lldb::addr_t offset = 0; + if (module_name && module_name[0]) { + FileSpecList module_spec_list; + module_spec_list.Append(FileSpec(module_name)); + sb_bp = target_sp->CreateBreakpoint( + &module_spec_list, nullptr, symbol_name, eFunctionNameTypeAuto, + eLanguageTypeUnknown, offset, skip_prologue, internal, hardware); + } else { + sb_bp = target_sp->CreateBreakpoint( + nullptr, nullptr, symbol_name, eFunctionNameTypeAuto, + eLanguageTypeUnknown, offset, skip_prologue, internal, hardware); + } + } + + return sb_bp; +} + +lldb::SBBreakpoint +SBTarget::BreakpointCreateByName(const char *symbol_name, + const SBFileSpecList &module_list, + const SBFileSpecList &comp_unit_list) { + LLDB_INSTRUMENT_VA(this, symbol_name, module_list, comp_unit_list); + + lldb::FunctionNameType name_type_mask = eFunctionNameTypeAuto; + return BreakpointCreateByName(symbol_name, name_type_mask, + eLanguageTypeUnknown, module_list, + comp_unit_list); +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateByName( + const char *symbol_name, uint32_t name_type_mask, + const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) { + LLDB_INSTRUMENT_VA(this, symbol_name, name_type_mask, module_list, + comp_unit_list); + + return BreakpointCreateByName(symbol_name, name_type_mask, + eLanguageTypeUnknown, module_list, + comp_unit_list); +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateByName( + const char *symbol_name, uint32_t name_type_mask, + LanguageType symbol_language, const SBFileSpecList &module_list, + const SBFileSpecList &comp_unit_list) { + LLDB_INSTRUMENT_VA(this, symbol_name, name_type_mask, symbol_language, + module_list, comp_unit_list); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp && symbol_name && symbol_name[0]) { + const bool internal = false; + const bool hardware = false; + const LazyBool skip_prologue = eLazyBoolCalculate; + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + FunctionNameType mask = static_cast<FunctionNameType>(name_type_mask); + sb_bp = target_sp->CreateBreakpoint(module_list.get(), comp_unit_list.get(), + symbol_name, mask, symbol_language, 0, + skip_prologue, internal, hardware); + } + + return sb_bp; +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateByNames( + const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask, + const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) { + LLDB_INSTRUMENT_VA(this, symbol_names, num_names, name_type_mask, module_list, + comp_unit_list); + + return BreakpointCreateByNames(symbol_names, num_names, name_type_mask, + eLanguageTypeUnknown, module_list, + comp_unit_list); +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateByNames( + const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask, + LanguageType symbol_language, const SBFileSpecList &module_list, + const SBFileSpecList &comp_unit_list) { + LLDB_INSTRUMENT_VA(this, symbol_names, num_names, name_type_mask, + symbol_language, module_list, comp_unit_list); + + return BreakpointCreateByNames(symbol_names, num_names, name_type_mask, + eLanguageTypeUnknown, 0, module_list, + comp_unit_list); +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateByNames( + const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask, + LanguageType symbol_language, lldb::addr_t offset, + const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) { + LLDB_INSTRUMENT_VA(this, symbol_names, num_names, name_type_mask, + symbol_language, offset, module_list, comp_unit_list); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp && num_names > 0) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + const bool internal = false; + const bool hardware = false; + FunctionNameType mask = static_cast<FunctionNameType>(name_type_mask); + const LazyBool skip_prologue = eLazyBoolCalculate; + sb_bp = target_sp->CreateBreakpoint( + module_list.get(), comp_unit_list.get(), symbol_names, num_names, mask, + symbol_language, offset, skip_prologue, internal, hardware); + } + + return sb_bp; +} + +SBBreakpoint SBTarget::BreakpointCreateByRegex(const char *symbol_name_regex, + const char *module_name) { + LLDB_INSTRUMENT_VA(this, symbol_name_regex, module_name); + + SBFileSpecList module_spec_list; + SBFileSpecList comp_unit_list; + if (module_name && module_name[0]) { + module_spec_list.Append(FileSpec(module_name)); + } + return BreakpointCreateByRegex(symbol_name_regex, eLanguageTypeUnknown, + module_spec_list, comp_unit_list); +} + +lldb::SBBreakpoint +SBTarget::BreakpointCreateByRegex(const char *symbol_name_regex, + const SBFileSpecList &module_list, + const SBFileSpecList &comp_unit_list) { + LLDB_INSTRUMENT_VA(this, symbol_name_regex, module_list, comp_unit_list); + + return BreakpointCreateByRegex(symbol_name_regex, eLanguageTypeUnknown, + module_list, comp_unit_list); +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateByRegex( + const char *symbol_name_regex, LanguageType symbol_language, + const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) { + LLDB_INSTRUMENT_VA(this, symbol_name_regex, symbol_language, module_list, + comp_unit_list); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp && symbol_name_regex && symbol_name_regex[0]) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + RegularExpression regexp((llvm::StringRef(symbol_name_regex))); + const bool internal = false; + const bool hardware = false; + const LazyBool skip_prologue = eLazyBoolCalculate; + + sb_bp = target_sp->CreateFuncRegexBreakpoint( + module_list.get(), comp_unit_list.get(), std::move(regexp), + symbol_language, skip_prologue, internal, hardware); + } + + return sb_bp; +} + +SBBreakpoint SBTarget::BreakpointCreateByAddress(addr_t address) { + LLDB_INSTRUMENT_VA(this, address); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + const bool hardware = false; + sb_bp = target_sp->CreateBreakpoint(address, false, hardware); + } + + return sb_bp; +} + +SBBreakpoint SBTarget::BreakpointCreateBySBAddress(SBAddress &sb_address) { + LLDB_INSTRUMENT_VA(this, sb_address); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (!sb_address.IsValid()) { + return sb_bp; + } + + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + const bool hardware = false; + sb_bp = target_sp->CreateBreakpoint(sb_address.ref(), false, hardware); + } + + return sb_bp; +} + +lldb::SBBreakpoint +SBTarget::BreakpointCreateBySourceRegex(const char *source_regex, + const lldb::SBFileSpec &source_file, + const char *module_name) { + LLDB_INSTRUMENT_VA(this, source_regex, source_file, module_name); + + SBFileSpecList module_spec_list; + + if (module_name && module_name[0]) { + module_spec_list.Append(FileSpec(module_name)); + } + + SBFileSpecList source_file_list; + if (source_file.IsValid()) { + source_file_list.Append(source_file); + } + + return BreakpointCreateBySourceRegex(source_regex, module_spec_list, + source_file_list); +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateBySourceRegex( + const char *source_regex, const SBFileSpecList &module_list, + const lldb::SBFileSpecList &source_file_list) { + LLDB_INSTRUMENT_VA(this, source_regex, module_list, source_file_list); + + return BreakpointCreateBySourceRegex(source_regex, module_list, + source_file_list, SBStringList()); +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateBySourceRegex( + const char *source_regex, const SBFileSpecList &module_list, + const lldb::SBFileSpecList &source_file_list, + const SBStringList &func_names) { + LLDB_INSTRUMENT_VA(this, source_regex, module_list, source_file_list, + func_names); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp && source_regex && source_regex[0]) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + const bool hardware = false; + const LazyBool move_to_nearest_code = eLazyBoolCalculate; + RegularExpression regexp((llvm::StringRef(source_regex))); + std::unordered_set<std::string> func_names_set; + for (size_t i = 0; i < func_names.GetSize(); i++) { + func_names_set.insert(func_names.GetStringAtIndex(i)); + } + + sb_bp = target_sp->CreateSourceRegexBreakpoint( + module_list.get(), source_file_list.get(), func_names_set, + std::move(regexp), false, hardware, move_to_nearest_code); + } + + return sb_bp; +} + +lldb::SBBreakpoint +SBTarget::BreakpointCreateForException(lldb::LanguageType language, + bool catch_bp, bool throw_bp) { + LLDB_INSTRUMENT_VA(this, language, catch_bp, throw_bp); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + const bool hardware = false; + sb_bp = target_sp->CreateExceptionBreakpoint(language, catch_bp, throw_bp, + hardware); + } + + return sb_bp; +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateFromScript( + const char *class_name, SBStructuredData &extra_args, + const SBFileSpecList &module_list, const SBFileSpecList &file_list, + bool request_hardware) { + LLDB_INSTRUMENT_VA(this, class_name, extra_args, module_list, file_list, + request_hardware); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + Status error; + + StructuredData::ObjectSP obj_sp = extra_args.m_impl_up->GetObjectSP(); + sb_bp = + target_sp->CreateScriptedBreakpoint(class_name, + module_list.get(), + file_list.get(), + false, /* internal */ + request_hardware, + obj_sp, + &error); + } + + return sb_bp; +} + +uint32_t SBTarget::GetNumBreakpoints() const { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) { + // The breakpoint list is thread safe, no need to lock + return target_sp->GetBreakpointList().GetSize(); + } + return 0; +} + +SBBreakpoint SBTarget::GetBreakpointAtIndex(uint32_t idx) const { + LLDB_INSTRUMENT_VA(this, idx); + + SBBreakpoint sb_breakpoint; + TargetSP target_sp(GetSP()); + if (target_sp) { + // The breakpoint list is thread safe, no need to lock + sb_breakpoint = target_sp->GetBreakpointList().GetBreakpointAtIndex(idx); + } + return sb_breakpoint; +} + +bool SBTarget::BreakpointDelete(break_id_t bp_id) { + LLDB_INSTRUMENT_VA(this, bp_id); + + bool result = false; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + result = target_sp->RemoveBreakpointByID(bp_id); + } + + return result; +} + +SBBreakpoint SBTarget::FindBreakpointByID(break_id_t bp_id) { + LLDB_INSTRUMENT_VA(this, bp_id); + + SBBreakpoint sb_breakpoint; + TargetSP target_sp(GetSP()); + if (target_sp && bp_id != LLDB_INVALID_BREAK_ID) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + sb_breakpoint = target_sp->GetBreakpointByID(bp_id); + } + + return sb_breakpoint; +} + +bool SBTarget::FindBreakpointsByName(const char *name, + SBBreakpointList &bkpts) { + LLDB_INSTRUMENT_VA(this, name, bkpts); + + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + llvm::Expected<std::vector<BreakpointSP>> expected_vector = + target_sp->GetBreakpointList().FindBreakpointsByName(name); + if (!expected_vector) { + LLDB_LOG_ERROR(GetLog(LLDBLog::Breakpoints), expected_vector.takeError(), + "invalid breakpoint name: {0}"); + return false; + } + for (BreakpointSP bkpt_sp : *expected_vector) { + bkpts.AppendByID(bkpt_sp->GetID()); + } + } + return true; +} + +void SBTarget::GetBreakpointNames(SBStringList &names) { + LLDB_INSTRUMENT_VA(this, names); + + names.Clear(); + + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + + std::vector<std::string> name_vec; + target_sp->GetBreakpointNames(name_vec); + for (const auto &name : name_vec) + names.AppendString(name.c_str()); + } +} + +void SBTarget::DeleteBreakpointName(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + target_sp->DeleteBreakpointName(ConstString(name)); + } +} + +bool SBTarget::EnableAllBreakpoints() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + target_sp->EnableAllowedBreakpoints(); + return true; + } + return false; +} + +bool SBTarget::DisableAllBreakpoints() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + target_sp->DisableAllowedBreakpoints(); + return true; + } + return false; +} + +bool SBTarget::DeleteAllBreakpoints() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + target_sp->RemoveAllowedBreakpoints(); + return true; + } + return false; +} + +lldb::SBError SBTarget::BreakpointsCreateFromFile(SBFileSpec &source_file, + SBBreakpointList &new_bps) { + LLDB_INSTRUMENT_VA(this, source_file, new_bps); + + SBStringList empty_name_list; + return BreakpointsCreateFromFile(source_file, empty_name_list, new_bps); +} + +lldb::SBError SBTarget::BreakpointsCreateFromFile(SBFileSpec &source_file, + SBStringList &matching_names, + SBBreakpointList &new_bps) { + LLDB_INSTRUMENT_VA(this, source_file, matching_names, new_bps); + + SBError sberr; + TargetSP target_sp(GetSP()); + if (!target_sp) { + sberr.SetErrorString( + "BreakpointCreateFromFile called with invalid target."); + return sberr; + } + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + + BreakpointIDList bp_ids; + + std::vector<std::string> name_vector; + size_t num_names = matching_names.GetSize(); + for (size_t i = 0; i < num_names; i++) + name_vector.push_back(matching_names.GetStringAtIndex(i)); + + sberr.ref() = target_sp->CreateBreakpointsFromFile(source_file.ref(), + name_vector, bp_ids); + if (sberr.Fail()) + return sberr; + + size_t num_bkpts = bp_ids.GetSize(); + for (size_t i = 0; i < num_bkpts; i++) { + BreakpointID bp_id = bp_ids.GetBreakpointIDAtIndex(i); + new_bps.AppendByID(bp_id.GetBreakpointID()); + } + return sberr; +} + +lldb::SBError SBTarget::BreakpointsWriteToFile(SBFileSpec &dest_file) { + LLDB_INSTRUMENT_VA(this, dest_file); + + SBError sberr; + TargetSP target_sp(GetSP()); + if (!target_sp) { + sberr.SetErrorString("BreakpointWriteToFile called with invalid target."); + return sberr; + } + SBBreakpointList bkpt_list(*this); + return BreakpointsWriteToFile(dest_file, bkpt_list); +} + +lldb::SBError SBTarget::BreakpointsWriteToFile(SBFileSpec &dest_file, + SBBreakpointList &bkpt_list, + bool append) { + LLDB_INSTRUMENT_VA(this, dest_file, bkpt_list, append); + + SBError sberr; + TargetSP target_sp(GetSP()); + if (!target_sp) { + sberr.SetErrorString("BreakpointWriteToFile called with invalid target."); + return sberr; + } + + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + BreakpointIDList bp_id_list; + bkpt_list.CopyToBreakpointIDList(bp_id_list); + sberr.ref() = target_sp->SerializeBreakpointsToFile(dest_file.ref(), + bp_id_list, append); + return sberr; +} + +uint32_t SBTarget::GetNumWatchpoints() const { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) { + // The watchpoint list is thread safe, no need to lock + return target_sp->GetWatchpointList().GetSize(); + } + return 0; +} + +SBWatchpoint SBTarget::GetWatchpointAtIndex(uint32_t idx) const { + LLDB_INSTRUMENT_VA(this, idx); + + SBWatchpoint sb_watchpoint; + TargetSP target_sp(GetSP()); + if (target_sp) { + // The watchpoint list is thread safe, no need to lock + sb_watchpoint.SetSP(target_sp->GetWatchpointList().GetByIndex(idx)); + } + return sb_watchpoint; +} + +bool SBTarget::DeleteWatchpoint(watch_id_t wp_id) { + LLDB_INSTRUMENT_VA(this, wp_id); + + bool result = false; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + std::unique_lock<std::recursive_mutex> lock; + target_sp->GetWatchpointList().GetListMutex(lock); + result = target_sp->RemoveWatchpointByID(wp_id); + } + + return result; +} + +SBWatchpoint SBTarget::FindWatchpointByID(lldb::watch_id_t wp_id) { + LLDB_INSTRUMENT_VA(this, wp_id); + + SBWatchpoint sb_watchpoint; + lldb::WatchpointSP watchpoint_sp; + TargetSP target_sp(GetSP()); + if (target_sp && wp_id != LLDB_INVALID_WATCH_ID) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + std::unique_lock<std::recursive_mutex> lock; + target_sp->GetWatchpointList().GetListMutex(lock); + watchpoint_sp = target_sp->GetWatchpointList().FindByID(wp_id); + sb_watchpoint.SetSP(watchpoint_sp); + } + + return sb_watchpoint; +} + +lldb::SBWatchpoint SBTarget::WatchAddress(lldb::addr_t addr, size_t size, + bool read, bool modify, + SBError &error) { + LLDB_INSTRUMENT_VA(this, addr, size, read, write, error); + + SBWatchpointOptions options; + options.SetWatchpointTypeRead(read); + options.SetWatchpointTypeWrite(eWatchpointWriteTypeOnModify); + return WatchpointCreateByAddress(addr, size, options, error); +} + +lldb::SBWatchpoint +SBTarget::WatchpointCreateByAddress(lldb::addr_t addr, size_t size, + SBWatchpointOptions options, + SBError &error) { + LLDB_INSTRUMENT_VA(this, addr, size, options, error); + + SBWatchpoint sb_watchpoint; + lldb::WatchpointSP watchpoint_sp; + TargetSP target_sp(GetSP()); + uint32_t watch_type = 0; + if (options.GetWatchpointTypeRead()) + watch_type |= LLDB_WATCH_TYPE_READ; + if (options.GetWatchpointTypeWrite() == eWatchpointWriteTypeAlways) + watch_type |= LLDB_WATCH_TYPE_WRITE; + if (options.GetWatchpointTypeWrite() == eWatchpointWriteTypeOnModify) + watch_type |= LLDB_WATCH_TYPE_MODIFY; + if (watch_type == 0) { + error.SetErrorString("Can't create a watchpoint that is neither read nor " + "write nor modify."); + return sb_watchpoint; + } + if (target_sp && addr != LLDB_INVALID_ADDRESS && size > 0) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + // Target::CreateWatchpoint() is thread safe. + Status cw_error; + // This API doesn't take in a type, so we can't figure out what it is. + CompilerType *type = nullptr; + watchpoint_sp = + target_sp->CreateWatchpoint(addr, size, type, watch_type, cw_error); + error.SetError(cw_error); + sb_watchpoint.SetSP(watchpoint_sp); + } + + return sb_watchpoint; +} + +bool SBTarget::EnableAllWatchpoints() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + std::unique_lock<std::recursive_mutex> lock; + target_sp->GetWatchpointList().GetListMutex(lock); + target_sp->EnableAllWatchpoints(); + return true; + } + return false; +} + +bool SBTarget::DisableAllWatchpoints() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + std::unique_lock<std::recursive_mutex> lock; + target_sp->GetWatchpointList().GetListMutex(lock); + target_sp->DisableAllWatchpoints(); + return true; + } + return false; +} + +SBValue SBTarget::CreateValueFromAddress(const char *name, SBAddress addr, + SBType type) { + LLDB_INSTRUMENT_VA(this, name, addr, type); + + SBValue sb_value; + lldb::ValueObjectSP new_value_sp; + if (IsValid() && name && *name && addr.IsValid() && type.IsValid()) { + lldb::addr_t load_addr(addr.GetLoadAddress(*this)); + ExecutionContext exe_ctx( + ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false))); + CompilerType ast_type(type.GetSP()->GetCompilerType(true)); + new_value_sp = ValueObject::CreateValueObjectFromAddress(name, load_addr, + exe_ctx, ast_type); + } + sb_value.SetSP(new_value_sp); + return sb_value; +} + +lldb::SBValue SBTarget::CreateValueFromData(const char *name, lldb::SBData data, + lldb::SBType type) { + LLDB_INSTRUMENT_VA(this, name, data, type); + + SBValue sb_value; + lldb::ValueObjectSP new_value_sp; + if (IsValid() && name && *name && data.IsValid() && type.IsValid()) { + DataExtractorSP extractor(*data); + ExecutionContext exe_ctx( + ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false))); + CompilerType ast_type(type.GetSP()->GetCompilerType(true)); + new_value_sp = ValueObject::CreateValueObjectFromData(name, *extractor, + exe_ctx, ast_type); + } + sb_value.SetSP(new_value_sp); + return sb_value; +} + +lldb::SBValue SBTarget::CreateValueFromExpression(const char *name, + const char *expr) { + LLDB_INSTRUMENT_VA(this, name, expr); + + SBValue sb_value; + lldb::ValueObjectSP new_value_sp; + if (IsValid() && name && *name && expr && *expr) { + ExecutionContext exe_ctx( + ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false))); + new_value_sp = + ValueObject::CreateValueObjectFromExpression(name, expr, exe_ctx); + } + sb_value.SetSP(new_value_sp); + return sb_value; +} + +bool SBTarget::DeleteAllWatchpoints() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + std::unique_lock<std::recursive_mutex> lock; + target_sp->GetWatchpointList().GetListMutex(lock); + target_sp->RemoveAllWatchpoints(); + return true; + } + return false; +} + +void SBTarget::AppendImageSearchPath(const char *from, const char *to, + lldb::SBError &error) { + LLDB_INSTRUMENT_VA(this, from, to, error); + + TargetSP target_sp(GetSP()); + if (!target_sp) + return error.SetErrorString("invalid target"); + + llvm::StringRef srFrom = from, srTo = to; + if (srFrom.empty()) + return error.SetErrorString("<from> path can't be empty"); + if (srTo.empty()) + return error.SetErrorString("<to> path can't be empty"); + + target_sp->GetImageSearchPathList().Append(srFrom, srTo, true); +} + +lldb::SBModule SBTarget::AddModule(const char *path, const char *triple, + const char *uuid_cstr) { + LLDB_INSTRUMENT_VA(this, path, triple, uuid_cstr); + + return AddModule(path, triple, uuid_cstr, nullptr); +} + +lldb::SBModule SBTarget::AddModule(const char *path, const char *triple, + const char *uuid_cstr, const char *symfile) { + LLDB_INSTRUMENT_VA(this, path, triple, uuid_cstr, symfile); + + TargetSP target_sp(GetSP()); + if (!target_sp) + return {}; + + ModuleSpec module_spec; + if (path) + module_spec.GetFileSpec().SetFile(path, FileSpec::Style::native); + + if (uuid_cstr) + module_spec.GetUUID().SetFromStringRef(uuid_cstr); + + if (triple) + module_spec.GetArchitecture() = + Platform::GetAugmentedArchSpec(target_sp->GetPlatform().get(), triple); + else + module_spec.GetArchitecture() = target_sp->GetArchitecture(); + + if (symfile) + module_spec.GetSymbolFileSpec().SetFile(symfile, FileSpec::Style::native); + + SBModuleSpec sb_modulespec(module_spec); + + return AddModule(sb_modulespec); +} + +lldb::SBModule SBTarget::AddModule(const SBModuleSpec &module_spec) { + LLDB_INSTRUMENT_VA(this, module_spec); + + lldb::SBModule sb_module; + TargetSP target_sp(GetSP()); + if (target_sp) { + sb_module.SetSP(target_sp->GetOrCreateModule(*module_spec.m_opaque_up, + true /* notify */)); + if (!sb_module.IsValid() && module_spec.m_opaque_up->GetUUID().IsValid()) { + Status error; + if (PluginManager::DownloadObjectAndSymbolFile(*module_spec.m_opaque_up, + error, + /* force_lookup */ true)) { + if (FileSystem::Instance().Exists( + module_spec.m_opaque_up->GetFileSpec())) { + sb_module.SetSP(target_sp->GetOrCreateModule(*module_spec.m_opaque_up, + true /* notify */)); + } + } + } + } + // If the target hasn't initialized any architecture yet, use the + // binary's architecture. + if (sb_module.IsValid() && !target_sp->GetArchitecture().IsValid() && + sb_module.GetSP()->GetArchitecture().IsValid()) + target_sp->SetArchitecture(sb_module.GetSP()->GetArchitecture()); + return sb_module; +} + +bool SBTarget::AddModule(lldb::SBModule &module) { + LLDB_INSTRUMENT_VA(this, module); + + TargetSP target_sp(GetSP()); + if (target_sp) { + target_sp->GetImages().AppendIfNeeded(module.GetSP()); + return true; + } + return false; +} + +uint32_t SBTarget::GetNumModules() const { + LLDB_INSTRUMENT_VA(this); + + uint32_t num = 0; + TargetSP target_sp(GetSP()); + if (target_sp) { + // The module list is thread safe, no need to lock + num = target_sp->GetImages().GetSize(); + } + + return num; +} + +void SBTarget::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_sp.reset(); +} + +SBModule SBTarget::FindModule(const SBFileSpec &sb_file_spec) { + LLDB_INSTRUMENT_VA(this, sb_file_spec); + + SBModule sb_module; + TargetSP target_sp(GetSP()); + if (target_sp && sb_file_spec.IsValid()) { + ModuleSpec module_spec(*sb_file_spec); + // The module list is thread safe, no need to lock + sb_module.SetSP(target_sp->GetImages().FindFirstModule(module_spec)); + } + return sb_module; +} + +SBSymbolContextList SBTarget::FindCompileUnits(const SBFileSpec &sb_file_spec) { + LLDB_INSTRUMENT_VA(this, sb_file_spec); + + SBSymbolContextList sb_sc_list; + const TargetSP target_sp(GetSP()); + if (target_sp && sb_file_spec.IsValid()) + target_sp->GetImages().FindCompileUnits(*sb_file_spec, *sb_sc_list); + return sb_sc_list; +} + +lldb::ByteOrder SBTarget::GetByteOrder() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) + return target_sp->GetArchitecture().GetByteOrder(); + return eByteOrderInvalid; +} + +const char *SBTarget::GetTriple() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (!target_sp) + return nullptr; + + std::string triple(target_sp->GetArchitecture().GetTriple().str()); + // Unique the string so we don't run into ownership issues since the const + // strings put the string into the string pool once and the strings never + // comes out + ConstString const_triple(triple.c_str()); + return const_triple.GetCString(); +} + +const char *SBTarget::GetABIName() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (!target_sp) + return nullptr; + + std::string abi_name(target_sp->GetABIName().str()); + ConstString const_name(abi_name.c_str()); + return const_name.GetCString(); +} + +const char *SBTarget::GetLabel() const { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (!target_sp) + return nullptr; + + return ConstString(target_sp->GetLabel().data()).AsCString(); +} + +SBError SBTarget::SetLabel(const char *label) { + LLDB_INSTRUMENT_VA(this, label); + + TargetSP target_sp(GetSP()); + if (!target_sp) + return Status("Couldn't get internal target object."); + + return Status(target_sp->SetLabel(label)); +} + +uint32_t SBTarget::GetDataByteSize() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) { + return target_sp->GetArchitecture().GetDataByteSize(); + } + return 0; +} + +uint32_t SBTarget::GetCodeByteSize() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) { + return target_sp->GetArchitecture().GetCodeByteSize(); + } + return 0; +} + +uint32_t SBTarget::GetMaximumNumberOfChildrenToDisplay() const { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if(target_sp){ + return target_sp->GetMaximumNumberOfChildrenToDisplay(); + } + return 0; +} + +uint32_t SBTarget::GetAddressByteSize() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) + return target_sp->GetArchitecture().GetAddressByteSize(); + return sizeof(void *); +} + +SBModule SBTarget::GetModuleAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBModule sb_module; + ModuleSP module_sp; + TargetSP target_sp(GetSP()); + if (target_sp) { + // The module list is thread safe, no need to lock + module_sp = target_sp->GetImages().GetModuleAtIndex(idx); + sb_module.SetSP(module_sp); + } + + return sb_module; +} + +bool SBTarget::RemoveModule(lldb::SBModule module) { + LLDB_INSTRUMENT_VA(this, module); + + TargetSP target_sp(GetSP()); + if (target_sp) + return target_sp->GetImages().Remove(module.GetSP()); + return false; +} + +SBBroadcaster SBTarget::GetBroadcaster() const { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + SBBroadcaster broadcaster(target_sp.get(), false); + + return broadcaster; +} + +bool SBTarget::GetDescription(SBStream &description, + lldb::DescriptionLevel description_level) { + LLDB_INSTRUMENT_VA(this, description, description_level); + + Stream &strm = description.ref(); + + TargetSP target_sp(GetSP()); + if (target_sp) { + target_sp->Dump(&strm, description_level); + } else + strm.PutCString("No value"); + + return true; +} + +lldb::SBSymbolContextList SBTarget::FindFunctions(const char *name, + uint32_t name_type_mask) { + LLDB_INSTRUMENT_VA(this, name, name_type_mask); + + lldb::SBSymbolContextList sb_sc_list; + if (!name || !name[0]) + return sb_sc_list; + + TargetSP target_sp(GetSP()); + if (!target_sp) + return sb_sc_list; + + ModuleFunctionSearchOptions function_options; + function_options.include_symbols = true; + function_options.include_inlines = true; + + FunctionNameType mask = static_cast<FunctionNameType>(name_type_mask); + target_sp->GetImages().FindFunctions(ConstString(name), mask, + function_options, *sb_sc_list); + return sb_sc_list; +} + +lldb::SBSymbolContextList SBTarget::FindGlobalFunctions(const char *name, + uint32_t max_matches, + MatchType matchtype) { + LLDB_INSTRUMENT_VA(this, name, max_matches, matchtype); + + lldb::SBSymbolContextList sb_sc_list; + if (name && name[0]) { + llvm::StringRef name_ref(name); + TargetSP target_sp(GetSP()); + if (target_sp) { + ModuleFunctionSearchOptions function_options; + function_options.include_symbols = true; + function_options.include_inlines = true; + + std::string regexstr; + switch (matchtype) { + case eMatchTypeRegex: + target_sp->GetImages().FindFunctions(RegularExpression(name_ref), + function_options, *sb_sc_list); + break; + case eMatchTypeRegexInsensitive: + target_sp->GetImages().FindFunctions( + RegularExpression(name_ref, llvm::Regex::RegexFlags::IgnoreCase), + function_options, *sb_sc_list); + break; + case eMatchTypeStartsWith: + regexstr = llvm::Regex::escape(name) + ".*"; + target_sp->GetImages().FindFunctions(RegularExpression(regexstr), + function_options, *sb_sc_list); + break; + default: + target_sp->GetImages().FindFunctions(ConstString(name), + eFunctionNameTypeAny, + function_options, *sb_sc_list); + break; + } + } + } + return sb_sc_list; +} + +lldb::SBType SBTarget::FindFirstType(const char *typename_cstr) { + LLDB_INSTRUMENT_VA(this, typename_cstr); + + TargetSP target_sp(GetSP()); + if (typename_cstr && typename_cstr[0] && target_sp) { + ConstString const_typename(typename_cstr); + TypeQuery query(const_typename.GetStringRef(), + TypeQueryOptions::e_find_one); + TypeResults results; + target_sp->GetImages().FindTypes(/*search_first=*/nullptr, query, results); + TypeSP type_sp = results.GetFirstType(); + if (type_sp) + return SBType(type_sp); + // Didn't find the type in the symbols; Try the loaded language runtimes. + if (auto process_sp = target_sp->GetProcessSP()) { + for (auto *runtime : process_sp->GetLanguageRuntimes()) { + if (auto vendor = runtime->GetDeclVendor()) { + auto types = vendor->FindTypes(const_typename, /*max_matches*/ 1); + if (!types.empty()) + return SBType(types.front()); + } + } + } + + // No matches, search for basic typename matches. + for (auto type_system_sp : target_sp->GetScratchTypeSystems()) + if (auto type = type_system_sp->GetBuiltinTypeByName(const_typename)) + return SBType(type); + } + + return SBType(); +} + +SBType SBTarget::GetBasicType(lldb::BasicType type) { + LLDB_INSTRUMENT_VA(this, type); + + TargetSP target_sp(GetSP()); + if (target_sp) { + for (auto type_system_sp : target_sp->GetScratchTypeSystems()) + if (auto compiler_type = type_system_sp->GetBasicTypeFromAST(type)) + return SBType(compiler_type); + } + return SBType(); +} + +lldb::SBTypeList SBTarget::FindTypes(const char *typename_cstr) { + LLDB_INSTRUMENT_VA(this, typename_cstr); + + SBTypeList sb_type_list; + TargetSP target_sp(GetSP()); + if (typename_cstr && typename_cstr[0] && target_sp) { + ModuleList &images = target_sp->GetImages(); + ConstString const_typename(typename_cstr); + TypeQuery query(typename_cstr); + TypeResults results; + images.FindTypes(nullptr, query, results); + for (const TypeSP &type_sp : results.GetTypeMap().Types()) + sb_type_list.Append(SBType(type_sp)); + + // Try the loaded language runtimes + if (auto process_sp = target_sp->GetProcessSP()) { + for (auto *runtime : process_sp->GetLanguageRuntimes()) { + if (auto *vendor = runtime->GetDeclVendor()) { + auto types = + vendor->FindTypes(const_typename, /*max_matches*/ UINT32_MAX); + for (auto type : types) + sb_type_list.Append(SBType(type)); + } + } + } + + if (sb_type_list.GetSize() == 0) { + // No matches, search for basic typename matches + for (auto type_system_sp : target_sp->GetScratchTypeSystems()) + if (auto compiler_type = + type_system_sp->GetBuiltinTypeByName(const_typename)) + sb_type_list.Append(SBType(compiler_type)); + } + } + return sb_type_list; +} + +SBValueList SBTarget::FindGlobalVariables(const char *name, + uint32_t max_matches) { + LLDB_INSTRUMENT_VA(this, name, max_matches); + + SBValueList sb_value_list; + + TargetSP target_sp(GetSP()); + if (name && target_sp) { + VariableList variable_list; + target_sp->GetImages().FindGlobalVariables(ConstString(name), max_matches, + variable_list); + if (!variable_list.Empty()) { + ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get(); + if (exe_scope == nullptr) + exe_scope = target_sp.get(); + for (const VariableSP &var_sp : variable_list) { + lldb::ValueObjectSP valobj_sp( + ValueObjectVariable::Create(exe_scope, var_sp)); + if (valobj_sp) + sb_value_list.Append(SBValue(valobj_sp)); + } + } + } + + return sb_value_list; +} + +SBValueList SBTarget::FindGlobalVariables(const char *name, + uint32_t max_matches, + MatchType matchtype) { + LLDB_INSTRUMENT_VA(this, name, max_matches, matchtype); + + SBValueList sb_value_list; + + TargetSP target_sp(GetSP()); + if (name && target_sp) { + llvm::StringRef name_ref(name); + VariableList variable_list; + + std::string regexstr; + switch (matchtype) { + case eMatchTypeNormal: + target_sp->GetImages().FindGlobalVariables(ConstString(name), max_matches, + variable_list); + break; + case eMatchTypeRegex: + target_sp->GetImages().FindGlobalVariables(RegularExpression(name_ref), + max_matches, variable_list); + break; + case eMatchTypeRegexInsensitive: + target_sp->GetImages().FindGlobalVariables( + RegularExpression(name_ref, llvm::Regex::IgnoreCase), max_matches, + variable_list); + break; + case eMatchTypeStartsWith: + regexstr = "^" + llvm::Regex::escape(name) + ".*"; + target_sp->GetImages().FindGlobalVariables(RegularExpression(regexstr), + max_matches, variable_list); + break; + } + if (!variable_list.Empty()) { + ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get(); + if (exe_scope == nullptr) + exe_scope = target_sp.get(); + for (const VariableSP &var_sp : variable_list) { + lldb::ValueObjectSP valobj_sp( + ValueObjectVariable::Create(exe_scope, var_sp)); + if (valobj_sp) + sb_value_list.Append(SBValue(valobj_sp)); + } + } + } + + return sb_value_list; +} + +lldb::SBValue SBTarget::FindFirstGlobalVariable(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + + SBValueList sb_value_list(FindGlobalVariables(name, 1)); + if (sb_value_list.IsValid() && sb_value_list.GetSize() > 0) + return sb_value_list.GetValueAtIndex(0); + return SBValue(); +} + +SBSourceManager SBTarget::GetSourceManager() { + LLDB_INSTRUMENT_VA(this); + + SBSourceManager source_manager(*this); + return source_manager; +} + +lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr, + uint32_t count) { + LLDB_INSTRUMENT_VA(this, base_addr, count); + + return ReadInstructions(base_addr, count, nullptr); +} + +lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr, + uint32_t count, + const char *flavor_string) { + LLDB_INSTRUMENT_VA(this, base_addr, count, flavor_string); + + SBInstructionList sb_instructions; + + TargetSP target_sp(GetSP()); + if (target_sp) { + Address *addr_ptr = base_addr.get(); + + if (addr_ptr) { + DataBufferHeap data( + target_sp->GetArchitecture().GetMaximumOpcodeByteSize() * count, 0); + bool force_live_memory = true; + lldb_private::Status error; + lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; + const size_t bytes_read = + target_sp->ReadMemory(*addr_ptr, data.GetBytes(), data.GetByteSize(), + error, force_live_memory, &load_addr); + const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS; + sb_instructions.SetDisassembler(Disassembler::DisassembleBytes( + target_sp->GetArchitecture(), nullptr, flavor_string, *addr_ptr, + data.GetBytes(), bytes_read, count, data_from_file)); + } + } + + return sb_instructions; +} + +lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress start_addr, + lldb::SBAddress end_addr, + const char *flavor_string) { + LLDB_INSTRUMENT_VA(this, start_addr, end_addr, flavor_string); + + SBInstructionList sb_instructions; + + TargetSP target_sp(GetSP()); + if (target_sp) { + lldb::addr_t start_load_addr = start_addr.GetLoadAddress(*this); + lldb::addr_t end_load_addr = end_addr.GetLoadAddress(*this); + if (end_load_addr > start_load_addr) { + lldb::addr_t size = end_load_addr - start_load_addr; + + AddressRange range(start_load_addr, size); + const bool force_live_memory = true; + sb_instructions.SetDisassembler(Disassembler::DisassembleRange( + target_sp->GetArchitecture(), nullptr, flavor_string, *target_sp, + range, force_live_memory)); + } + } + return sb_instructions; +} + +lldb::SBInstructionList SBTarget::GetInstructions(lldb::SBAddress base_addr, + const void *buf, + size_t size) { + LLDB_INSTRUMENT_VA(this, base_addr, buf, size); + + return GetInstructionsWithFlavor(base_addr, nullptr, buf, size); +} + +lldb::SBInstructionList +SBTarget::GetInstructionsWithFlavor(lldb::SBAddress base_addr, + const char *flavor_string, const void *buf, + size_t size) { + LLDB_INSTRUMENT_VA(this, base_addr, flavor_string, buf, size); + + SBInstructionList sb_instructions; + + TargetSP target_sp(GetSP()); + if (target_sp) { + Address addr; + + if (base_addr.get()) + addr = *base_addr.get(); + + const bool data_from_file = true; + + sb_instructions.SetDisassembler(Disassembler::DisassembleBytes( + target_sp->GetArchitecture(), nullptr, flavor_string, addr, buf, size, + UINT32_MAX, data_from_file)); + } + + return sb_instructions; +} + +lldb::SBInstructionList SBTarget::GetInstructions(lldb::addr_t base_addr, + const void *buf, + size_t size) { + LLDB_INSTRUMENT_VA(this, base_addr, buf, size); + + return GetInstructionsWithFlavor(ResolveLoadAddress(base_addr), nullptr, buf, + size); +} + +lldb::SBInstructionList +SBTarget::GetInstructionsWithFlavor(lldb::addr_t base_addr, + const char *flavor_string, const void *buf, + size_t size) { + LLDB_INSTRUMENT_VA(this, base_addr, flavor_string, buf, size); + + return GetInstructionsWithFlavor(ResolveLoadAddress(base_addr), flavor_string, + buf, size); +} + +SBError SBTarget::SetSectionLoadAddress(lldb::SBSection section, + lldb::addr_t section_base_addr) { + LLDB_INSTRUMENT_VA(this, section, section_base_addr); + + SBError sb_error; + TargetSP target_sp(GetSP()); + if (target_sp) { + if (!section.IsValid()) { + sb_error.SetErrorStringWithFormat("invalid section"); + } else { + SectionSP section_sp(section.GetSP()); + if (section_sp) { + if (section_sp->IsThreadSpecific()) { + sb_error.SetErrorString( + "thread specific sections are not yet supported"); + } else { + ProcessSP process_sp(target_sp->GetProcessSP()); + if (target_sp->SetSectionLoadAddress(section_sp, section_base_addr)) { + ModuleSP module_sp(section_sp->GetModule()); + if (module_sp) { + ModuleList module_list; + module_list.Append(module_sp); + target_sp->ModulesDidLoad(module_list); + } + // Flush info in the process (stack frames, etc) + if (process_sp) + process_sp->Flush(); + } + } + } + } + } else { + sb_error.SetErrorString("invalid target"); + } + return sb_error; +} + +SBError SBTarget::ClearSectionLoadAddress(lldb::SBSection section) { + LLDB_INSTRUMENT_VA(this, section); + + SBError sb_error; + + TargetSP target_sp(GetSP()); + if (target_sp) { + if (!section.IsValid()) { + sb_error.SetErrorStringWithFormat("invalid section"); + } else { + SectionSP section_sp(section.GetSP()); + if (section_sp) { + ProcessSP process_sp(target_sp->GetProcessSP()); + if (target_sp->SetSectionUnloaded(section_sp)) { + ModuleSP module_sp(section_sp->GetModule()); + if (module_sp) { + ModuleList module_list; + module_list.Append(module_sp); + target_sp->ModulesDidUnload(module_list, false); + } + // Flush info in the process (stack frames, etc) + if (process_sp) + process_sp->Flush(); + } + } else { + sb_error.SetErrorStringWithFormat("invalid section"); + } + } + } else { + sb_error.SetErrorStringWithFormat("invalid target"); + } + return sb_error; +} + +SBError SBTarget::SetModuleLoadAddress(lldb::SBModule module, + int64_t slide_offset) { + LLDB_INSTRUMENT_VA(this, module, slide_offset); + + if (slide_offset < 0) { + SBError sb_error; + sb_error.SetErrorStringWithFormat("slide must be positive"); + return sb_error; + } + + return SetModuleLoadAddress(module, static_cast<uint64_t>(slide_offset)); +} + +SBError SBTarget::SetModuleLoadAddress(lldb::SBModule module, + uint64_t slide_offset) { + + SBError sb_error; + + TargetSP target_sp(GetSP()); + if (target_sp) { + ModuleSP module_sp(module.GetSP()); + if (module_sp) { + bool changed = false; + if (module_sp->SetLoadAddress(*target_sp, slide_offset, true, changed)) { + // The load was successful, make sure that at least some sections + // changed before we notify that our module was loaded. + if (changed) { + ModuleList module_list; + module_list.Append(module_sp); + target_sp->ModulesDidLoad(module_list); + // Flush info in the process (stack frames, etc) + ProcessSP process_sp(target_sp->GetProcessSP()); + if (process_sp) + process_sp->Flush(); + } + } + } else { + sb_error.SetErrorStringWithFormat("invalid module"); + } + + } else { + sb_error.SetErrorStringWithFormat("invalid target"); + } + return sb_error; +} + +SBError SBTarget::ClearModuleLoadAddress(lldb::SBModule module) { + LLDB_INSTRUMENT_VA(this, module); + + SBError sb_error; + + char path[PATH_MAX]; + TargetSP target_sp(GetSP()); + if (target_sp) { + ModuleSP module_sp(module.GetSP()); + if (module_sp) { + ObjectFile *objfile = module_sp->GetObjectFile(); + if (objfile) { + SectionList *section_list = objfile->GetSectionList(); + if (section_list) { + ProcessSP process_sp(target_sp->GetProcessSP()); + + bool changed = false; + const size_t num_sections = section_list->GetSize(); + for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) { + SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx)); + if (section_sp) + changed |= target_sp->SetSectionUnloaded(section_sp); + } + if (changed) { + ModuleList module_list; + module_list.Append(module_sp); + target_sp->ModulesDidUnload(module_list, false); + // Flush info in the process (stack frames, etc) + ProcessSP process_sp(target_sp->GetProcessSP()); + if (process_sp) + process_sp->Flush(); + } + } else { + module_sp->GetFileSpec().GetPath(path, sizeof(path)); + sb_error.SetErrorStringWithFormat("no sections in object file '%s'", + path); + } + } else { + module_sp->GetFileSpec().GetPath(path, sizeof(path)); + sb_error.SetErrorStringWithFormat("no object file for module '%s'", + path); + } + } else { + sb_error.SetErrorStringWithFormat("invalid module"); + } + } else { + sb_error.SetErrorStringWithFormat("invalid target"); + } + return sb_error; +} + +lldb::SBSymbolContextList SBTarget::FindSymbols(const char *name, + lldb::SymbolType symbol_type) { + LLDB_INSTRUMENT_VA(this, name, symbol_type); + + SBSymbolContextList sb_sc_list; + if (name && name[0]) { + TargetSP target_sp(GetSP()); + if (target_sp) + target_sp->GetImages().FindSymbolsWithNameAndType( + ConstString(name), symbol_type, *sb_sc_list); + } + return sb_sc_list; +} + +lldb::SBValue SBTarget::EvaluateExpression(const char *expr) { + LLDB_INSTRUMENT_VA(this, expr); + + TargetSP target_sp(GetSP()); + if (!target_sp) + return SBValue(); + + SBExpressionOptions options; + lldb::DynamicValueType fetch_dynamic_value = + target_sp->GetPreferDynamicValue(); + options.SetFetchDynamicValue(fetch_dynamic_value); + options.SetUnwindOnError(true); + return EvaluateExpression(expr, options); +} + +lldb::SBValue SBTarget::EvaluateExpression(const char *expr, + const SBExpressionOptions &options) { + LLDB_INSTRUMENT_VA(this, expr, options); + + Log *expr_log = GetLog(LLDBLog::Expressions); + SBValue expr_result; + ValueObjectSP expr_value_sp; + TargetSP target_sp(GetSP()); + StackFrame *frame = nullptr; + if (target_sp) { + if (expr == nullptr || expr[0] == '\0') { + return expr_result; + } + + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + ExecutionContext exe_ctx(m_opaque_sp.get()); + + frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + + if (target) { + // If we have a process, make sure to lock the runlock: + if (process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + target->EvaluateExpression(expr, frame, expr_value_sp, options.ref()); + } else { + Status error; + error.SetErrorString("can't evaluate expressions when the " + "process is running."); + expr_value_sp = ValueObjectConstResult::Create(nullptr, error); + } + } else { + target->EvaluateExpression(expr, frame, expr_value_sp, options.ref()); + } + + expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue()); + } + } + LLDB_LOGF(expr_log, + "** [SBTarget::EvaluateExpression] Expression result is " + "%s, summary %s **", + expr_result.GetValue(), expr_result.GetSummary()); + return expr_result; +} + +lldb::addr_t SBTarget::GetStackRedZoneSize() { + LLDB_INSTRUMENT_VA(this); + + TargetSP target_sp(GetSP()); + if (target_sp) { + ABISP abi_sp; + ProcessSP process_sp(target_sp->GetProcessSP()); + if (process_sp) + abi_sp = process_sp->GetABI(); + else + abi_sp = ABI::FindPlugin(ProcessSP(), target_sp->GetArchitecture()); + if (abi_sp) + return abi_sp->GetRedZoneSize(); + } + return 0; +} + +bool SBTarget::IsLoaded(const SBModule &module) const { + LLDB_INSTRUMENT_VA(this, module); + + TargetSP target_sp(GetSP()); + if (!target_sp) + return false; + + ModuleSP module_sp(module.GetSP()); + if (!module_sp) + return false; + + return module_sp->IsLoadedInTarget(target_sp.get()); +} + +lldb::SBLaunchInfo SBTarget::GetLaunchInfo() const { + LLDB_INSTRUMENT_VA(this); + + lldb::SBLaunchInfo launch_info(nullptr); + TargetSP target_sp(GetSP()); + if (target_sp) + launch_info.set_ref(m_opaque_sp->GetProcessLaunchInfo()); + return launch_info; +} + +void SBTarget::SetLaunchInfo(const lldb::SBLaunchInfo &launch_info) { + LLDB_INSTRUMENT_VA(this, launch_info); + + TargetSP target_sp(GetSP()); + if (target_sp) + m_opaque_sp->SetProcessLaunchInfo(launch_info.ref()); +} + +SBEnvironment SBTarget::GetEnvironment() { + LLDB_INSTRUMENT_VA(this); + TargetSP target_sp(GetSP()); + + if (target_sp) { + return SBEnvironment(target_sp->GetEnvironment()); + } + + return SBEnvironment(); +} + +lldb::SBTrace SBTarget::GetTrace() { + LLDB_INSTRUMENT_VA(this); + TargetSP target_sp(GetSP()); + + if (target_sp) + return SBTrace(target_sp->GetTrace()); + + return SBTrace(); +} + +lldb::SBTrace SBTarget::CreateTrace(lldb::SBError &error) { + LLDB_INSTRUMENT_VA(this, error); + TargetSP target_sp(GetSP()); + error.Clear(); + + if (target_sp) { + if (llvm::Expected<lldb::TraceSP> trace_sp = target_sp->CreateTrace()) { + return SBTrace(*trace_sp); + } else { + error.SetErrorString(llvm::toString(trace_sp.takeError()).c_str()); + } + } else { + error.SetErrorString("missing target"); + } + return SBTrace(); +} diff --git a/contrib/llvm-project/lldb/source/API/SBThread.cpp b/contrib/llvm-project/lldb/source/API/SBThread.cpp new file mode 100644 index 000000000000..53643362421d --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBThread.cpp @@ -0,0 +1,1349 @@ +//===-- SBThread.cpp ------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBThread.h" +#include "Utils.h" +#include "lldb/API/SBAddress.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBFileSpec.h" +#include "lldb/API/SBFormat.h" +#include "lldb/API/SBFrame.h" +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStructuredData.h" +#include "lldb/API/SBSymbolContext.h" +#include "lldb/API/SBThreadCollection.h" +#include "lldb/API/SBThreadPlan.h" +#include "lldb/API/SBValue.h" +#include "lldb/Breakpoint/BreakpointLocation.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Core/StructuredDataImpl.h" +#include "lldb/Core/ValueObject.h" +#include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Symbol/CompileUnit.h" +#include "lldb/Symbol/SymbolContext.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/Queue.h" +#include "lldb/Target/StopInfo.h" +#include "lldb/Target/SystemRuntime.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" +#include "lldb/Target/ThreadPlan.h" +#include "lldb/Target/ThreadPlanStepInRange.h" +#include "lldb/Target/ThreadPlanStepInstruction.h" +#include "lldb/Target/ThreadPlanStepOut.h" +#include "lldb/Target/ThreadPlanStepRange.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/State.h" +#include "lldb/Utility/Stream.h" +#include "lldb/Utility/StructuredData.h" +#include "lldb/lldb-enumerations.h" + +#include <memory> + +using namespace lldb; +using namespace lldb_private; + +const char *SBThread::GetBroadcasterClassName() { + LLDB_INSTRUMENT(); + + return ConstString(Thread::GetStaticBroadcasterClass()).AsCString(); +} + +// Constructors +SBThread::SBThread() : m_opaque_sp(new ExecutionContextRef()) { + LLDB_INSTRUMENT_VA(this); +} + +SBThread::SBThread(const ThreadSP &lldb_object_sp) + : m_opaque_sp(new ExecutionContextRef(lldb_object_sp)) { + LLDB_INSTRUMENT_VA(this, lldb_object_sp); +} + +SBThread::SBThread(const SBThread &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_sp = clone(rhs.m_opaque_sp); +} + +// Assignment operator + +const lldb::SBThread &SBThread::operator=(const SBThread &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_sp = clone(rhs.m_opaque_sp); + return *this; +} + +// Destructor +SBThread::~SBThread() = default; + +lldb::SBQueue SBThread::GetQueue() const { + LLDB_INSTRUMENT_VA(this); + + SBQueue sb_queue; + QueueSP queue_sp; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + queue_sp = exe_ctx.GetThreadPtr()->GetQueue(); + if (queue_sp) { + sb_queue.SetQueue(queue_sp); + } + } + } + + return sb_queue; +} + +bool SBThread::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBThread::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) + return m_opaque_sp->GetThreadSP().get() != nullptr; + } + // Without a valid target & process, this thread can't be valid. + return false; +} + +void SBThread::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_sp->Clear(); +} + +StopReason SBThread::GetStopReason() { + LLDB_INSTRUMENT_VA(this); + + StopReason reason = eStopReasonInvalid; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + return exe_ctx.GetThreadPtr()->GetStopReason(); + } + } + + return reason; +} + +size_t SBThread::GetStopReasonDataCount() { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + StopInfoSP stop_info_sp = exe_ctx.GetThreadPtr()->GetStopInfo(); + if (stop_info_sp) { + StopReason reason = stop_info_sp->GetStopReason(); + switch (reason) { + case eStopReasonInvalid: + case eStopReasonNone: + case eStopReasonTrace: + case eStopReasonExec: + case eStopReasonPlanComplete: + case eStopReasonThreadExiting: + case eStopReasonInstrumentation: + case eStopReasonProcessorTrace: + case eStopReasonVForkDone: + // There is no data for these stop reasons. + return 0; + + case eStopReasonBreakpoint: { + break_id_t site_id = stop_info_sp->GetValue(); + lldb::BreakpointSiteSP bp_site_sp( + exe_ctx.GetProcessPtr()->GetBreakpointSiteList().FindByID( + site_id)); + if (bp_site_sp) + return bp_site_sp->GetNumberOfConstituents() * 2; + else + return 0; // Breakpoint must have cleared itself... + } break; + + case eStopReasonWatchpoint: + return 1; + + case eStopReasonSignal: + return 1; + + case eStopReasonException: + return 1; + + case eStopReasonFork: + return 1; + + case eStopReasonVFork: + return 1; + } + } + } + } + return 0; +} + +uint64_t SBThread::GetStopReasonDataAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + Thread *thread = exe_ctx.GetThreadPtr(); + StopInfoSP stop_info_sp = thread->GetStopInfo(); + if (stop_info_sp) { + StopReason reason = stop_info_sp->GetStopReason(); + switch (reason) { + case eStopReasonInvalid: + case eStopReasonNone: + case eStopReasonTrace: + case eStopReasonExec: + case eStopReasonPlanComplete: + case eStopReasonThreadExiting: + case eStopReasonInstrumentation: + case eStopReasonProcessorTrace: + case eStopReasonVForkDone: + // There is no data for these stop reasons. + return 0; + + case eStopReasonBreakpoint: { + break_id_t site_id = stop_info_sp->GetValue(); + lldb::BreakpointSiteSP bp_site_sp( + exe_ctx.GetProcessPtr()->GetBreakpointSiteList().FindByID( + site_id)); + if (bp_site_sp) { + uint32_t bp_index = idx / 2; + BreakpointLocationSP bp_loc_sp( + bp_site_sp->GetConstituentAtIndex(bp_index)); + if (bp_loc_sp) { + if (idx & 1) { + // Odd idx, return the breakpoint location ID + return bp_loc_sp->GetID(); + } else { + // Even idx, return the breakpoint ID + return bp_loc_sp->GetBreakpoint().GetID(); + } + } + } + return LLDB_INVALID_BREAK_ID; + } break; + + case eStopReasonWatchpoint: + return stop_info_sp->GetValue(); + + case eStopReasonSignal: + return stop_info_sp->GetValue(); + + case eStopReasonException: + return stop_info_sp->GetValue(); + + case eStopReasonFork: + return stop_info_sp->GetValue(); + + case eStopReasonVFork: + return stop_info_sp->GetValue(); + } + } + } + } + return 0; +} + +bool SBThread::GetStopReasonExtendedInfoAsJSON(lldb::SBStream &stream) { + LLDB_INSTRUMENT_VA(this, stream); + + Stream &strm = stream.ref(); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) + return false; + + StopInfoSP stop_info = exe_ctx.GetThreadPtr()->GetStopInfo(); + StructuredData::ObjectSP info = stop_info->GetExtendedInfo(); + if (!info) + return false; + + info->Dump(strm); + + return true; +} + +SBThreadCollection +SBThread::GetStopReasonExtendedBacktraces(InstrumentationRuntimeType type) { + LLDB_INSTRUMENT_VA(this, type); + + SBThreadCollection threads; + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) + return SBThreadCollection(); + + ProcessSP process_sp = exe_ctx.GetProcessSP(); + + StopInfoSP stop_info = exe_ctx.GetThreadPtr()->GetStopInfo(); + StructuredData::ObjectSP info = stop_info->GetExtendedInfo(); + if (!info) + return threads; + + threads = process_sp->GetInstrumentationRuntime(type) + ->GetBacktracesFromExtendedStopInfo(info); + return threads; +} + +size_t SBThread::GetStopDescription(char *dst, size_t dst_len) { + LLDB_INSTRUMENT_VA(this, dst, dst_len); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (dst) + *dst = 0; + + if (!exe_ctx.HasThreadScope()) + return 0; + + Process::StopLocker stop_locker; + if (!stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) + return 0; + + std::string thread_stop_desc = exe_ctx.GetThreadPtr()->GetStopDescription(); + if (thread_stop_desc.empty()) + return 0; + + if (dst) + return ::snprintf(dst, dst_len, "%s", thread_stop_desc.c_str()) + 1; + + // NULL dst passed in, return the length needed to contain the + // description. + return thread_stop_desc.size() + 1; // Include the NULL byte for size +} + +SBValue SBThread::GetStopReturnValue() { + LLDB_INSTRUMENT_VA(this); + + ValueObjectSP return_valobj_sp; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + StopInfoSP stop_info_sp = exe_ctx.GetThreadPtr()->GetStopInfo(); + if (stop_info_sp) { + return_valobj_sp = StopInfo::GetReturnValueObject(stop_info_sp); + } + } + } + + return SBValue(return_valobj_sp); +} + +void SBThread::SetThread(const ThreadSP &lldb_object_sp) { + m_opaque_sp->SetThreadSP(lldb_object_sp); +} + +lldb::tid_t SBThread::GetThreadID() const { + LLDB_INSTRUMENT_VA(this); + + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (thread_sp) + return thread_sp->GetID(); + return LLDB_INVALID_THREAD_ID; +} + +uint32_t SBThread::GetIndexID() const { + LLDB_INSTRUMENT_VA(this); + + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (thread_sp) + return thread_sp->GetIndexID(); + return LLDB_INVALID_INDEX32; +} + +const char *SBThread::GetName() const { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) + return nullptr; + + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) + return ConstString(exe_ctx.GetThreadPtr()->GetName()).GetCString(); + + return nullptr; +} + +const char *SBThread::GetQueueName() const { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) + return nullptr; + + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) + return ConstString(exe_ctx.GetThreadPtr()->GetQueueName()).GetCString(); + + return nullptr; +} + +lldb::queue_id_t SBThread::GetQueueID() const { + LLDB_INSTRUMENT_VA(this); + + queue_id_t id = LLDB_INVALID_QUEUE_ID; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + id = exe_ctx.GetThreadPtr()->GetQueueID(); + } + } + + return id; +} + +bool SBThread::GetInfoItemByPathAsString(const char *path, SBStream &strm) { + LLDB_INSTRUMENT_VA(this, path, strm); + + bool success = false; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + Thread *thread = exe_ctx.GetThreadPtr(); + StructuredData::ObjectSP info_root_sp = thread->GetExtendedInfo(); + if (info_root_sp) { + StructuredData::ObjectSP node = + info_root_sp->GetObjectForDotSeparatedPath(path); + if (node) { + if (node->GetType() == eStructuredDataTypeString) { + strm.ref() << node->GetAsString()->GetValue(); + success = true; + } + if (node->GetType() == eStructuredDataTypeInteger) { + strm.Printf("0x%" PRIx64, node->GetUnsignedIntegerValue()); + success = true; + } + if (node->GetType() == eStructuredDataTypeFloat) { + strm.Printf("0x%f", node->GetAsFloat()->GetValue()); + success = true; + } + if (node->GetType() == eStructuredDataTypeBoolean) { + if (node->GetAsBoolean()->GetValue()) + strm.Printf("true"); + else + strm.Printf("false"); + success = true; + } + if (node->GetType() == eStructuredDataTypeNull) { + strm.Printf("null"); + success = true; + } + } + } + } + } + + return success; +} + +SBError SBThread::ResumeNewPlan(ExecutionContext &exe_ctx, + ThreadPlan *new_plan) { + SBError sb_error; + + Process *process = exe_ctx.GetProcessPtr(); + if (!process) { + sb_error.SetErrorString("No process in SBThread::ResumeNewPlan"); + return sb_error; + } + + Thread *thread = exe_ctx.GetThreadPtr(); + if (!thread) { + sb_error.SetErrorString("No thread in SBThread::ResumeNewPlan"); + return sb_error; + } + + // User level plans should be Controlling Plans so they can be interrupted, + // other plans executed, and then a "continue" will resume the plan. + if (new_plan != nullptr) { + new_plan->SetIsControllingPlan(true); + new_plan->SetOkayToDiscard(false); + } + + // Why do we need to set the current thread by ID here??? + process->GetThreadList().SetSelectedThreadByID(thread->GetID()); + + if (process->GetTarget().GetDebugger().GetAsyncExecution()) + sb_error.ref() = process->Resume(); + else + sb_error.ref() = process->ResumeSynchronous(nullptr); + + return sb_error; +} + +void SBThread::StepOver(lldb::RunMode stop_other_threads) { + LLDB_INSTRUMENT_VA(this, stop_other_threads); + + SBError error; // Ignored + StepOver(stop_other_threads, error); +} + +void SBThread::StepOver(lldb::RunMode stop_other_threads, SBError &error) { + LLDB_INSTRUMENT_VA(this, stop_other_threads, error); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) { + error.SetErrorString("this SBThread object is invalid"); + return; + } + + Thread *thread = exe_ctx.GetThreadPtr(); + bool abort_other_plans = false; + StackFrameSP frame_sp(thread->GetStackFrameAtIndex(0)); + + Status new_plan_status; + ThreadPlanSP new_plan_sp; + if (frame_sp) { + if (frame_sp->HasDebugInformation()) { + const LazyBool avoid_no_debug = eLazyBoolCalculate; + SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything)); + new_plan_sp = thread->QueueThreadPlanForStepOverRange( + abort_other_plans, sc.line_entry, sc, stop_other_threads, + new_plan_status, avoid_no_debug); + } else { + new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction( + true, abort_other_plans, stop_other_threads, new_plan_status); + } + } + error = ResumeNewPlan(exe_ctx, new_plan_sp.get()); +} + +void SBThread::StepInto(lldb::RunMode stop_other_threads) { + LLDB_INSTRUMENT_VA(this, stop_other_threads); + + StepInto(nullptr, stop_other_threads); +} + +void SBThread::StepInto(const char *target_name, + lldb::RunMode stop_other_threads) { + LLDB_INSTRUMENT_VA(this, target_name, stop_other_threads); + + SBError error; // Ignored + StepInto(target_name, LLDB_INVALID_LINE_NUMBER, error, stop_other_threads); +} + +void SBThread::StepInto(const char *target_name, uint32_t end_line, + SBError &error, lldb::RunMode stop_other_threads) { + LLDB_INSTRUMENT_VA(this, target_name, end_line, error, stop_other_threads); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) { + error.SetErrorString("this SBThread object is invalid"); + return; + } + + bool abort_other_plans = false; + + Thread *thread = exe_ctx.GetThreadPtr(); + StackFrameSP frame_sp(thread->GetStackFrameAtIndex(0)); + ThreadPlanSP new_plan_sp; + Status new_plan_status; + + if (frame_sp && frame_sp->HasDebugInformation()) { + SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything)); + AddressRange range; + if (end_line == LLDB_INVALID_LINE_NUMBER) + range = sc.line_entry.range; + else { + if (!sc.GetAddressRangeFromHereToEndLine(end_line, range, error.ref())) + return; + } + + const LazyBool step_out_avoids_code_without_debug_info = + eLazyBoolCalculate; + const LazyBool step_in_avoids_code_without_debug_info = + eLazyBoolCalculate; + new_plan_sp = thread->QueueThreadPlanForStepInRange( + abort_other_plans, range, sc, target_name, stop_other_threads, + new_plan_status, step_in_avoids_code_without_debug_info, + step_out_avoids_code_without_debug_info); + } else { + new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction( + false, abort_other_plans, stop_other_threads, new_plan_status); + } + + if (new_plan_status.Success()) + error = ResumeNewPlan(exe_ctx, new_plan_sp.get()); + else + error.SetErrorString(new_plan_status.AsCString()); +} + +void SBThread::StepOut() { + LLDB_INSTRUMENT_VA(this); + + SBError error; // Ignored + StepOut(error); +} + +void SBThread::StepOut(SBError &error) { + LLDB_INSTRUMENT_VA(this, error); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) { + error.SetErrorString("this SBThread object is invalid"); + return; + } + + bool abort_other_plans = false; + bool stop_other_threads = false; + + Thread *thread = exe_ctx.GetThreadPtr(); + + const LazyBool avoid_no_debug = eLazyBoolCalculate; + Status new_plan_status; + ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForStepOut( + abort_other_plans, nullptr, false, stop_other_threads, eVoteYes, + eVoteNoOpinion, 0, new_plan_status, avoid_no_debug)); + + if (new_plan_status.Success()) + error = ResumeNewPlan(exe_ctx, new_plan_sp.get()); + else + error.SetErrorString(new_plan_status.AsCString()); +} + +void SBThread::StepOutOfFrame(SBFrame &sb_frame) { + LLDB_INSTRUMENT_VA(this, sb_frame); + + SBError error; // Ignored + StepOutOfFrame(sb_frame, error); +} + +void SBThread::StepOutOfFrame(SBFrame &sb_frame, SBError &error) { + LLDB_INSTRUMENT_VA(this, sb_frame, error); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!sb_frame.IsValid()) { + error.SetErrorString("passed invalid SBFrame object"); + return; + } + + StackFrameSP frame_sp(sb_frame.GetFrameSP()); + + if (!exe_ctx.HasThreadScope()) { + error.SetErrorString("this SBThread object is invalid"); + return; + } + + bool abort_other_plans = false; + bool stop_other_threads = false; + Thread *thread = exe_ctx.GetThreadPtr(); + if (sb_frame.GetThread().GetThreadID() != thread->GetID()) { + error.SetErrorString("passed a frame from another thread"); + return; + } + + Status new_plan_status; + ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForStepOut( + abort_other_plans, nullptr, false, stop_other_threads, eVoteYes, + eVoteNoOpinion, frame_sp->GetFrameIndex(), new_plan_status)); + + if (new_plan_status.Success()) + error = ResumeNewPlan(exe_ctx, new_plan_sp.get()); + else + error.SetErrorString(new_plan_status.AsCString()); +} + +void SBThread::StepInstruction(bool step_over) { + LLDB_INSTRUMENT_VA(this, step_over); + + SBError error; // Ignored + StepInstruction(step_over, error); +} + +void SBThread::StepInstruction(bool step_over, SBError &error) { + LLDB_INSTRUMENT_VA(this, step_over, error); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) { + error.SetErrorString("this SBThread object is invalid"); + return; + } + + Thread *thread = exe_ctx.GetThreadPtr(); + Status new_plan_status; + ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForStepSingleInstruction( + step_over, false, true, new_plan_status)); + + if (new_plan_status.Success()) + error = ResumeNewPlan(exe_ctx, new_plan_sp.get()); + else + error.SetErrorString(new_plan_status.AsCString()); +} + +void SBThread::RunToAddress(lldb::addr_t addr) { + LLDB_INSTRUMENT_VA(this, addr); + + SBError error; // Ignored + RunToAddress(addr, error); +} + +void SBThread::RunToAddress(lldb::addr_t addr, SBError &error) { + LLDB_INSTRUMENT_VA(this, addr, error); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) { + error.SetErrorString("this SBThread object is invalid"); + return; + } + + bool abort_other_plans = false; + bool stop_other_threads = true; + + Address target_addr(addr); + + Thread *thread = exe_ctx.GetThreadPtr(); + + Status new_plan_status; + ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForRunToAddress( + abort_other_plans, target_addr, stop_other_threads, new_plan_status)); + + if (new_plan_status.Success()) + error = ResumeNewPlan(exe_ctx, new_plan_sp.get()); + else + error.SetErrorString(new_plan_status.AsCString()); +} + +SBError SBThread::StepOverUntil(lldb::SBFrame &sb_frame, + lldb::SBFileSpec &sb_file_spec, uint32_t line) { + LLDB_INSTRUMENT_VA(this, sb_frame, sb_file_spec, line); + + SBError sb_error; + char path[PATH_MAX]; + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrameSP frame_sp(sb_frame.GetFrameSP()); + + if (exe_ctx.HasThreadScope()) { + Target *target = exe_ctx.GetTargetPtr(); + Thread *thread = exe_ctx.GetThreadPtr(); + + if (line == 0) { + sb_error.SetErrorString("invalid line argument"); + return sb_error; + } + + if (!frame_sp) { + // We don't want to run SelectMostRelevantFrame here, for instance if + // you called a sequence of StepOverUntil's you wouldn't want the + // frame changed out from under you because you stepped into a + // recognized frame. + frame_sp = thread->GetSelectedFrame(DoNoSelectMostRelevantFrame); + if (!frame_sp) + frame_sp = thread->GetStackFrameAtIndex(0); + } + + SymbolContext frame_sc; + if (!frame_sp) { + sb_error.SetErrorString("no valid frames in thread to step"); + return sb_error; + } + + // If we have a frame, get its line + frame_sc = frame_sp->GetSymbolContext( + eSymbolContextCompUnit | eSymbolContextFunction | + eSymbolContextLineEntry | eSymbolContextSymbol); + + if (frame_sc.comp_unit == nullptr) { + sb_error.SetErrorStringWithFormat( + "frame %u doesn't have debug information", frame_sp->GetFrameIndex()); + return sb_error; + } + + FileSpec step_file_spec; + if (sb_file_spec.IsValid()) { + // The file spec passed in was valid, so use it + step_file_spec = sb_file_spec.ref(); + } else { + if (frame_sc.line_entry.IsValid()) + step_file_spec = frame_sc.line_entry.GetFile(); + else { + sb_error.SetErrorString("invalid file argument or no file for frame"); + return sb_error; + } + } + + // Grab the current function, then we will make sure the "until" address is + // within the function. We discard addresses that are out of the current + // function, and then if there are no addresses remaining, give an + // appropriate error message. + + bool all_in_function = true; + AddressRange fun_range = frame_sc.function->GetAddressRange(); + + std::vector<addr_t> step_over_until_addrs; + const bool abort_other_plans = false; + const bool stop_other_threads = false; + // TODO: Handle SourceLocationSpec column information + SourceLocationSpec location_spec( + step_file_spec, line, /*column=*/std::nullopt, /*check_inlines=*/true, + /*exact_match=*/false); + + SymbolContextList sc_list; + frame_sc.comp_unit->ResolveSymbolContext(location_spec, + eSymbolContextLineEntry, sc_list); + for (const SymbolContext &sc : sc_list) { + addr_t step_addr = + sc.line_entry.range.GetBaseAddress().GetLoadAddress(target); + if (step_addr != LLDB_INVALID_ADDRESS) { + if (fun_range.ContainsLoadAddress(step_addr, target)) + step_over_until_addrs.push_back(step_addr); + else + all_in_function = false; + } + } + + if (step_over_until_addrs.empty()) { + if (all_in_function) { + step_file_spec.GetPath(path, sizeof(path)); + sb_error.SetErrorStringWithFormat("No line entries for %s:%u", path, + line); + } else + sb_error.SetErrorString("step until target not in current function"); + } else { + Status new_plan_status; + ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForStepUntil( + abort_other_plans, &step_over_until_addrs[0], + step_over_until_addrs.size(), stop_other_threads, + frame_sp->GetFrameIndex(), new_plan_status)); + + if (new_plan_status.Success()) + sb_error = ResumeNewPlan(exe_ctx, new_plan_sp.get()); + else + sb_error.SetErrorString(new_plan_status.AsCString()); + } + } else { + sb_error.SetErrorString("this SBThread object is invalid"); + } + return sb_error; +} + +SBError SBThread::StepUsingScriptedThreadPlan(const char *script_class_name) { + LLDB_INSTRUMENT_VA(this, script_class_name); + + return StepUsingScriptedThreadPlan(script_class_name, true); +} + +SBError SBThread::StepUsingScriptedThreadPlan(const char *script_class_name, + bool resume_immediately) { + LLDB_INSTRUMENT_VA(this, script_class_name, resume_immediately); + + lldb::SBStructuredData no_data; + return StepUsingScriptedThreadPlan(script_class_name, no_data, + resume_immediately); +} + +SBError SBThread::StepUsingScriptedThreadPlan(const char *script_class_name, + SBStructuredData &args_data, + bool resume_immediately) { + LLDB_INSTRUMENT_VA(this, script_class_name, args_data, resume_immediately); + + SBError error; + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) { + error.SetErrorString("this SBThread object is invalid"); + return error; + } + + Thread *thread = exe_ctx.GetThreadPtr(); + Status new_plan_status; + StructuredData::ObjectSP obj_sp = args_data.m_impl_up->GetObjectSP(); + + ThreadPlanSP new_plan_sp = thread->QueueThreadPlanForStepScripted( + false, script_class_name, obj_sp, false, new_plan_status); + + if (new_plan_status.Fail()) { + error.SetErrorString(new_plan_status.AsCString()); + return error; + } + + if (!resume_immediately) + return error; + + if (new_plan_status.Success()) + error = ResumeNewPlan(exe_ctx, new_plan_sp.get()); + else + error.SetErrorString(new_plan_status.AsCString()); + + return error; +} + +SBError SBThread::JumpToLine(lldb::SBFileSpec &file_spec, uint32_t line) { + LLDB_INSTRUMENT_VA(this, file_spec, line); + + SBError sb_error; + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) { + sb_error.SetErrorString("this SBThread object is invalid"); + return sb_error; + } + + Thread *thread = exe_ctx.GetThreadPtr(); + + Status err = thread->JumpToLine(file_spec.ref(), line, true); + sb_error.SetError(err); + return sb_error; +} + +SBError SBThread::ReturnFromFrame(SBFrame &frame, SBValue &return_value) { + LLDB_INSTRUMENT_VA(this, frame, return_value); + + SBError sb_error; + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Thread *thread = exe_ctx.GetThreadPtr(); + sb_error.SetError( + thread->ReturnFromFrame(frame.GetFrameSP(), return_value.GetSP())); + } + + return sb_error; +} + +SBError SBThread::UnwindInnermostExpression() { + LLDB_INSTRUMENT_VA(this); + + SBError sb_error; + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Thread *thread = exe_ctx.GetThreadPtr(); + sb_error.SetError(thread->UnwindInnermostExpression()); + if (sb_error.Success()) + thread->SetSelectedFrameByIndex(0, false); + } + + return sb_error; +} + +bool SBThread::Suspend() { + LLDB_INSTRUMENT_VA(this); + + SBError error; // Ignored + return Suspend(error); +} + +bool SBThread::Suspend(SBError &error) { + LLDB_INSTRUMENT_VA(this, error); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + bool result = false; + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + exe_ctx.GetThreadPtr()->SetResumeState(eStateSuspended); + result = true; + } else { + error.SetErrorString("process is running"); + } + } else + error.SetErrorString("this SBThread object is invalid"); + return result; +} + +bool SBThread::Resume() { + LLDB_INSTRUMENT_VA(this); + + SBError error; // Ignored + return Resume(error); +} + +bool SBThread::Resume(SBError &error) { + LLDB_INSTRUMENT_VA(this, error); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + bool result = false; + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + const bool override_suspend = true; + exe_ctx.GetThreadPtr()->SetResumeState(eStateRunning, override_suspend); + result = true; + } else { + error.SetErrorString("process is running"); + } + } else + error.SetErrorString("this SBThread object is invalid"); + return result; +} + +bool SBThread::IsSuspended() { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) + return exe_ctx.GetThreadPtr()->GetResumeState() == eStateSuspended; + return false; +} + +bool SBThread::IsStopped() { + LLDB_INSTRUMENT_VA(this); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) + return StateIsStoppedState(exe_ctx.GetThreadPtr()->GetState(), true); + return false; +} + +SBProcess SBThread::GetProcess() { + LLDB_INSTRUMENT_VA(this); + + SBProcess sb_process; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + // Have to go up to the target so we can get a shared pointer to our + // process... + sb_process.SetSP(exe_ctx.GetProcessSP()); + } + + return sb_process; +} + +uint32_t SBThread::GetNumFrames() { + LLDB_INSTRUMENT_VA(this); + + uint32_t num_frames = 0; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + num_frames = exe_ctx.GetThreadPtr()->GetStackFrameCount(); + } + } + + return num_frames; +} + +SBFrame SBThread::GetFrameAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBFrame sb_frame; + StackFrameSP frame_sp; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + frame_sp = exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(idx); + sb_frame.SetFrameSP(frame_sp); + } + } + + return sb_frame; +} + +lldb::SBFrame SBThread::GetSelectedFrame() { + LLDB_INSTRUMENT_VA(this); + + SBFrame sb_frame; + StackFrameSP frame_sp; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + frame_sp = + exe_ctx.GetThreadPtr()->GetSelectedFrame(SelectMostRelevantFrame); + sb_frame.SetFrameSP(frame_sp); + } + } + + return sb_frame; +} + +lldb::SBFrame SBThread::SetSelectedFrame(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBFrame sb_frame; + StackFrameSP frame_sp; + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + Thread *thread = exe_ctx.GetThreadPtr(); + frame_sp = thread->GetStackFrameAtIndex(idx); + if (frame_sp) { + thread->SetSelectedFrame(frame_sp.get()); + sb_frame.SetFrameSP(frame_sp); + } + } + } + + return sb_frame; +} + +bool SBThread::EventIsThreadEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return Thread::ThreadEventData::GetEventDataFromEvent(event.get()) != nullptr; +} + +SBFrame SBThread::GetStackFrameFromEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return Thread::ThreadEventData::GetStackFrameFromEvent(event.get()); +} + +SBThread SBThread::GetThreadFromEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return Thread::ThreadEventData::GetThreadFromEvent(event.get()); +} + +bool SBThread::operator==(const SBThread &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_sp->GetThreadSP().get() == + rhs.m_opaque_sp->GetThreadSP().get(); +} + +bool SBThread::operator!=(const SBThread &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return m_opaque_sp->GetThreadSP().get() != + rhs.m_opaque_sp->GetThreadSP().get(); +} + +bool SBThread::GetStatus(SBStream &status) const { + LLDB_INSTRUMENT_VA(this, status); + + Stream &strm = status.ref(); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + exe_ctx.GetThreadPtr()->GetStatus(strm, 0, 1, 1, true); + } else + strm.PutCString("No status"); + + return true; +} + +bool SBThread::GetDescription(SBStream &description) const { + LLDB_INSTRUMENT_VA(this, description); + + return GetDescription(description, false); +} + +bool SBThread::GetDescription(SBStream &description, bool stop_format) const { + LLDB_INSTRUMENT_VA(this, description, stop_format); + + Stream &strm = description.ref(); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + exe_ctx.GetThreadPtr()->DumpUsingSettingsFormat( + strm, LLDB_INVALID_THREAD_ID, stop_format); + } else + strm.PutCString("No value"); + + return true; +} + +SBError SBThread::GetDescriptionWithFormat(const SBFormat &format, + SBStream &output) { + Stream &strm = output.ref(); + + SBError error; + if (!format) { + error.SetErrorString("The provided SBFormat object is invalid"); + return error; + } + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + if (exe_ctx.GetThreadPtr()->DumpUsingFormat( + strm, LLDB_INVALID_THREAD_ID, format.GetFormatEntrySP().get())) { + return error; + } + } + + error.SetErrorStringWithFormat( + "It was not possible to generate a thread description with the given " + "format string '%s'", + format.GetFormatEntrySP()->string.c_str()); + return error; +} + +SBThread SBThread::GetExtendedBacktraceThread(const char *type) { + LLDB_INSTRUMENT_VA(this, type); + + std::unique_lock<std::recursive_mutex> lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + SBThread sb_origin_thread; + + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + if (exe_ctx.HasThreadScope()) { + ThreadSP real_thread(exe_ctx.GetThreadSP()); + if (real_thread) { + ConstString type_const(type); + Process *process = exe_ctx.GetProcessPtr(); + if (process) { + SystemRuntime *runtime = process->GetSystemRuntime(); + if (runtime) { + ThreadSP new_thread_sp( + runtime->GetExtendedBacktraceThread(real_thread, type_const)); + if (new_thread_sp) { + // Save this in the Process' ExtendedThreadList so a strong + // pointer retains the object. + process->GetExtendedThreadList().AddThread(new_thread_sp); + sb_origin_thread.SetThread(new_thread_sp); + } + } + } + } + } + } + + return sb_origin_thread; +} + +uint32_t SBThread::GetExtendedBacktraceOriginatingIndexID() { + LLDB_INSTRUMENT_VA(this); + + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (thread_sp) + return thread_sp->GetExtendedBacktraceOriginatingIndexID(); + return LLDB_INVALID_INDEX32; +} + +SBValue SBThread::GetCurrentException() { + LLDB_INSTRUMENT_VA(this); + + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (!thread_sp) + return SBValue(); + + return SBValue(thread_sp->GetCurrentException()); +} + +SBThread SBThread::GetCurrentExceptionBacktrace() { + LLDB_INSTRUMENT_VA(this); + + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (!thread_sp) + return SBThread(); + + return SBThread(thread_sp->GetCurrentExceptionBacktrace()); +} + +bool SBThread::SafeToCallFunctions() { + LLDB_INSTRUMENT_VA(this); + + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (thread_sp) + return thread_sp->SafeToCallFunctions(); + return true; +} + +lldb_private::Thread *SBThread::operator->() { + return get(); +} + +lldb_private::Thread *SBThread::get() { + return m_opaque_sp->GetThreadSP().get(); +} + +SBValue SBThread::GetSiginfo() { + LLDB_INSTRUMENT_VA(this); + + ThreadSP thread_sp = m_opaque_sp->GetThreadSP(); + if (!thread_sp) + return SBValue(); + return thread_sp->GetSiginfoValue(); +} diff --git a/contrib/llvm-project/lldb/source/API/SBThreadCollection.cpp b/contrib/llvm-project/lldb/source/API/SBThreadCollection.cpp new file mode 100644 index 000000000000..9d688e012239 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBThreadCollection.cpp @@ -0,0 +1,83 @@ +//===-- SBThreadCollection.cpp --------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBThreadCollection.h" +#include "lldb/API/SBThread.h" +#include "lldb/Target/ThreadList.h" +#include "lldb/Utility/Instrumentation.h" + +using namespace lldb; +using namespace lldb_private; + +SBThreadCollection::SBThreadCollection() { LLDB_INSTRUMENT_VA(this); } + +SBThreadCollection::SBThreadCollection(const SBThreadCollection &rhs) + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const SBThreadCollection &SBThreadCollection:: +operator=(const SBThreadCollection &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; +} + +SBThreadCollection::SBThreadCollection(const ThreadCollectionSP &threads) + : m_opaque_sp(threads) {} + +SBThreadCollection::~SBThreadCollection() = default; + +void SBThreadCollection::SetOpaque(const lldb::ThreadCollectionSP &threads) { + m_opaque_sp = threads; +} + +lldb_private::ThreadCollection *SBThreadCollection::get() const { + return m_opaque_sp.get(); +} + +lldb_private::ThreadCollection *SBThreadCollection::operator->() const { + return m_opaque_sp.operator->(); +} + +lldb::ThreadCollectionSP &SBThreadCollection::operator*() { + return m_opaque_sp; +} + +const lldb::ThreadCollectionSP &SBThreadCollection::operator*() const { + return m_opaque_sp; +} + +bool SBThreadCollection::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBThreadCollection::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} + +size_t SBThreadCollection::GetSize() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + return m_opaque_sp->GetSize(); + return 0; +} + +SBThread SBThreadCollection::GetThreadAtIndex(size_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBThread thread; + if (m_opaque_sp && idx < m_opaque_sp->GetSize()) + thread = m_opaque_sp->GetThreadAtIndex(idx); + return thread; +} diff --git a/contrib/llvm-project/lldb/source/API/SBThreadPlan.cpp b/contrib/llvm-project/lldb/source/API/SBThreadPlan.cpp new file mode 100644 index 000000000000..f756bca3176e --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBThreadPlan.cpp @@ -0,0 +1,415 @@ +//===-- SBThreadPlan.cpp --------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBThread.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBFileSpec.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStructuredData.h" +#include "lldb/API/SBSymbolContext.h" +#include "lldb/Breakpoint/BreakpointLocation.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Core/StructuredDataImpl.h" +#include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Symbol/CompileUnit.h" +#include "lldb/Symbol/SymbolContext.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/Queue.h" +#include "lldb/Target/StopInfo.h" +#include "lldb/Target/SystemRuntime.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" +#include "lldb/Target/ThreadPlan.h" +#include "lldb/Target/ThreadPlanPython.h" +#include "lldb/Target/ThreadPlanStepInRange.h" +#include "lldb/Target/ThreadPlanStepInstruction.h" +#include "lldb/Target/ThreadPlanStepOut.h" +#include "lldb/Target/ThreadPlanStepRange.h" +#include "lldb/Utility/State.h" +#include "lldb/Utility/Stream.h" +#include "lldb/Utility/StructuredData.h" + +#include "lldb/API/SBAddress.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBFrame.h" +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBThreadPlan.h" +#include "lldb/API/SBValue.h" + +#include <memory> + +using namespace lldb; +using namespace lldb_private; + +// Constructors +SBThreadPlan::SBThreadPlan() { LLDB_INSTRUMENT_VA(this); } + +SBThreadPlan::SBThreadPlan(const ThreadPlanSP &lldb_object_sp) + : m_opaque_wp(lldb_object_sp) { + LLDB_INSTRUMENT_VA(this, lldb_object_sp); +} + +SBThreadPlan::SBThreadPlan(const SBThreadPlan &rhs) + : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBThreadPlan::SBThreadPlan(lldb::SBThread &sb_thread, const char *class_name) { + LLDB_INSTRUMENT_VA(this, sb_thread, class_name); + + Thread *thread = sb_thread.get(); + if (thread) + m_opaque_wp = std::make_shared<ThreadPlanPython>(*thread, class_name, + StructuredDataImpl()); +} + +SBThreadPlan::SBThreadPlan(lldb::SBThread &sb_thread, const char *class_name, + lldb::SBStructuredData &args_data) { + LLDB_INSTRUMENT_VA(this, sb_thread, class_name, args_data); + + Thread *thread = sb_thread.get(); + if (thread) + m_opaque_wp = std::make_shared<ThreadPlanPython>(*thread, class_name, + *args_data.m_impl_up); +} + +// Assignment operator + +const lldb::SBThreadPlan &SBThreadPlan::operator=(const SBThreadPlan &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_wp = rhs.m_opaque_wp; + return *this; +} +// Destructor +SBThreadPlan::~SBThreadPlan() = default; + +bool SBThreadPlan::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBThreadPlan::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return static_cast<bool>(GetSP()); +} + +void SBThreadPlan::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_wp.reset(); +} + +lldb::StopReason SBThreadPlan::GetStopReason() { + LLDB_INSTRUMENT_VA(this); + + return eStopReasonNone; +} + +size_t SBThreadPlan::GetStopReasonDataCount() { + LLDB_INSTRUMENT_VA(this); + + return 0; +} + +uint64_t SBThreadPlan::GetStopReasonDataAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + return 0; +} + +SBThread SBThreadPlan::GetThread() const { + LLDB_INSTRUMENT_VA(this); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) { + return SBThread(thread_plan_sp->GetThread().shared_from_this()); + } else + return SBThread(); +} + +bool SBThreadPlan::GetDescription(lldb::SBStream &description) const { + LLDB_INSTRUMENT_VA(this, description); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) { + thread_plan_sp->GetDescription(description.get(), eDescriptionLevelFull); + } else { + description.Printf("Empty SBThreadPlan"); + } + return true; +} + +void SBThreadPlan::SetThreadPlan(const ThreadPlanSP &lldb_object_wp) { + m_opaque_wp = lldb_object_wp; +} + +void SBThreadPlan::SetPlanComplete(bool success) { + LLDB_INSTRUMENT_VA(this, success); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) + thread_plan_sp->SetPlanComplete(success); +} + +bool SBThreadPlan::IsPlanComplete() { + LLDB_INSTRUMENT_VA(this); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) + return thread_plan_sp->IsPlanComplete(); + return true; +} + +bool SBThreadPlan::IsPlanStale() { + LLDB_INSTRUMENT_VA(this); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) + return thread_plan_sp->IsPlanStale(); + return true; +} + +bool SBThreadPlan::IsValid() { + LLDB_INSTRUMENT_VA(this); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) + return thread_plan_sp->ValidatePlan(nullptr); + return false; +} + +bool SBThreadPlan::GetStopOthers() { + LLDB_INSTRUMENT_VA(this); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) + return thread_plan_sp->StopOthers(); + return false; +} + +void SBThreadPlan::SetStopOthers(bool stop_others) { + LLDB_INSTRUMENT_VA(this, stop_others); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) + thread_plan_sp->SetStopOthers(stop_others); +} + +// This section allows an SBThreadPlan to push another of the common types of +// plans... +// +// FIXME, you should only be able to queue thread plans from inside the methods +// of a Scripted Thread Plan. Need a way to enforce that. + +SBThreadPlan +SBThreadPlan::QueueThreadPlanForStepOverRange(SBAddress &sb_start_address, + lldb::addr_t size) { + LLDB_INSTRUMENT_VA(this, sb_start_address, size); + + SBError error; + return QueueThreadPlanForStepOverRange(sb_start_address, size, error); +} + +SBThreadPlan SBThreadPlan::QueueThreadPlanForStepOverRange( + SBAddress &sb_start_address, lldb::addr_t size, SBError &error) { + LLDB_INSTRUMENT_VA(this, sb_start_address, size, error); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) { + Address *start_address = sb_start_address.get(); + if (!start_address) { + return SBThreadPlan(); + } + + AddressRange range(*start_address, size); + SymbolContext sc; + start_address->CalculateSymbolContext(&sc); + Status plan_status; + + SBThreadPlan plan = SBThreadPlan( + thread_plan_sp->GetThread().QueueThreadPlanForStepOverRange( + false, range, sc, eAllThreads, plan_status)); + + if (plan_status.Fail()) + error.SetErrorString(plan_status.AsCString()); + else + plan.GetSP()->SetPrivate(true); + + return plan; + } + return SBThreadPlan(); +} + +SBThreadPlan +SBThreadPlan::QueueThreadPlanForStepInRange(SBAddress &sb_start_address, + lldb::addr_t size) { + LLDB_INSTRUMENT_VA(this, sb_start_address, size); + + SBError error; + return QueueThreadPlanForStepInRange(sb_start_address, size, error); +} + +SBThreadPlan +SBThreadPlan::QueueThreadPlanForStepInRange(SBAddress &sb_start_address, + lldb::addr_t size, SBError &error) { + LLDB_INSTRUMENT_VA(this, sb_start_address, size, error); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) { + Address *start_address = sb_start_address.get(); + if (!start_address) { + return SBThreadPlan(); + } + + AddressRange range(*start_address, size); + SymbolContext sc; + start_address->CalculateSymbolContext(&sc); + + Status plan_status; + SBThreadPlan plan = + SBThreadPlan(thread_plan_sp->GetThread().QueueThreadPlanForStepInRange( + false, range, sc, nullptr, eAllThreads, plan_status)); + + if (plan_status.Fail()) + error.SetErrorString(plan_status.AsCString()); + else + plan.GetSP()->SetPrivate(true); + + return plan; + } + return SBThreadPlan(); +} + +SBThreadPlan +SBThreadPlan::QueueThreadPlanForStepOut(uint32_t frame_idx_to_step_to, + bool first_insn) { + LLDB_INSTRUMENT_VA(this, frame_idx_to_step_to, first_insn); + + SBError error; + return QueueThreadPlanForStepOut(frame_idx_to_step_to, first_insn, error); +} + +SBThreadPlan +SBThreadPlan::QueueThreadPlanForStepOut(uint32_t frame_idx_to_step_to, + bool first_insn, SBError &error) { + LLDB_INSTRUMENT_VA(this, frame_idx_to_step_to, first_insn, error); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) { + SymbolContext sc; + sc = thread_plan_sp->GetThread().GetStackFrameAtIndex(0)->GetSymbolContext( + lldb::eSymbolContextEverything); + + Status plan_status; + SBThreadPlan plan = + SBThreadPlan(thread_plan_sp->GetThread().QueueThreadPlanForStepOut( + false, &sc, first_insn, false, eVoteYes, eVoteNoOpinion, + frame_idx_to_step_to, plan_status)); + + if (plan_status.Fail()) + error.SetErrorString(plan_status.AsCString()); + else + plan.GetSP()->SetPrivate(true); + + return plan; + } + return SBThreadPlan(); +} + +SBThreadPlan +SBThreadPlan::QueueThreadPlanForRunToAddress(SBAddress sb_address) { + LLDB_INSTRUMENT_VA(this, sb_address); + + SBError error; + return QueueThreadPlanForRunToAddress(sb_address, error); +} + +SBThreadPlan SBThreadPlan::QueueThreadPlanForRunToAddress(SBAddress sb_address, + SBError &error) { + LLDB_INSTRUMENT_VA(this, sb_address, error); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) { + Address *address = sb_address.get(); + if (!address) + return SBThreadPlan(); + + Status plan_status; + SBThreadPlan plan = + SBThreadPlan(thread_plan_sp->GetThread().QueueThreadPlanForRunToAddress( + false, *address, false, plan_status)); + + if (plan_status.Fail()) + error.SetErrorString(plan_status.AsCString()); + else + plan.GetSP()->SetPrivate(true); + + return plan; + } + return SBThreadPlan(); +} + +SBThreadPlan +SBThreadPlan::QueueThreadPlanForStepScripted(const char *script_class_name) { + LLDB_INSTRUMENT_VA(this, script_class_name); + + SBError error; + return QueueThreadPlanForStepScripted(script_class_name, error); +} + +SBThreadPlan +SBThreadPlan::QueueThreadPlanForStepScripted(const char *script_class_name, + SBError &error) { + LLDB_INSTRUMENT_VA(this, script_class_name, error); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) { + Status plan_status; + StructuredData::ObjectSP empty_args; + SBThreadPlan plan = + SBThreadPlan(thread_plan_sp->GetThread().QueueThreadPlanForStepScripted( + false, script_class_name, empty_args, false, plan_status)); + + if (plan_status.Fail()) + error.SetErrorString(plan_status.AsCString()); + else + plan.GetSP()->SetPrivate(true); + + return plan; + } + return SBThreadPlan(); +} + +SBThreadPlan +SBThreadPlan::QueueThreadPlanForStepScripted(const char *script_class_name, + lldb::SBStructuredData &args_data, + SBError &error) { + LLDB_INSTRUMENT_VA(this, script_class_name, args_data, error); + + ThreadPlanSP thread_plan_sp(GetSP()); + if (thread_plan_sp) { + Status plan_status; + StructuredData::ObjectSP args_obj = args_data.m_impl_up->GetObjectSP(); + SBThreadPlan plan = + SBThreadPlan(thread_plan_sp->GetThread().QueueThreadPlanForStepScripted( + false, script_class_name, args_obj, false, plan_status)); + + if (plan_status.Fail()) + error.SetErrorString(plan_status.AsCString()); + else + plan.GetSP()->SetPrivate(true); + + return plan; + } else { + return SBThreadPlan(); + } +} diff --git a/contrib/llvm-project/lldb/source/API/SBTrace.cpp b/contrib/llvm-project/lldb/source/API/SBTrace.cpp new file mode 100644 index 000000000000..da31d173425e --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBTrace.cpp @@ -0,0 +1,149 @@ +//===-- SBTrace.cpp -------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/Target/Process.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBStructuredData.h" +#include "lldb/API/SBThread.h" +#include "lldb/API/SBTrace.h" + +#include "lldb/Core/StructuredDataImpl.h" + +#include <memory> + +using namespace lldb; +using namespace lldb_private; +using namespace llvm; + +SBTrace::SBTrace() { LLDB_INSTRUMENT_VA(this); } + +SBTrace::SBTrace(const lldb::TraceSP &trace_sp) : m_opaque_sp(trace_sp) { + LLDB_INSTRUMENT_VA(this, trace_sp); +} + +SBTrace SBTrace::LoadTraceFromFile(SBError &error, SBDebugger &debugger, + const SBFileSpec &trace_description_file) { + LLDB_INSTRUMENT_VA(error, debugger, trace_description_file); + + Expected<lldb::TraceSP> trace_or_err = Trace::LoadPostMortemTraceFromFile( + debugger.ref(), trace_description_file.ref()); + + if (!trace_or_err) { + error.SetErrorString(toString(trace_or_err.takeError()).c_str()); + return SBTrace(); + } + + return SBTrace(trace_or_err.get()); +} + +SBTraceCursor SBTrace::CreateNewCursor(SBError &error, SBThread &thread) { + LLDB_INSTRUMENT_VA(this, error, thread); + + if (!m_opaque_sp) { + error.SetErrorString("error: invalid trace"); + return SBTraceCursor(); + } + if (!thread.get()) { + error.SetErrorString("error: invalid thread"); + return SBTraceCursor(); + } + + if (llvm::Expected<lldb::TraceCursorSP> trace_cursor_sp = + m_opaque_sp->CreateNewCursor(*thread.get())) { + return SBTraceCursor(std::move(*trace_cursor_sp)); + } else { + error.SetErrorString(llvm::toString(trace_cursor_sp.takeError()).c_str()); + return SBTraceCursor(); + } +} + +SBFileSpec SBTrace::SaveToDisk(SBError &error, const SBFileSpec &bundle_dir, + bool compact) { + LLDB_INSTRUMENT_VA(this, error, bundle_dir, compact); + + error.Clear(); + SBFileSpec file_spec; + + if (!m_opaque_sp) + error.SetErrorString("error: invalid trace"); + else if (Expected<FileSpec> desc_file = + m_opaque_sp->SaveToDisk(bundle_dir.ref(), compact)) + file_spec.SetFileSpec(*desc_file); + else + error.SetErrorString(llvm::toString(desc_file.takeError()).c_str()); + + return file_spec; +} + +const char *SBTrace::GetStartConfigurationHelp() { + LLDB_INSTRUMENT_VA(this); + if (!m_opaque_sp) + return nullptr; + + return ConstString(m_opaque_sp->GetStartConfigurationHelp()).GetCString(); +} + +SBError SBTrace::Start(const SBStructuredData &configuration) { + LLDB_INSTRUMENT_VA(this, configuration); + SBError error; + if (!m_opaque_sp) + error.SetErrorString("error: invalid trace"); + else if (llvm::Error err = + m_opaque_sp->Start(configuration.m_impl_up->GetObjectSP())) + error.SetErrorString(llvm::toString(std::move(err)).c_str()); + return error; +} + +SBError SBTrace::Start(const SBThread &thread, + const SBStructuredData &configuration) { + LLDB_INSTRUMENT_VA(this, thread, configuration); + + SBError error; + if (!m_opaque_sp) + error.SetErrorString("error: invalid trace"); + else { + if (llvm::Error err = + m_opaque_sp->Start(std::vector<lldb::tid_t>{thread.GetThreadID()}, + configuration.m_impl_up->GetObjectSP())) + error.SetErrorString(llvm::toString(std::move(err)).c_str()); + } + + return error; +} + +SBError SBTrace::Stop() { + LLDB_INSTRUMENT_VA(this); + SBError error; + if (!m_opaque_sp) + error.SetErrorString("error: invalid trace"); + else if (llvm::Error err = m_opaque_sp->Stop()) + error.SetErrorString(llvm::toString(std::move(err)).c_str()); + return error; +} + +SBError SBTrace::Stop(const SBThread &thread) { + LLDB_INSTRUMENT_VA(this, thread); + SBError error; + if (!m_opaque_sp) + error.SetErrorString("error: invalid trace"); + else if (llvm::Error err = m_opaque_sp->Stop({thread.GetThreadID()})) + error.SetErrorString(llvm::toString(std::move(err)).c_str()); + return error; +} + +bool SBTrace::IsValid() { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} + +SBTrace::operator bool() const { + LLDB_INSTRUMENT_VA(this); + return (bool)m_opaque_sp; +} diff --git a/contrib/llvm-project/lldb/source/API/SBTraceCursor.cpp b/contrib/llvm-project/lldb/source/API/SBTraceCursor.cpp new file mode 100644 index 000000000000..c3dacd0d4b3d --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBTraceCursor.cpp @@ -0,0 +1,137 @@ +//===-- SBTraceCursor.cpp +//-------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBTraceCursor.h" +#include "Utils.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Target/TraceCursor.h" + +using namespace lldb; +using namespace lldb_private; + +SBTraceCursor::SBTraceCursor() { LLDB_INSTRUMENT_VA(this); } + +SBTraceCursor::SBTraceCursor(TraceCursorSP trace_cursor_sp) + : m_opaque_sp{std::move(trace_cursor_sp)} { + LLDB_INSTRUMENT_VA(this, trace_cursor_sp); +} + +void SBTraceCursor::SetForwards(bool forwards) { + LLDB_INSTRUMENT_VA(this, forwards); + + m_opaque_sp->SetForwards(forwards); +} + +bool SBTraceCursor::IsForwards() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->IsForwards(); +} + +void SBTraceCursor::Next() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->Next(); +} + +bool SBTraceCursor::HasValue() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->HasValue(); +} + +bool SBTraceCursor::GoToId(lldb::user_id_t id) { + LLDB_INSTRUMENT_VA(this, id); + + return m_opaque_sp->GoToId(id); +} + +bool SBTraceCursor::HasId(lldb::user_id_t id) const { + LLDB_INSTRUMENT_VA(this, id); + + return m_opaque_sp->HasId(id); +} + +lldb::user_id_t SBTraceCursor::GetId() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetId(); +} + +bool SBTraceCursor::Seek(int64_t offset, lldb::TraceCursorSeekType origin) { + LLDB_INSTRUMENT_VA(this, offset); + + return m_opaque_sp->Seek(offset, origin); +} + +lldb::TraceItemKind SBTraceCursor::GetItemKind() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetItemKind(); +} + +bool SBTraceCursor::IsError() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->IsError(); +} + +const char *SBTraceCursor::GetError() const { + LLDB_INSTRUMENT_VA(this); + + return ConstString(m_opaque_sp->GetError()).GetCString(); +} + +bool SBTraceCursor::IsEvent() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->IsEvent(); +} + +lldb::TraceEvent SBTraceCursor::GetEventType() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetEventType(); +} + +const char *SBTraceCursor::GetEventTypeAsString() const { + LLDB_INSTRUMENT_VA(this); + + return ConstString(m_opaque_sp->GetEventTypeAsString()).GetCString(); +} + +bool SBTraceCursor::IsInstruction() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->IsInstruction(); +} + +lldb::addr_t SBTraceCursor::GetLoadAddress() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetLoadAddress(); +} + +lldb::cpu_id_t SBTraceCursor::GetCPU() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp->GetCPU(); +} + +bool SBTraceCursor::IsValid() const { + LLDB_INSTRUMENT_VA(this); + + return this->operator bool(); +} + +SBTraceCursor::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} diff --git a/contrib/llvm-project/lldb/source/API/SBType.cpp b/contrib/llvm-project/lldb/source/API/SBType.cpp new file mode 100644 index 000000000000..8a063e5ad61d --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBType.cpp @@ -0,0 +1,1011 @@ +//===-- SBType.cpp --------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBType.h" +#include "Utils.h" +#include "lldb/API/SBDefines.h" +#include "lldb/API/SBModule.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBTypeEnumMember.h" +#include "lldb/Core/Mangled.h" +#include "lldb/Core/ValueObjectConstResult.h" +#include "lldb/Symbol/CompilerDecl.h" +#include "lldb/Symbol/CompilerType.h" +#include "lldb/Symbol/Type.h" +#include "lldb/Symbol/TypeSystem.h" +#include "lldb/Utility/ConstString.h" +#include "lldb/Utility/DataExtractor.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Scalar.h" +#include "lldb/Utility/Stream.h" + +#include "llvm/ADT/APSInt.h" +#include "llvm/Support/MathExtras.h" + +#include <memory> +#include <optional> + +using namespace lldb; +using namespace lldb_private; + +SBType::SBType() { LLDB_INSTRUMENT_VA(this); } + +SBType::SBType(const CompilerType &type) : m_opaque_sp(new TypeImpl(type)) {} + +SBType::SBType(const lldb::TypeSP &type_sp) + : m_opaque_sp(new TypeImpl(type_sp)) {} + +SBType::SBType(const lldb::TypeImplSP &type_impl_sp) + : m_opaque_sp(type_impl_sp) {} + +SBType::SBType(const SBType &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } +} + +// SBType::SBType (TypeImpl* impl) : +// m_opaque_up(impl) +//{} +// +bool SBType::operator==(SBType &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + + if (!rhs.IsValid()) + return false; + + return *m_opaque_sp.get() == *rhs.m_opaque_sp.get(); +} + +bool SBType::operator!=(SBType &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return rhs.IsValid(); + + if (!rhs.IsValid()) + return true; + + return *m_opaque_sp.get() != *rhs.m_opaque_sp.get(); +} + +lldb::TypeImplSP SBType::GetSP() { return m_opaque_sp; } + +void SBType::SetSP(const lldb::TypeImplSP &type_impl_sp) { + m_opaque_sp = type_impl_sp; +} + +SBType &SBType::operator=(const SBType &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; +} + +SBType::~SBType() = default; + +TypeImpl &SBType::ref() { + if (m_opaque_sp.get() == nullptr) + m_opaque_sp = std::make_shared<TypeImpl>(); + return *m_opaque_sp; +} + +const TypeImpl &SBType::ref() const { + // "const SBAddress &addr" should already have checked "addr.IsValid()" prior + // to calling this function. In case you didn't we will assert and die to let + // you know. + assert(m_opaque_sp.get()); + return *m_opaque_sp; +} + +bool SBType::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBType::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp.get() == nullptr) + return false; + + return m_opaque_sp->IsValid(); +} + +uint64_t SBType::GetByteSize() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + if (std::optional<uint64_t> size = + m_opaque_sp->GetCompilerType(false).GetByteSize(nullptr)) + return *size; + return 0; +} + +uint64_t SBType::GetByteAlign() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return 0; + + std::optional<uint64_t> bit_align = + m_opaque_sp->GetCompilerType(/*prefer_dynamic=*/false) + .GetTypeBitAlign(nullptr); + return llvm::divideCeil(bit_align.value_or(0), 8); +} + +bool SBType::IsPointerType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsPointerType(); +} + +bool SBType::IsArrayType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsArrayType(nullptr, nullptr, + nullptr); +} + +bool SBType::IsVectorType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsVectorType(nullptr, nullptr); +} + +bool SBType::IsReferenceType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsReferenceType(); +} + +SBType SBType::GetPointerType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return SBType(); + + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetPointerType()))); +} + +SBType SBType::GetPointeeType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return SBType(); + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetPointeeType()))); +} + +SBType SBType::GetReferenceType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return SBType(); + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetReferenceType()))); +} + +SBType SBType::GetTypedefedType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return SBType(); + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetTypedefedType()))); +} + +SBType SBType::GetDereferencedType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return SBType(); + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetDereferencedType()))); +} + +SBType SBType::GetArrayElementType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return SBType(); + return SBType(TypeImplSP(new TypeImpl( + m_opaque_sp->GetCompilerType(true).GetArrayElementType(nullptr)))); +} + +SBType SBType::GetArrayType(uint64_t size) { + LLDB_INSTRUMENT_VA(this, size); + + if (!IsValid()) + return SBType(); + return SBType(TypeImplSP( + new TypeImpl(m_opaque_sp->GetCompilerType(true).GetArrayType(size)))); +} + +SBType SBType::GetVectorElementType() { + LLDB_INSTRUMENT_VA(this); + + SBType type_sb; + if (IsValid()) { + CompilerType vector_element_type; + if (m_opaque_sp->GetCompilerType(true).IsVectorType(&vector_element_type, + nullptr)) + type_sb.SetSP(TypeImplSP(new TypeImpl(vector_element_type))); + } + return type_sb; +} + +bool SBType::IsFunctionType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsFunctionType(); +} + +bool SBType::IsPolymorphicClass() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsPolymorphicClass(); +} + +bool SBType::IsTypedefType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsTypedefType(); +} + +bool SBType::IsAnonymousType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsAnonymousType(); +} + +bool SBType::IsScopedEnumerationType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsScopedEnumerationType(); +} + +bool SBType::IsAggregateType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsAggregateType(); +} + +lldb::SBType SBType::GetFunctionReturnType() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) { + CompilerType return_type( + m_opaque_sp->GetCompilerType(true).GetFunctionReturnType()); + if (return_type.IsValid()) + return SBType(return_type); + } + return lldb::SBType(); +} + +lldb::SBTypeList SBType::GetFunctionArgumentTypes() { + LLDB_INSTRUMENT_VA(this); + + SBTypeList sb_type_list; + if (IsValid()) { + CompilerType func_type(m_opaque_sp->GetCompilerType(true)); + size_t count = func_type.GetNumberOfFunctionArguments(); + for (size_t i = 0; i < count; i++) { + sb_type_list.Append(SBType(func_type.GetFunctionArgumentAtIndex(i))); + } + } + return sb_type_list; +} + +uint32_t SBType::GetNumberOfMemberFunctions() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) { + return m_opaque_sp->GetCompilerType(true).GetNumMemberFunctions(); + } + return 0; +} + +lldb::SBTypeMemberFunction SBType::GetMemberFunctionAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBTypeMemberFunction sb_func_type; + if (IsValid()) + sb_func_type.reset(new TypeMemberFunctionImpl( + m_opaque_sp->GetCompilerType(true).GetMemberFunctionAtIndex(idx))); + return sb_func_type; +} + +SBTypeStaticField::SBTypeStaticField() { LLDB_INSTRUMENT_VA(this); } + +SBTypeStaticField::SBTypeStaticField(lldb_private::CompilerDecl decl) + : m_opaque_up(decl ? std::make_unique<CompilerDecl>(decl) : nullptr) {} + +SBTypeStaticField::SBTypeStaticField(const SBTypeStaticField &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBTypeStaticField &SBTypeStaticField::operator=(const SBTypeStaticField &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +SBTypeStaticField::~SBTypeStaticField() { LLDB_INSTRUMENT_VA(this); } + +SBTypeStaticField::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return IsValid(); +} + +bool SBTypeStaticField::IsValid() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up != nullptr; +} + +const char *SBTypeStaticField::GetName() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return ""; + return m_opaque_up->GetName().GetCString(); +} + +const char *SBTypeStaticField::GetMangledName() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return ""; + return m_opaque_up->GetMangledName().GetCString(); +} + +SBType SBTypeStaticField::GetType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return SBType(); + return SBType(m_opaque_up->GetType()); +} + +SBValue SBTypeStaticField::GetConstantValue(lldb::SBTarget target) { + LLDB_INSTRUMENT_VA(this, target); + + if (!IsValid()) + return SBValue(); + + Scalar value = m_opaque_up->GetConstantValue(); + if (!value.IsValid()) + return SBValue(); + DataExtractor data; + value.GetData(data); + auto value_obj_sp = ValueObjectConstResult::Create( + target.GetSP().get(), m_opaque_up->GetType(), m_opaque_up->GetName(), + data); + return SBValue(std::move(value_obj_sp)); +} + +lldb::SBType SBType::GetUnqualifiedType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return SBType(); + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetUnqualifiedType()))); +} + +lldb::SBType SBType::GetCanonicalType() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetCanonicalType()))); + return SBType(); +} + +SBType SBType::GetEnumerationIntegerType() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) { + return SBType( + m_opaque_sp->GetCompilerType(true).GetEnumerationIntegerType()); + } + return SBType(); +} + +lldb::BasicType SBType::GetBasicType() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return m_opaque_sp->GetCompilerType(false).GetBasicTypeEnumeration(); + return eBasicTypeInvalid; +} + +SBType SBType::GetBasicType(lldb::BasicType basic_type) { + LLDB_INSTRUMENT_VA(this, basic_type); + + if (IsValid() && m_opaque_sp->IsValid()) + if (auto ts = m_opaque_sp->GetTypeSystem(false)) + return SBType(ts->GetBasicTypeFromAST(basic_type)); + return SBType(); +} + +uint32_t SBType::GetNumberOfDirectBaseClasses() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return m_opaque_sp->GetCompilerType(true).GetNumDirectBaseClasses(); + return 0; +} + +uint32_t SBType::GetNumberOfVirtualBaseClasses() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return m_opaque_sp->GetCompilerType(true).GetNumVirtualBaseClasses(); + return 0; +} + +uint32_t SBType::GetNumberOfFields() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return m_opaque_sp->GetCompilerType(true).GetNumFields(); + return 0; +} + +bool SBType::GetDescription(SBStream &description, + lldb::DescriptionLevel description_level) { + LLDB_INSTRUMENT_VA(this, description, description_level); + + Stream &strm = description.ref(); + + if (m_opaque_sp) { + m_opaque_sp->GetDescription(strm, description_level); + } else + strm.PutCString("No value"); + + return true; +} + +SBTypeMember SBType::GetDirectBaseClassAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBTypeMember sb_type_member; + if (IsValid()) { + uint32_t bit_offset = 0; + CompilerType base_class_type = + m_opaque_sp->GetCompilerType(true).GetDirectBaseClassAtIndex( + idx, &bit_offset); + if (base_class_type.IsValid()) + sb_type_member.reset(new TypeMemberImpl( + TypeImplSP(new TypeImpl(base_class_type)), bit_offset)); + } + return sb_type_member; +} + +SBTypeMember SBType::GetVirtualBaseClassAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBTypeMember sb_type_member; + if (IsValid()) { + uint32_t bit_offset = 0; + CompilerType base_class_type = + m_opaque_sp->GetCompilerType(true).GetVirtualBaseClassAtIndex( + idx, &bit_offset); + if (base_class_type.IsValid()) + sb_type_member.reset(new TypeMemberImpl( + TypeImplSP(new TypeImpl(base_class_type)), bit_offset)); + } + return sb_type_member; +} + +SBTypeStaticField SBType::GetStaticFieldWithName(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + + if (!IsValid() || !name) + return SBTypeStaticField(); + + return SBTypeStaticField(m_opaque_sp->GetCompilerType(/*prefer_dynamic=*/true) + .GetStaticFieldWithName(name)); +} + +SBTypeEnumMemberList SBType::GetEnumMembers() { + LLDB_INSTRUMENT_VA(this); + + SBTypeEnumMemberList sb_enum_member_list; + if (IsValid()) { + CompilerType this_type(m_opaque_sp->GetCompilerType(true)); + if (this_type.IsValid()) { + this_type.ForEachEnumerator([&sb_enum_member_list]( + const CompilerType &integer_type, + ConstString name, + const llvm::APSInt &value) -> bool { + SBTypeEnumMember enum_member( + lldb::TypeEnumMemberImplSP(new TypeEnumMemberImpl( + lldb::TypeImplSP(new TypeImpl(integer_type)), name, value))); + sb_enum_member_list.Append(enum_member); + return true; // Keep iterating + }); + } + } + return sb_enum_member_list; +} + +SBTypeMember SBType::GetFieldAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + SBTypeMember sb_type_member; + if (IsValid()) { + CompilerType this_type(m_opaque_sp->GetCompilerType(false)); + if (this_type.IsValid()) { + uint64_t bit_offset = 0; + uint32_t bitfield_bit_size = 0; + bool is_bitfield = false; + std::string name_sstr; + CompilerType field_type(this_type.GetFieldAtIndex( + idx, name_sstr, &bit_offset, &bitfield_bit_size, &is_bitfield)); + if (field_type.IsValid()) { + ConstString name; + if (!name_sstr.empty()) + name.SetCString(name_sstr.c_str()); + sb_type_member.reset( + new TypeMemberImpl(TypeImplSP(new TypeImpl(field_type)), bit_offset, + name, bitfield_bit_size, is_bitfield)); + } + } + } + return sb_type_member; +} + +bool SBType::IsTypeComplete() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + CompilerType compiler_type = m_opaque_sp->GetCompilerType(false); + // Only return true if we have a complete type and it wasn't forcefully + // completed. + if (compiler_type.IsCompleteType()) + return !compiler_type.IsForcefullyCompleted(); + return false; +} + +uint32_t SBType::GetTypeFlags() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return 0; + return m_opaque_sp->GetCompilerType(true).GetTypeInfo(); +} + +lldb::SBModule SBType::GetModule() { + LLDB_INSTRUMENT_VA(this); + + lldb::SBModule sb_module; + if (!IsValid()) + return sb_module; + + sb_module.SetSP(m_opaque_sp->GetModule()); + return sb_module; +} + +const char *SBType::GetName() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return ""; + return m_opaque_sp->GetName().GetCString(); +} + +const char *SBType::GetDisplayTypeName() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return ""; + return m_opaque_sp->GetDisplayTypeName().GetCString(); +} + +lldb::TypeClass SBType::GetTypeClass() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return m_opaque_sp->GetCompilerType(true).GetTypeClass(); + return lldb::eTypeClassInvalid; +} + +uint32_t SBType::GetNumberOfTemplateArguments() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return m_opaque_sp->GetCompilerType(false).GetNumTemplateArguments( + /*expand_pack=*/true); + return 0; +} + +lldb::SBType SBType::GetTemplateArgumentType(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + if (!IsValid()) + return SBType(); + + CompilerType type; + const bool expand_pack = true; + switch(GetTemplateArgumentKind(idx)) { + case eTemplateArgumentKindType: + type = m_opaque_sp->GetCompilerType(false).GetTypeTemplateArgument( + idx, expand_pack); + break; + case eTemplateArgumentKindIntegral: + type = m_opaque_sp->GetCompilerType(false) + .GetIntegralTemplateArgument(idx, expand_pack) + ->type; + break; + default: + break; + } + if (type.IsValid()) + return SBType(type); + return SBType(); +} + +lldb::TemplateArgumentKind SBType::GetTemplateArgumentKind(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + if (IsValid()) + return m_opaque_sp->GetCompilerType(false).GetTemplateArgumentKind( + idx, /*expand_pack=*/true); + return eTemplateArgumentKindNull; +} + +SBType SBType::FindDirectNestedType(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + + if (!IsValid()) + return SBType(); + return SBType(m_opaque_sp->FindDirectNestedType(name)); +} + +SBTypeList::SBTypeList() : m_opaque_up(new TypeListImpl()) { + LLDB_INSTRUMENT_VA(this); +} + +SBTypeList::SBTypeList(const SBTypeList &rhs) + : m_opaque_up(new TypeListImpl()) { + LLDB_INSTRUMENT_VA(this, rhs); + + for (uint32_t i = 0, rhs_size = const_cast<SBTypeList &>(rhs).GetSize(); + i < rhs_size; i++) + Append(const_cast<SBTypeList &>(rhs).GetTypeAtIndex(i)); +} + +bool SBTypeList::IsValid() { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTypeList::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_up != nullptr); +} + +SBTypeList &SBTypeList::operator=(const SBTypeList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_up = std::make_unique<TypeListImpl>(); + for (uint32_t i = 0, rhs_size = const_cast<SBTypeList &>(rhs).GetSize(); + i < rhs_size; i++) + Append(const_cast<SBTypeList &>(rhs).GetTypeAtIndex(i)); + } + return *this; +} + +void SBTypeList::Append(SBType type) { + LLDB_INSTRUMENT_VA(this, type); + + if (type.IsValid()) + m_opaque_up->Append(type.m_opaque_sp); +} + +SBType SBTypeList::GetTypeAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + if (m_opaque_up) + return SBType(m_opaque_up->GetTypeAtIndex(index)); + return SBType(); +} + +uint32_t SBTypeList::GetSize() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetSize(); +} + +SBTypeList::~SBTypeList() = default; + +SBTypeMember::SBTypeMember() { LLDB_INSTRUMENT_VA(this); } + +SBTypeMember::~SBTypeMember() = default; + +SBTypeMember::SBTypeMember(const SBTypeMember &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + if (rhs.IsValid()) + m_opaque_up = std::make_unique<TypeMemberImpl>(rhs.ref()); + } +} + +lldb::SBTypeMember &SBTypeMember::operator=(const lldb::SBTypeMember &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + if (rhs.IsValid()) + m_opaque_up = std::make_unique<TypeMemberImpl>(rhs.ref()); + } + return *this; +} + +bool SBTypeMember::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTypeMember::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up.get(); +} + +const char *SBTypeMember::GetName() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + return m_opaque_up->GetName().GetCString(); + return nullptr; +} + +SBType SBTypeMember::GetType() { + LLDB_INSTRUMENT_VA(this); + + SBType sb_type; + if (m_opaque_up) { + sb_type.SetSP(m_opaque_up->GetTypeImpl()); + } + return sb_type; +} + +uint64_t SBTypeMember::GetOffsetInBytes() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + return m_opaque_up->GetBitOffset() / 8u; + return 0; +} + +uint64_t SBTypeMember::GetOffsetInBits() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + return m_opaque_up->GetBitOffset(); + return 0; +} + +bool SBTypeMember::IsBitfield() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + return m_opaque_up->GetIsBitfield(); + return false; +} + +uint32_t SBTypeMember::GetBitfieldSizeInBits() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_up) + return m_opaque_up->GetBitfieldBitSize(); + return 0; +} + +bool SBTypeMember::GetDescription(lldb::SBStream &description, + lldb::DescriptionLevel description_level) { + LLDB_INSTRUMENT_VA(this, description, description_level); + + Stream &strm = description.ref(); + + if (m_opaque_up) { + const uint32_t bit_offset = m_opaque_up->GetBitOffset(); + const uint32_t byte_offset = bit_offset / 8u; + const uint32_t byte_bit_offset = bit_offset % 8u; + const char *name = m_opaque_up->GetName().GetCString(); + if (byte_bit_offset) + strm.Printf("+%u + %u bits: (", byte_offset, byte_bit_offset); + else + strm.Printf("+%u: (", byte_offset); + + TypeImplSP type_impl_sp(m_opaque_up->GetTypeImpl()); + if (type_impl_sp) + type_impl_sp->GetDescription(strm, description_level); + + strm.Printf(") %s", name); + if (m_opaque_up->GetIsBitfield()) { + const uint32_t bitfield_bit_size = m_opaque_up->GetBitfieldBitSize(); + strm.Printf(" : %u", bitfield_bit_size); + } + } else { + strm.PutCString("No value"); + } + return true; +} + +void SBTypeMember::reset(TypeMemberImpl *type_member_impl) { + m_opaque_up.reset(type_member_impl); +} + +TypeMemberImpl &SBTypeMember::ref() { + if (m_opaque_up == nullptr) + m_opaque_up = std::make_unique<TypeMemberImpl>(); + return *m_opaque_up; +} + +const TypeMemberImpl &SBTypeMember::ref() const { return *m_opaque_up; } + +SBTypeMemberFunction::SBTypeMemberFunction() { LLDB_INSTRUMENT_VA(this); } + +SBTypeMemberFunction::~SBTypeMemberFunction() = default; + +SBTypeMemberFunction::SBTypeMemberFunction(const SBTypeMemberFunction &rhs) + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +lldb::SBTypeMemberFunction &SBTypeMemberFunction:: +operator=(const lldb::SBTypeMemberFunction &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; +} + +bool SBTypeMemberFunction::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTypeMemberFunction::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get(); +} + +const char *SBTypeMemberFunction::GetName() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + return m_opaque_sp->GetName().GetCString(); + return nullptr; +} + +const char *SBTypeMemberFunction::GetDemangledName() { + LLDB_INSTRUMENT_VA(this); + + if (!m_opaque_sp) + return nullptr; + + ConstString mangled_str = m_opaque_sp->GetMangledName(); + if (!mangled_str) + return nullptr; + + Mangled mangled(mangled_str); + return mangled.GetDemangledName().GetCString(); +} + +const char *SBTypeMemberFunction::GetMangledName() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + return m_opaque_sp->GetMangledName().GetCString(); + return nullptr; +} + +SBType SBTypeMemberFunction::GetType() { + LLDB_INSTRUMENT_VA(this); + + SBType sb_type; + if (m_opaque_sp) { + sb_type.SetSP(lldb::TypeImplSP(new TypeImpl(m_opaque_sp->GetType()))); + } + return sb_type; +} + +lldb::SBType SBTypeMemberFunction::GetReturnType() { + LLDB_INSTRUMENT_VA(this); + + SBType sb_type; + if (m_opaque_sp) { + sb_type.SetSP(lldb::TypeImplSP(new TypeImpl(m_opaque_sp->GetReturnType()))); + } + return sb_type; +} + +uint32_t SBTypeMemberFunction::GetNumberOfArguments() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + return m_opaque_sp->GetNumArguments(); + return 0; +} + +lldb::SBType SBTypeMemberFunction::GetArgumentTypeAtIndex(uint32_t i) { + LLDB_INSTRUMENT_VA(this, i); + + SBType sb_type; + if (m_opaque_sp) { + sb_type.SetSP( + lldb::TypeImplSP(new TypeImpl(m_opaque_sp->GetArgumentAtIndex(i)))); + } + return sb_type; +} + +lldb::MemberFunctionKind SBTypeMemberFunction::GetKind() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp) + return m_opaque_sp->GetKind(); + return lldb::eMemberFunctionKindUnknown; +} + +bool SBTypeMemberFunction::GetDescription( + lldb::SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_INSTRUMENT_VA(this, description, description_level); + + Stream &strm = description.ref(); + + if (m_opaque_sp) + return m_opaque_sp->GetDescription(strm); + + return false; +} + +void SBTypeMemberFunction::reset(TypeMemberFunctionImpl *type_member_impl) { + m_opaque_sp.reset(type_member_impl); +} + +TypeMemberFunctionImpl &SBTypeMemberFunction::ref() { + if (!m_opaque_sp) + m_opaque_sp = std::make_shared<TypeMemberFunctionImpl>(); + return *m_opaque_sp.get(); +} + +const TypeMemberFunctionImpl &SBTypeMemberFunction::ref() const { + return *m_opaque_sp.get(); +} diff --git a/contrib/llvm-project/lldb/source/API/SBTypeCategory.cpp b/contrib/llvm-project/lldb/source/API/SBTypeCategory.cpp new file mode 100644 index 000000000000..3521a30c64c5 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBTypeCategory.cpp @@ -0,0 +1,544 @@ +//===-- SBTypeCategory.cpp ------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBTypeCategory.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBStream.h" +#include "lldb/API/SBTypeFilter.h" +#include "lldb/API/SBTypeFormat.h" +#include "lldb/API/SBTypeNameSpecifier.h" +#include "lldb/API/SBTypeSummary.h" +#include "lldb/API/SBTypeSynthetic.h" + +#include "lldb/Core/Debugger.h" +#include "lldb/DataFormatters/DataVisualization.h" +#include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Interpreter/ScriptInterpreter.h" + +using namespace lldb; +using namespace lldb_private; + +typedef std::pair<lldb::TypeCategoryImplSP, user_id_t> ImplType; + +SBTypeCategory::SBTypeCategory() { LLDB_INSTRUMENT_VA(this); } + +SBTypeCategory::SBTypeCategory(const char *name) { + DataVisualization::Categories::GetCategory(ConstString(name), m_opaque_sp); +} + +SBTypeCategory::SBTypeCategory(const lldb::SBTypeCategory &rhs) + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBTypeCategory::~SBTypeCategory() = default; + +bool SBTypeCategory::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTypeCategory::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_sp.get() != nullptr); +} + +bool SBTypeCategory::GetEnabled() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return m_opaque_sp->IsEnabled(); +} + +void SBTypeCategory::SetEnabled(bool enabled) { + LLDB_INSTRUMENT_VA(this, enabled); + + if (!IsValid()) + return; + if (enabled) + DataVisualization::Categories::Enable(m_opaque_sp); + else + DataVisualization::Categories::Disable(m_opaque_sp); +} + +const char *SBTypeCategory::GetName() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return nullptr; + return ConstString(m_opaque_sp->GetName()).GetCString(); +} + +lldb::LanguageType SBTypeCategory::GetLanguageAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + if (IsValid()) + return m_opaque_sp->GetLanguageAtIndex(idx); + return lldb::eLanguageTypeUnknown; +} + +uint32_t SBTypeCategory::GetNumLanguages() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return m_opaque_sp->GetNumLanguages(); + return 0; +} + +void SBTypeCategory::AddLanguage(lldb::LanguageType language) { + LLDB_INSTRUMENT_VA(this, language); + + if (IsValid()) + m_opaque_sp->AddLanguage(language); +} + +uint32_t SBTypeCategory::GetNumFormats() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return 0; + + return m_opaque_sp->GetNumFormats(); +} + +uint32_t SBTypeCategory::GetNumSummaries() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return 0; + return m_opaque_sp->GetNumSummaries(); +} + +uint32_t SBTypeCategory::GetNumFilters() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return 0; + return m_opaque_sp->GetNumFilters(); +} + +uint32_t SBTypeCategory::GetNumSynthetics() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return 0; + return m_opaque_sp->GetNumSynthetics(); +} + +lldb::SBTypeNameSpecifier +SBTypeCategory::GetTypeNameSpecifierForFilterAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + if (!IsValid()) + return SBTypeNameSpecifier(); + return SBTypeNameSpecifier( + m_opaque_sp->GetTypeNameSpecifierForFilterAtIndex(index)); +} + +lldb::SBTypeNameSpecifier +SBTypeCategory::GetTypeNameSpecifierForFormatAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + if (!IsValid()) + return SBTypeNameSpecifier(); + return SBTypeNameSpecifier( + m_opaque_sp->GetTypeNameSpecifierForFormatAtIndex(index)); +} + +lldb::SBTypeNameSpecifier +SBTypeCategory::GetTypeNameSpecifierForSummaryAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + if (!IsValid()) + return SBTypeNameSpecifier(); + return SBTypeNameSpecifier( + m_opaque_sp->GetTypeNameSpecifierForSummaryAtIndex(index)); +} + +lldb::SBTypeNameSpecifier +SBTypeCategory::GetTypeNameSpecifierForSyntheticAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + if (!IsValid()) + return SBTypeNameSpecifier(); + return SBTypeNameSpecifier( + m_opaque_sp->GetTypeNameSpecifierForSyntheticAtIndex(index)); +} + +SBTypeFilter SBTypeCategory::GetFilterForType(SBTypeNameSpecifier spec) { + LLDB_INSTRUMENT_VA(this, spec); + + if (!IsValid()) + return SBTypeFilter(); + + if (!spec.IsValid()) + return SBTypeFilter(); + + lldb::TypeFilterImplSP children_sp = + m_opaque_sp->GetFilterForType(spec.GetSP()); + + if (!children_sp) + return lldb::SBTypeFilter(); + + TypeFilterImplSP filter_sp = + std::static_pointer_cast<TypeFilterImpl>(children_sp); + + return lldb::SBTypeFilter(filter_sp); +} +SBTypeFormat SBTypeCategory::GetFormatForType(SBTypeNameSpecifier spec) { + LLDB_INSTRUMENT_VA(this, spec); + + if (!IsValid()) + return SBTypeFormat(); + + if (!spec.IsValid()) + return SBTypeFormat(); + + lldb::TypeFormatImplSP format_sp = + m_opaque_sp->GetFormatForType(spec.GetSP()); + + if (!format_sp) + return lldb::SBTypeFormat(); + + return lldb::SBTypeFormat(format_sp); +} + +SBTypeSummary SBTypeCategory::GetSummaryForType(SBTypeNameSpecifier spec) { + LLDB_INSTRUMENT_VA(this, spec); + + if (!IsValid()) + return SBTypeSummary(); + + if (!spec.IsValid()) + return SBTypeSummary(); + + lldb::TypeSummaryImplSP summary_sp = + m_opaque_sp->GetSummaryForType(spec.GetSP()); + + if (!summary_sp) + return lldb::SBTypeSummary(); + + return lldb::SBTypeSummary(summary_sp); +} + +SBTypeSynthetic SBTypeCategory::GetSyntheticForType(SBTypeNameSpecifier spec) { + LLDB_INSTRUMENT_VA(this, spec); + + if (!IsValid()) + return SBTypeSynthetic(); + + if (!spec.IsValid()) + return SBTypeSynthetic(); + + lldb::SyntheticChildrenSP children_sp = + m_opaque_sp->GetSyntheticForType(spec.GetSP()); + + if (!children_sp) + return lldb::SBTypeSynthetic(); + + ScriptedSyntheticChildrenSP synth_sp = + std::static_pointer_cast<ScriptedSyntheticChildren>(children_sp); + + return lldb::SBTypeSynthetic(synth_sp); +} + +SBTypeFilter SBTypeCategory::GetFilterAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + if (!IsValid()) + return SBTypeFilter(); + lldb::SyntheticChildrenSP children_sp = + m_opaque_sp->GetSyntheticAtIndex((index)); + + if (!children_sp.get()) + return lldb::SBTypeFilter(); + + TypeFilterImplSP filter_sp = + std::static_pointer_cast<TypeFilterImpl>(children_sp); + + return lldb::SBTypeFilter(filter_sp); +} + +SBTypeFormat SBTypeCategory::GetFormatAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + if (!IsValid()) + return SBTypeFormat(); + return SBTypeFormat(m_opaque_sp->GetFormatAtIndex((index))); +} + +SBTypeSummary SBTypeCategory::GetSummaryAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + if (!IsValid()) + return SBTypeSummary(); + return SBTypeSummary(m_opaque_sp->GetSummaryAtIndex((index))); +} + +SBTypeSynthetic SBTypeCategory::GetSyntheticAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + if (!IsValid()) + return SBTypeSynthetic(); + lldb::SyntheticChildrenSP children_sp = + m_opaque_sp->GetSyntheticAtIndex((index)); + + if (!children_sp.get()) + return lldb::SBTypeSynthetic(); + + ScriptedSyntheticChildrenSP synth_sp = + std::static_pointer_cast<ScriptedSyntheticChildren>(children_sp); + + return lldb::SBTypeSynthetic(synth_sp); +} + +bool SBTypeCategory::AddTypeFormat(SBTypeNameSpecifier type_name, + SBTypeFormat format) { + LLDB_INSTRUMENT_VA(this, type_name, format); + + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + if (!format.IsValid()) + return false; + + m_opaque_sp->AddTypeFormat(type_name.GetSP(), format.GetSP()); + return true; +} + +bool SBTypeCategory::DeleteTypeFormat(SBTypeNameSpecifier type_name) { + LLDB_INSTRUMENT_VA(this, type_name); + + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + return m_opaque_sp->DeleteTypeFormat(type_name.GetSP()); +} + +bool SBTypeCategory::AddTypeSummary(SBTypeNameSpecifier type_name, + SBTypeSummary summary) { + LLDB_INSTRUMENT_VA(this, type_name, summary); + + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + if (!summary.IsValid()) + return false; + + // FIXME: we need to iterate over all the Debugger objects and have each of + // them contain a copy of the function + // since we currently have formatters live in a global space, while Python + // code lives in a specific Debugger-related environment this should + // eventually be fixed by deciding a final location in the LLDB object space + // for formatters + if (summary.IsFunctionCode()) { + const void *name_token = + (const void *)ConstString(type_name.GetName()).GetCString(); + const char *script = summary.GetData(); + StringList input; + input.SplitIntoLines(script, strlen(script)); + uint32_t num_debuggers = lldb_private::Debugger::GetNumDebuggers(); + bool need_set = true; + for (uint32_t j = 0; j < num_debuggers; j++) { + DebuggerSP debugger_sp = lldb_private::Debugger::GetDebuggerAtIndex(j); + if (debugger_sp) { + ScriptInterpreter *interpreter_ptr = + debugger_sp->GetScriptInterpreter(); + if (interpreter_ptr) { + std::string output; + if (interpreter_ptr->GenerateTypeScriptFunction(input, output, + name_token) && + !output.empty()) { + if (need_set) { + need_set = false; + summary.SetFunctionName(output.c_str()); + } + } + } + } + } + } + + m_opaque_sp->AddTypeSummary(type_name.GetSP(), summary.GetSP()); + return true; +} + +bool SBTypeCategory::DeleteTypeSummary(SBTypeNameSpecifier type_name) { + LLDB_INSTRUMENT_VA(this, type_name); + + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + return m_opaque_sp->DeleteTypeSummary(type_name.GetSP()); +} + +bool SBTypeCategory::AddTypeFilter(SBTypeNameSpecifier type_name, + SBTypeFilter filter) { + LLDB_INSTRUMENT_VA(this, type_name, filter); + + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + if (!filter.IsValid()) + return false; + + m_opaque_sp->AddTypeFilter(type_name.GetSP(), filter.GetSP()); + return true; +} + +bool SBTypeCategory::DeleteTypeFilter(SBTypeNameSpecifier type_name) { + LLDB_INSTRUMENT_VA(this, type_name); + + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + return m_opaque_sp->DeleteTypeFilter(type_name.GetSP()); +} + +bool SBTypeCategory::AddTypeSynthetic(SBTypeNameSpecifier type_name, + SBTypeSynthetic synth) { + LLDB_INSTRUMENT_VA(this, type_name, synth); + + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + if (!synth.IsValid()) + return false; + + // FIXME: we need to iterate over all the Debugger objects and have each of + // them contain a copy of the function + // since we currently have formatters live in a global space, while Python + // code lives in a specific Debugger-related environment this should + // eventually be fixed by deciding a final location in the LLDB object space + // for formatters + if (synth.IsClassCode()) { + const void *name_token = + (const void *)ConstString(type_name.GetName()).GetCString(); + const char *script = synth.GetData(); + StringList input; + input.SplitIntoLines(script, strlen(script)); + uint32_t num_debuggers = lldb_private::Debugger::GetNumDebuggers(); + bool need_set = true; + for (uint32_t j = 0; j < num_debuggers; j++) { + DebuggerSP debugger_sp = lldb_private::Debugger::GetDebuggerAtIndex(j); + if (debugger_sp) { + ScriptInterpreter *interpreter_ptr = + debugger_sp->GetScriptInterpreter(); + if (interpreter_ptr) { + std::string output; + if (interpreter_ptr->GenerateTypeSynthClass(input, output, + name_token) && + !output.empty()) { + if (need_set) { + need_set = false; + synth.SetClassName(output.c_str()); + } + } + } + } + } + } + + m_opaque_sp->AddTypeSynthetic(type_name.GetSP(), synth.GetSP()); + return true; +} + +bool SBTypeCategory::DeleteTypeSynthetic(SBTypeNameSpecifier type_name) { + LLDB_INSTRUMENT_VA(this, type_name); + + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + return m_opaque_sp->DeleteTypeSynthetic(type_name.GetSP()); +} + +bool SBTypeCategory::GetDescription(lldb::SBStream &description, + lldb::DescriptionLevel description_level) { + LLDB_INSTRUMENT_VA(this, description, description_level); + + if (!IsValid()) + return false; + description.Printf("Category name: %s\n", GetName()); + return true; +} + +lldb::SBTypeCategory &SBTypeCategory:: +operator=(const lldb::SBTypeCategory &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; +} + +bool SBTypeCategory::operator==(lldb::SBTypeCategory &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + + return m_opaque_sp.get() == rhs.m_opaque_sp.get(); +} + +bool SBTypeCategory::operator!=(lldb::SBTypeCategory &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return rhs.IsValid(); + + return m_opaque_sp.get() != rhs.m_opaque_sp.get(); +} + +lldb::TypeCategoryImplSP SBTypeCategory::GetSP() { + if (!IsValid()) + return lldb::TypeCategoryImplSP(); + return m_opaque_sp; +} + +void SBTypeCategory::SetSP( + const lldb::TypeCategoryImplSP &typecategory_impl_sp) { + m_opaque_sp = typecategory_impl_sp; +} + +SBTypeCategory::SBTypeCategory( + const lldb::TypeCategoryImplSP &typecategory_impl_sp) + : m_opaque_sp(typecategory_impl_sp) {} + +bool SBTypeCategory::IsDefaultCategory() { + if (!IsValid()) + return false; + + return (strcmp(m_opaque_sp->GetName(), "default") == 0); +} diff --git a/contrib/llvm-project/lldb/source/API/SBTypeEnumMember.cpp b/contrib/llvm-project/lldb/source/API/SBTypeEnumMember.cpp new file mode 100644 index 000000000000..a3d99bd57e31 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBTypeEnumMember.cpp @@ -0,0 +1,183 @@ +//===-- SBTypeEnumMember.cpp ----------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBTypeEnumMember.h" +#include "Utils.h" +#include "lldb/API/SBDefines.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBType.h" +#include "lldb/Symbol/CompilerType.h" +#include "lldb/Symbol/Type.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Stream.h" + +#include <memory> + +using namespace lldb; +using namespace lldb_private; + +SBTypeEnumMember::SBTypeEnumMember() { LLDB_INSTRUMENT_VA(this); } + +SBTypeEnumMember::~SBTypeEnumMember() = default; + +SBTypeEnumMember::SBTypeEnumMember( + const lldb::TypeEnumMemberImplSP &enum_member_sp) + : m_opaque_sp(enum_member_sp) {} + +SBTypeEnumMember::SBTypeEnumMember(const SBTypeEnumMember &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_sp = clone(rhs.m_opaque_sp); +} + +SBTypeEnumMember &SBTypeEnumMember::operator=(const SBTypeEnumMember &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_sp = clone(rhs.m_opaque_sp); + return *this; +} + +bool SBTypeEnumMember::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTypeEnumMember::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get(); +} + +const char *SBTypeEnumMember::GetName() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp.get()) + return m_opaque_sp->GetName().GetCString(); + return nullptr; +} + +int64_t SBTypeEnumMember::GetValueAsSigned() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp.get()) + return m_opaque_sp->GetValueAsSigned(); + return 0; +} + +uint64_t SBTypeEnumMember::GetValueAsUnsigned() { + LLDB_INSTRUMENT_VA(this); + + if (m_opaque_sp.get()) + return m_opaque_sp->GetValueAsUnsigned(); + return 0; +} + +SBType SBTypeEnumMember::GetType() { + LLDB_INSTRUMENT_VA(this); + + SBType sb_type; + if (m_opaque_sp.get()) { + sb_type.SetSP(m_opaque_sp->GetIntegerType()); + } + return sb_type; +} + +void SBTypeEnumMember::reset(TypeEnumMemberImpl *type_member_impl) { + m_opaque_sp.reset(type_member_impl); +} + +TypeEnumMemberImpl &SBTypeEnumMember::ref() { + if (m_opaque_sp.get() == nullptr) + m_opaque_sp = std::make_shared<TypeEnumMemberImpl>(); + return *m_opaque_sp.get(); +} + +const TypeEnumMemberImpl &SBTypeEnumMember::ref() const { + return *m_opaque_sp.get(); +} + +SBTypeEnumMemberList::SBTypeEnumMemberList() + : m_opaque_up(new TypeEnumMemberListImpl()) { + LLDB_INSTRUMENT_VA(this); +} + +SBTypeEnumMemberList::SBTypeEnumMemberList(const SBTypeEnumMemberList &rhs) + : m_opaque_up(new TypeEnumMemberListImpl()) { + LLDB_INSTRUMENT_VA(this, rhs); + + for (uint32_t i = 0, + rhs_size = const_cast<SBTypeEnumMemberList &>(rhs).GetSize(); + i < rhs_size; i++) + Append(const_cast<SBTypeEnumMemberList &>(rhs).GetTypeEnumMemberAtIndex(i)); +} + +bool SBTypeEnumMemberList::IsValid() { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTypeEnumMemberList::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_up != nullptr); +} + +SBTypeEnumMemberList &SBTypeEnumMemberList:: +operator=(const SBTypeEnumMemberList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_up = std::make_unique<TypeEnumMemberListImpl>(); + for (uint32_t i = 0, + rhs_size = const_cast<SBTypeEnumMemberList &>(rhs).GetSize(); + i < rhs_size; i++) + Append( + const_cast<SBTypeEnumMemberList &>(rhs).GetTypeEnumMemberAtIndex(i)); + } + return *this; +} + +void SBTypeEnumMemberList::Append(SBTypeEnumMember enum_member) { + LLDB_INSTRUMENT_VA(this, enum_member); + + if (enum_member.IsValid()) + m_opaque_up->Append(enum_member.m_opaque_sp); +} + +SBTypeEnumMember +SBTypeEnumMemberList::GetTypeEnumMemberAtIndex(uint32_t index) { + LLDB_INSTRUMENT_VA(this, index); + + if (m_opaque_up) + return SBTypeEnumMember(m_opaque_up->GetTypeEnumMemberAtIndex(index)); + return SBTypeEnumMember(); +} + +uint32_t SBTypeEnumMemberList::GetSize() { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetSize(); +} + +SBTypeEnumMemberList::~SBTypeEnumMemberList() = default; + +bool SBTypeEnumMember::GetDescription( + lldb::SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_INSTRUMENT_VA(this, description, description_level); + + Stream &strm = description.ref(); + + if (m_opaque_sp.get()) { + if (m_opaque_sp->GetIntegerType()->GetDescription(strm, + description_level)) { + strm.Printf(" %s", m_opaque_sp->GetName().GetCString()); + } + } else { + strm.PutCString("No value"); + } + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBTypeFilter.cpp b/contrib/llvm-project/lldb/source/API/SBTypeFilter.cpp new file mode 100644 index 000000000000..f1b5bc952b86 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBTypeFilter.cpp @@ -0,0 +1,180 @@ +//===-- SBTypeFilter.cpp --------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBTypeFilter.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBStream.h" + +#include "lldb/DataFormatters/DataVisualization.h" + +using namespace lldb; +using namespace lldb_private; + +SBTypeFilter::SBTypeFilter() { LLDB_INSTRUMENT_VA(this); } + +SBTypeFilter::SBTypeFilter(uint32_t options) + : m_opaque_sp(TypeFilterImplSP(new TypeFilterImpl(options))) { + LLDB_INSTRUMENT_VA(this, options); +} + +SBTypeFilter::SBTypeFilter(const lldb::SBTypeFilter &rhs) + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBTypeFilter::~SBTypeFilter() = default; + +bool SBTypeFilter::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTypeFilter::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} + +uint32_t SBTypeFilter::GetOptions() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return m_opaque_sp->GetOptions(); + return 0; +} + +void SBTypeFilter::SetOptions(uint32_t value) { + LLDB_INSTRUMENT_VA(this, value); + + if (CopyOnWrite_Impl()) + m_opaque_sp->SetOptions(value); +} + +bool SBTypeFilter::GetDescription(lldb::SBStream &description, + lldb::DescriptionLevel description_level) { + LLDB_INSTRUMENT_VA(this, description, description_level); + + if (!IsValid()) + return false; + else { + description.Printf("%s\n", m_opaque_sp->GetDescription().c_str()); + return true; + } +} + +void SBTypeFilter::Clear() { + LLDB_INSTRUMENT_VA(this); + + if (CopyOnWrite_Impl()) + m_opaque_sp->Clear(); +} + +uint32_t SBTypeFilter::GetNumberOfExpressionPaths() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return m_opaque_sp->GetCount(); + return 0; +} + +const char *SBTypeFilter::GetExpressionPathAtIndex(uint32_t i) { + LLDB_INSTRUMENT_VA(this, i); + + if (!IsValid()) + return nullptr; + + const char *item = m_opaque_sp->GetExpressionPathAtIndex(i); + if (item && *item == '.') + item++; + return ConstString(item).GetCString(); +} + +bool SBTypeFilter::ReplaceExpressionPathAtIndex(uint32_t i, const char *item) { + LLDB_INSTRUMENT_VA(this, i, item); + + if (CopyOnWrite_Impl()) + return m_opaque_sp->SetExpressionPathAtIndex(i, item); + else + return false; +} + +void SBTypeFilter::AppendExpressionPath(const char *item) { + LLDB_INSTRUMENT_VA(this, item); + + if (CopyOnWrite_Impl()) + m_opaque_sp->AddExpressionPath(item); +} + +lldb::SBTypeFilter &SBTypeFilter::operator=(const lldb::SBTypeFilter &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; +} + +bool SBTypeFilter::operator==(lldb::SBTypeFilter &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + + return m_opaque_sp == rhs.m_opaque_sp; +} + +bool SBTypeFilter::IsEqualTo(lldb::SBTypeFilter &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + + if (GetNumberOfExpressionPaths() != rhs.GetNumberOfExpressionPaths()) + return false; + + for (uint32_t j = 0; j < GetNumberOfExpressionPaths(); j++) + if (strcmp(GetExpressionPathAtIndex(j), rhs.GetExpressionPathAtIndex(j)) != + 0) + return false; + + return GetOptions() == rhs.GetOptions(); +} + +bool SBTypeFilter::operator!=(lldb::SBTypeFilter &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + + return m_opaque_sp != rhs.m_opaque_sp; +} + +lldb::TypeFilterImplSP SBTypeFilter::GetSP() { return m_opaque_sp; } + +void SBTypeFilter::SetSP(const lldb::TypeFilterImplSP &typefilter_impl_sp) { + m_opaque_sp = typefilter_impl_sp; +} + +SBTypeFilter::SBTypeFilter(const lldb::TypeFilterImplSP &typefilter_impl_sp) + : m_opaque_sp(typefilter_impl_sp) {} + +bool SBTypeFilter::CopyOnWrite_Impl() { + if (!IsValid()) + return false; + if (m_opaque_sp.use_count() == 1) + return true; + + TypeFilterImplSP new_sp(new TypeFilterImpl(GetOptions())); + + for (uint32_t j = 0; j < GetNumberOfExpressionPaths(); j++) + new_sp->AddExpressionPath(GetExpressionPathAtIndex(j)); + + SetSP(new_sp); + + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBTypeFormat.cpp b/contrib/llvm-project/lldb/source/API/SBTypeFormat.cpp new file mode 100644 index 000000000000..a0c37de2a73b --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBTypeFormat.cpp @@ -0,0 +1,183 @@ +//===-- SBTypeFormat.cpp --------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBTypeFormat.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBStream.h" + +#include "lldb/DataFormatters/DataVisualization.h" + +using namespace lldb; +using namespace lldb_private; + +SBTypeFormat::SBTypeFormat() { LLDB_INSTRUMENT_VA(this); } + +SBTypeFormat::SBTypeFormat(lldb::Format format, uint32_t options) + : m_opaque_sp( + TypeFormatImplSP(new TypeFormatImpl_Format(format, options))) { + LLDB_INSTRUMENT_VA(this, format, options); +} + +SBTypeFormat::SBTypeFormat(const char *type, uint32_t options) + : m_opaque_sp(TypeFormatImplSP(new TypeFormatImpl_EnumType( + ConstString(type ? type : ""), options))) { + LLDB_INSTRUMENT_VA(this, type, options); +} + +SBTypeFormat::SBTypeFormat(const lldb::SBTypeFormat &rhs) + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBTypeFormat::~SBTypeFormat() = default; + +bool SBTypeFormat::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTypeFormat::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} + +lldb::Format SBTypeFormat::GetFormat() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid() && m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeFormat) + return ((TypeFormatImpl_Format *)m_opaque_sp.get())->GetFormat(); + return lldb::eFormatInvalid; +} + +const char *SBTypeFormat::GetTypeName() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid() && m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeEnum) + return ((TypeFormatImpl_EnumType *)m_opaque_sp.get()) + ->GetTypeName() + .AsCString(""); + return ""; +} + +uint32_t SBTypeFormat::GetOptions() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return m_opaque_sp->GetOptions(); + return 0; +} + +void SBTypeFormat::SetFormat(lldb::Format fmt) { + LLDB_INSTRUMENT_VA(this, fmt); + + if (CopyOnWrite_Impl(Type::eTypeFormat)) + ((TypeFormatImpl_Format *)m_opaque_sp.get())->SetFormat(fmt); +} + +void SBTypeFormat::SetTypeName(const char *type) { + LLDB_INSTRUMENT_VA(this, type); + + if (CopyOnWrite_Impl(Type::eTypeEnum)) + ((TypeFormatImpl_EnumType *)m_opaque_sp.get()) + ->SetTypeName(ConstString(type ? type : "")); +} + +void SBTypeFormat::SetOptions(uint32_t value) { + LLDB_INSTRUMENT_VA(this, value); + + if (CopyOnWrite_Impl(Type::eTypeKeepSame)) + m_opaque_sp->SetOptions(value); +} + +bool SBTypeFormat::GetDescription(lldb::SBStream &description, + lldb::DescriptionLevel description_level) { + LLDB_INSTRUMENT_VA(this, description, description_level); + + if (!IsValid()) + return false; + else { + description.Printf("%s\n", m_opaque_sp->GetDescription().c_str()); + return true; + } +} + +lldb::SBTypeFormat &SBTypeFormat::operator=(const lldb::SBTypeFormat &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; +} + +bool SBTypeFormat::operator==(lldb::SBTypeFormat &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + return m_opaque_sp == rhs.m_opaque_sp; +} + +bool SBTypeFormat::IsEqualTo(lldb::SBTypeFormat &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + + if (GetFormat() == rhs.GetFormat()) + return GetOptions() == rhs.GetOptions(); + else + return false; +} + +bool SBTypeFormat::operator!=(lldb::SBTypeFormat &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + return m_opaque_sp != rhs.m_opaque_sp; +} + +lldb::TypeFormatImplSP SBTypeFormat::GetSP() { return m_opaque_sp; } + +void SBTypeFormat::SetSP(const lldb::TypeFormatImplSP &typeformat_impl_sp) { + m_opaque_sp = typeformat_impl_sp; +} + +SBTypeFormat::SBTypeFormat(const lldb::TypeFormatImplSP &typeformat_impl_sp) + : m_opaque_sp(typeformat_impl_sp) {} + +bool SBTypeFormat::CopyOnWrite_Impl(Type type) { + if (!IsValid()) + return false; + + if (m_opaque_sp.use_count() == 1 && + ((type == Type::eTypeKeepSame) || + (type == Type::eTypeFormat && + m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeFormat) || + (type == Type::eTypeEnum && + m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeEnum))) + return true; + + if (type == Type::eTypeKeepSame) { + if (m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeFormat) + type = Type::eTypeFormat; + else + type = Type::eTypeEnum; + } + + if (type == Type::eTypeFormat) + SetSP( + TypeFormatImplSP(new TypeFormatImpl_Format(GetFormat(), GetOptions()))); + else + SetSP(TypeFormatImplSP( + new TypeFormatImpl_EnumType(ConstString(GetTypeName()), GetOptions()))); + + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBTypeNameSpecifier.cpp b/contrib/llvm-project/lldb/source/API/SBTypeNameSpecifier.cpp new file mode 100644 index 000000000000..308b1cd6b2be --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBTypeNameSpecifier.cpp @@ -0,0 +1,164 @@ +//===-- SBTypeNameSpecifier.cpp -------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBTypeNameSpecifier.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBStream.h" +#include "lldb/API/SBType.h" + +#include "lldb/DataFormatters/DataVisualization.h" + +using namespace lldb; +using namespace lldb_private; + +SBTypeNameSpecifier::SBTypeNameSpecifier() { LLDB_INSTRUMENT_VA(this); } + +SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name, bool is_regex) + : SBTypeNameSpecifier(name, is_regex ? eFormatterMatchRegex + : eFormatterMatchExact) { + LLDB_INSTRUMENT_VA(this, name, is_regex); +} + +SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name, + FormatterMatchType match_type) + : m_opaque_sp(new TypeNameSpecifierImpl(name, match_type)) { + LLDB_INSTRUMENT_VA(this, name, match_type); + + if (name == nullptr || (*name) == 0) + m_opaque_sp.reset(); +} + +SBTypeNameSpecifier::SBTypeNameSpecifier(SBType type) { + LLDB_INSTRUMENT_VA(this, type); + + if (type.IsValid()) + m_opaque_sp = TypeNameSpecifierImplSP( + new TypeNameSpecifierImpl(type.m_opaque_sp->GetCompilerType(true))); +} + +SBTypeNameSpecifier::SBTypeNameSpecifier(const lldb::SBTypeNameSpecifier &rhs) + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBTypeNameSpecifier::~SBTypeNameSpecifier() = default; + +bool SBTypeNameSpecifier::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTypeNameSpecifier::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} + +const char *SBTypeNameSpecifier::GetName() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return nullptr; + + return ConstString(m_opaque_sp->GetName()).GetCString(); +} + +SBType SBTypeNameSpecifier::GetType() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return SBType(); + lldb_private::CompilerType c_type = m_opaque_sp->GetCompilerType(); + if (c_type.IsValid()) + return SBType(c_type); + return SBType(); +} + +FormatterMatchType SBTypeNameSpecifier::GetMatchType() { + LLDB_INSTRUMENT_VA(this); + if (!IsValid()) + return eFormatterMatchExact; + return m_opaque_sp->GetMatchType(); +} + +bool SBTypeNameSpecifier::IsRegex() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + + return m_opaque_sp->GetMatchType() == eFormatterMatchRegex; +} + +bool SBTypeNameSpecifier::GetDescription( + lldb::SBStream &description, lldb::DescriptionLevel description_level) { + LLDB_INSTRUMENT_VA(this, description, description_level); + + lldb::FormatterMatchType match_type = GetMatchType(); + const char *match_type_str = + (match_type == eFormatterMatchExact ? "plain" + : match_type == eFormatterMatchRegex ? "regex" + : "callback"); + if (!IsValid()) + return false; + description.Printf("SBTypeNameSpecifier(%s,%s)", GetName(), match_type_str); + return true; +} + +lldb::SBTypeNameSpecifier &SBTypeNameSpecifier:: +operator=(const lldb::SBTypeNameSpecifier &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; +} + +bool SBTypeNameSpecifier::operator==(lldb::SBTypeNameSpecifier &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + return m_opaque_sp == rhs.m_opaque_sp; +} + +bool SBTypeNameSpecifier::IsEqualTo(lldb::SBTypeNameSpecifier &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + + if (GetMatchType() != rhs.GetMatchType()) + return false; + if (GetName() == nullptr || rhs.GetName() == nullptr) + return false; + + return (strcmp(GetName(), rhs.GetName()) == 0); +} + +bool SBTypeNameSpecifier::operator!=(lldb::SBTypeNameSpecifier &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + return m_opaque_sp != rhs.m_opaque_sp; +} + +lldb::TypeNameSpecifierImplSP SBTypeNameSpecifier::GetSP() { + return m_opaque_sp; +} + +void SBTypeNameSpecifier::SetSP( + const lldb::TypeNameSpecifierImplSP &type_namespec_sp) { + m_opaque_sp = type_namespec_sp; +} + +SBTypeNameSpecifier::SBTypeNameSpecifier( + const lldb::TypeNameSpecifierImplSP &type_namespec_sp) + : m_opaque_sp(type_namespec_sp) {} diff --git a/contrib/llvm-project/lldb/source/API/SBTypeSummary.cpp b/contrib/llvm-project/lldb/source/API/SBTypeSummary.cpp new file mode 100644 index 000000000000..a5e87188c9f6 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBTypeSummary.cpp @@ -0,0 +1,436 @@ +//===-- SBTypeSummary.cpp -------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBTypeSummary.h" +#include "Utils.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBValue.h" +#include "lldb/DataFormatters/DataVisualization.h" +#include "lldb/Utility/Instrumentation.h" + +#include "llvm/Support/Casting.h" + +using namespace lldb; +using namespace lldb_private; + +SBTypeSummaryOptions::SBTypeSummaryOptions() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_up = std::make_unique<TypeSummaryOptions>(); +} + +SBTypeSummaryOptions::SBTypeSummaryOptions( + const lldb::SBTypeSummaryOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +SBTypeSummaryOptions::~SBTypeSummaryOptions() = default; + +bool SBTypeSummaryOptions::IsValid() { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTypeSummaryOptions::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up.get(); +} + +lldb::LanguageType SBTypeSummaryOptions::GetLanguage() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return m_opaque_up->GetLanguage(); + return lldb::eLanguageTypeUnknown; +} + +lldb::TypeSummaryCapping SBTypeSummaryOptions::GetCapping() { + LLDB_INSTRUMENT_VA(this); + + if (IsValid()) + return m_opaque_up->GetCapping(); + return eTypeSummaryCapped; +} + +void SBTypeSummaryOptions::SetLanguage(lldb::LanguageType l) { + LLDB_INSTRUMENT_VA(this, l); + + if (IsValid()) + m_opaque_up->SetLanguage(l); +} + +void SBTypeSummaryOptions::SetCapping(lldb::TypeSummaryCapping c) { + LLDB_INSTRUMENT_VA(this, c); + + if (IsValid()) + m_opaque_up->SetCapping(c); +} + +lldb_private::TypeSummaryOptions *SBTypeSummaryOptions::operator->() { + return m_opaque_up.get(); +} + +const lldb_private::TypeSummaryOptions *SBTypeSummaryOptions:: +operator->() const { + return m_opaque_up.get(); +} + +lldb_private::TypeSummaryOptions *SBTypeSummaryOptions::get() { + return m_opaque_up.get(); +} + +lldb_private::TypeSummaryOptions &SBTypeSummaryOptions::ref() { + return *m_opaque_up; +} + +const lldb_private::TypeSummaryOptions &SBTypeSummaryOptions::ref() const { + return *m_opaque_up; +} + +SBTypeSummaryOptions::SBTypeSummaryOptions( + const lldb_private::TypeSummaryOptions &lldb_object) + : m_opaque_up(std::make_unique<TypeSummaryOptions>(lldb_object)) { + LLDB_INSTRUMENT_VA(this, lldb_object); +} + +SBTypeSummary::SBTypeSummary() { LLDB_INSTRUMENT_VA(this); } + +SBTypeSummary SBTypeSummary::CreateWithSummaryString(const char *data, + uint32_t options) { + LLDB_INSTRUMENT_VA(data, options); + + if (!data || data[0] == 0) + return SBTypeSummary(); + + return SBTypeSummary( + TypeSummaryImplSP(new StringSummaryFormat(options, data))); +} + +SBTypeSummary SBTypeSummary::CreateWithFunctionName(const char *data, + uint32_t options) { + LLDB_INSTRUMENT_VA(data, options); + + if (!data || data[0] == 0) + return SBTypeSummary(); + + return SBTypeSummary( + TypeSummaryImplSP(new ScriptSummaryFormat(options, data))); +} + +SBTypeSummary SBTypeSummary::CreateWithScriptCode(const char *data, + uint32_t options) { + LLDB_INSTRUMENT_VA(data, options); + + if (!data || data[0] == 0) + return SBTypeSummary(); + + return SBTypeSummary( + TypeSummaryImplSP(new ScriptSummaryFormat(options, "", data))); +} + +SBTypeSummary SBTypeSummary::CreateWithCallback(FormatCallback cb, + uint32_t options, + const char *description) { + LLDB_INSTRUMENT_VA(cb, options, description); + + SBTypeSummary retval; + if (cb) { + retval.SetSP(TypeSummaryImplSP(new CXXFunctionSummaryFormat( + options, + [cb](ValueObject &valobj, Stream &stm, + const TypeSummaryOptions &opt) -> bool { + SBStream stream; + SBValue sb_value(valobj.GetSP()); + SBTypeSummaryOptions options(opt); + if (!cb(sb_value, options, stream)) + return false; + stm.Write(stream.GetData(), stream.GetSize()); + return true; + }, + description ? description : "callback summary formatter"))); + } + + return retval; +} + +SBTypeSummary::SBTypeSummary(const lldb::SBTypeSummary &rhs) + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBTypeSummary::~SBTypeSummary() = default; + +bool SBTypeSummary::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTypeSummary::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} + +bool SBTypeSummary::IsFunctionCode() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + if (ScriptSummaryFormat *script_summary_ptr = + llvm::dyn_cast<ScriptSummaryFormat>(m_opaque_sp.get())) { + const char *ftext = script_summary_ptr->GetPythonScript(); + return (ftext && *ftext != 0); + } + return false; +} + +bool SBTypeSummary::IsFunctionName() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + if (ScriptSummaryFormat *script_summary_ptr = + llvm::dyn_cast<ScriptSummaryFormat>(m_opaque_sp.get())) { + const char *ftext = script_summary_ptr->GetPythonScript(); + return (!ftext || *ftext == 0); + } + return false; +} + +bool SBTypeSummary::IsSummaryString() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + + return m_opaque_sp->GetKind() == TypeSummaryImpl::Kind::eSummaryString; +} + +const char *SBTypeSummary::GetData() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return nullptr; + if (ScriptSummaryFormat *script_summary_ptr = + llvm::dyn_cast<ScriptSummaryFormat>(m_opaque_sp.get())) { + const char *fname = script_summary_ptr->GetFunctionName(); + const char *ftext = script_summary_ptr->GetPythonScript(); + if (ftext && *ftext) + return ConstString(ftext).GetCString(); + return ConstString(fname).GetCString(); + } else if (StringSummaryFormat *string_summary_ptr = + llvm::dyn_cast<StringSummaryFormat>(m_opaque_sp.get())) + return ConstString(string_summary_ptr->GetSummaryString()).GetCString(); + return nullptr; +} + +uint32_t SBTypeSummary::GetOptions() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return lldb::eTypeOptionNone; + return m_opaque_sp->GetOptions(); +} + +void SBTypeSummary::SetOptions(uint32_t value) { + LLDB_INSTRUMENT_VA(this, value); + + if (!CopyOnWrite_Impl()) + return; + m_opaque_sp->SetOptions(value); +} + +void SBTypeSummary::SetSummaryString(const char *data) { + LLDB_INSTRUMENT_VA(this, data); + + if (!IsValid()) + return; + if (!llvm::isa<StringSummaryFormat>(m_opaque_sp.get())) + ChangeSummaryType(false); + if (StringSummaryFormat *string_summary_ptr = + llvm::dyn_cast<StringSummaryFormat>(m_opaque_sp.get())) + string_summary_ptr->SetSummaryString(data); +} + +void SBTypeSummary::SetFunctionName(const char *data) { + LLDB_INSTRUMENT_VA(this, data); + + if (!IsValid()) + return; + if (!llvm::isa<ScriptSummaryFormat>(m_opaque_sp.get())) + ChangeSummaryType(true); + if (ScriptSummaryFormat *script_summary_ptr = + llvm::dyn_cast<ScriptSummaryFormat>(m_opaque_sp.get())) + script_summary_ptr->SetFunctionName(data); +} + +void SBTypeSummary::SetFunctionCode(const char *data) { + LLDB_INSTRUMENT_VA(this, data); + + if (!IsValid()) + return; + if (!llvm::isa<ScriptSummaryFormat>(m_opaque_sp.get())) + ChangeSummaryType(true); + if (ScriptSummaryFormat *script_summary_ptr = + llvm::dyn_cast<ScriptSummaryFormat>(m_opaque_sp.get())) + script_summary_ptr->SetPythonScript(data); +} + +bool SBTypeSummary::GetDescription(lldb::SBStream &description, + lldb::DescriptionLevel description_level) { + LLDB_INSTRUMENT_VA(this, description, description_level); + + if (!CopyOnWrite_Impl()) + return false; + else { + description.Printf("%s\n", m_opaque_sp->GetDescription().c_str()); + return true; + } +} + +bool SBTypeSummary::DoesPrintValue(lldb::SBValue value) { + LLDB_INSTRUMENT_VA(this, value); + + if (!IsValid()) + return false; + lldb::ValueObjectSP value_sp = value.GetSP(); + return m_opaque_sp->DoesPrintValue(value_sp.get()); +} + +lldb::SBTypeSummary &SBTypeSummary::operator=(const lldb::SBTypeSummary &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; +} + +bool SBTypeSummary::operator==(lldb::SBTypeSummary &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + return m_opaque_sp == rhs.m_opaque_sp; +} + +bool SBTypeSummary::IsEqualTo(lldb::SBTypeSummary &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (IsValid()) { + // valid and invalid are different + if (!rhs.IsValid()) + return false; + } else { + // invalid and valid are different + if (rhs.IsValid()) + return false; + else + // both invalid are the same + return true; + } + + if (m_opaque_sp->GetKind() != rhs.m_opaque_sp->GetKind()) + return false; + + switch (m_opaque_sp->GetKind()) { + case TypeSummaryImpl::Kind::eCallback: + return llvm::dyn_cast<CXXFunctionSummaryFormat>(m_opaque_sp.get()) == + llvm::dyn_cast<CXXFunctionSummaryFormat>(rhs.m_opaque_sp.get()); + case TypeSummaryImpl::Kind::eScript: + if (IsFunctionCode() != rhs.IsFunctionCode()) + return false; + if (IsFunctionName() != rhs.IsFunctionName()) + return false; + return GetOptions() == rhs.GetOptions(); + case TypeSummaryImpl::Kind::eSummaryString: + if (IsSummaryString() != rhs.IsSummaryString()) + return false; + return GetOptions() == rhs.GetOptions(); + case TypeSummaryImpl::Kind::eInternal: + return (m_opaque_sp.get() == rhs.m_opaque_sp.get()); + } + + return false; +} + +bool SBTypeSummary::operator!=(lldb::SBTypeSummary &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + return m_opaque_sp != rhs.m_opaque_sp; +} + +lldb::TypeSummaryImplSP SBTypeSummary::GetSP() { return m_opaque_sp; } + +void SBTypeSummary::SetSP(const lldb::TypeSummaryImplSP &typesummary_impl_sp) { + m_opaque_sp = typesummary_impl_sp; +} + +SBTypeSummary::SBTypeSummary(const lldb::TypeSummaryImplSP &typesummary_impl_sp) + : m_opaque_sp(typesummary_impl_sp) {} + +bool SBTypeSummary::CopyOnWrite_Impl() { + if (!IsValid()) + return false; + + if (m_opaque_sp.use_count() == 1) + return true; + + TypeSummaryImplSP new_sp; + + if (CXXFunctionSummaryFormat *current_summary_ptr = + llvm::dyn_cast<CXXFunctionSummaryFormat>(m_opaque_sp.get())) { + new_sp = TypeSummaryImplSP(new CXXFunctionSummaryFormat( + GetOptions(), current_summary_ptr->m_impl, + current_summary_ptr->m_description.c_str())); + } else if (ScriptSummaryFormat *current_summary_ptr = + llvm::dyn_cast<ScriptSummaryFormat>(m_opaque_sp.get())) { + new_sp = TypeSummaryImplSP(new ScriptSummaryFormat( + GetOptions(), current_summary_ptr->GetFunctionName(), + current_summary_ptr->GetPythonScript())); + } else if (StringSummaryFormat *current_summary_ptr = + llvm::dyn_cast<StringSummaryFormat>(m_opaque_sp.get())) { + new_sp = TypeSummaryImplSP(new StringSummaryFormat( + GetOptions(), current_summary_ptr->GetSummaryString())); + } + + SetSP(new_sp); + + return nullptr != new_sp.get(); +} + +bool SBTypeSummary::ChangeSummaryType(bool want_script) { + if (!IsValid()) + return false; + + TypeSummaryImplSP new_sp; + + if (want_script == + (m_opaque_sp->GetKind() == TypeSummaryImpl::Kind::eScript)) { + if (m_opaque_sp->GetKind() == + lldb_private::TypeSummaryImpl::Kind::eCallback && + !want_script) + new_sp = TypeSummaryImplSP(new StringSummaryFormat(GetOptions(), "")); + else + return CopyOnWrite_Impl(); + } + + if (!new_sp) { + if (want_script) + new_sp = TypeSummaryImplSP(new ScriptSummaryFormat(GetOptions(), "", "")); + else + new_sp = TypeSummaryImplSP(new StringSummaryFormat(GetOptions(), "")); + } + + SetSP(new_sp); + + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBTypeSynthetic.cpp b/contrib/llvm-project/lldb/source/API/SBTypeSynthetic.cpp new file mode 100644 index 000000000000..19a4c53bad6a --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBTypeSynthetic.cpp @@ -0,0 +1,197 @@ +//===-- SBTypeSynthetic.cpp -----------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBTypeSynthetic.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBStream.h" + +#include "lldb/DataFormatters/DataVisualization.h" + +using namespace lldb; +using namespace lldb_private; + +SBTypeSynthetic::SBTypeSynthetic() { LLDB_INSTRUMENT_VA(this); } + +SBTypeSynthetic SBTypeSynthetic::CreateWithClassName(const char *data, + uint32_t options) { + LLDB_INSTRUMENT_VA(data, options); + + if (!data || data[0] == 0) + return SBTypeSynthetic(); + return SBTypeSynthetic(ScriptedSyntheticChildrenSP( + new ScriptedSyntheticChildren(options, data, ""))); +} + +SBTypeSynthetic SBTypeSynthetic::CreateWithScriptCode(const char *data, + uint32_t options) { + LLDB_INSTRUMENT_VA(data, options); + + if (!data || data[0] == 0) + return SBTypeSynthetic(); + return SBTypeSynthetic(ScriptedSyntheticChildrenSP( + new ScriptedSyntheticChildren(options, "", data))); +} + +SBTypeSynthetic::SBTypeSynthetic(const lldb::SBTypeSynthetic &rhs) + : m_opaque_sp(rhs.m_opaque_sp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBTypeSynthetic::~SBTypeSynthetic() = default; + +bool SBTypeSynthetic::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBTypeSynthetic::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_sp.get() != nullptr; +} + +bool SBTypeSynthetic::IsClassCode() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + const char *code = m_opaque_sp->GetPythonCode(); + return (code && *code); +} + +bool SBTypeSynthetic::IsClassName() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return !IsClassCode(); +} + +const char *SBTypeSynthetic::GetData() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return nullptr; + if (IsClassCode()) + return ConstString(m_opaque_sp->GetPythonCode()).GetCString(); + + return ConstString(m_opaque_sp->GetPythonClassName()).GetCString(); +} + +void SBTypeSynthetic::SetClassName(const char *data) { + LLDB_INSTRUMENT_VA(this, data); + + if (IsValid() && data && *data) + m_opaque_sp->SetPythonClassName(data); +} + +void SBTypeSynthetic::SetClassCode(const char *data) { + LLDB_INSTRUMENT_VA(this, data); + + if (IsValid() && data && *data) + m_opaque_sp->SetPythonCode(data); +} + +uint32_t SBTypeSynthetic::GetOptions() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return lldb::eTypeOptionNone; + return m_opaque_sp->GetOptions(); +} + +void SBTypeSynthetic::SetOptions(uint32_t value) { + LLDB_INSTRUMENT_VA(this, value); + + if (!CopyOnWrite_Impl()) + return; + m_opaque_sp->SetOptions(value); +} + +bool SBTypeSynthetic::GetDescription(lldb::SBStream &description, + lldb::DescriptionLevel description_level) { + LLDB_INSTRUMENT_VA(this, description, description_level); + + if (m_opaque_sp) { + description.Printf("%s\n", m_opaque_sp->GetDescription().c_str()); + return true; + } + return false; +} + +lldb::SBTypeSynthetic &SBTypeSynthetic:: +operator=(const lldb::SBTypeSynthetic &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; +} + +bool SBTypeSynthetic::operator==(lldb::SBTypeSynthetic &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + return m_opaque_sp == rhs.m_opaque_sp; +} + +bool SBTypeSynthetic::IsEqualTo(lldb::SBTypeSynthetic &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + + if (m_opaque_sp->IsScripted() != rhs.m_opaque_sp->IsScripted()) + return false; + + if (IsClassCode() != rhs.IsClassCode()) + return false; + + if (strcmp(GetData(), rhs.GetData())) + return false; + + return GetOptions() == rhs.GetOptions(); +} + +bool SBTypeSynthetic::operator!=(lldb::SBTypeSynthetic &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (!IsValid()) + return !rhs.IsValid(); + return m_opaque_sp != rhs.m_opaque_sp; +} + +lldb::ScriptedSyntheticChildrenSP SBTypeSynthetic::GetSP() { + return m_opaque_sp; +} + +void SBTypeSynthetic::SetSP( + const lldb::ScriptedSyntheticChildrenSP &TypeSynthetic_impl_sp) { + m_opaque_sp = TypeSynthetic_impl_sp; +} + +SBTypeSynthetic::SBTypeSynthetic( + const lldb::ScriptedSyntheticChildrenSP &TypeSynthetic_impl_sp) + : m_opaque_sp(TypeSynthetic_impl_sp) {} + +bool SBTypeSynthetic::CopyOnWrite_Impl() { + if (!IsValid()) + return false; + if (m_opaque_sp.use_count() == 1) + return true; + + ScriptedSyntheticChildrenSP new_sp(new ScriptedSyntheticChildren( + m_opaque_sp->GetOptions(), m_opaque_sp->GetPythonClassName(), + m_opaque_sp->GetPythonCode())); + + SetSP(new_sp); + + return true; +} diff --git a/contrib/llvm-project/lldb/source/API/SBUnixSignals.cpp b/contrib/llvm-project/lldb/source/API/SBUnixSignals.cpp new file mode 100644 index 000000000000..519881b186e4 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBUnixSignals.cpp @@ -0,0 +1,159 @@ +//===-- SBUnixSignals.cpp -------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/Target/Platform.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/UnixSignals.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/lldb-defines.h" + +#include "lldb/API/SBUnixSignals.h" + +using namespace lldb; +using namespace lldb_private; + +SBUnixSignals::SBUnixSignals() { LLDB_INSTRUMENT_VA(this); } + +SBUnixSignals::SBUnixSignals(const SBUnixSignals &rhs) + : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +SBUnixSignals::SBUnixSignals(ProcessSP &process_sp) + : m_opaque_wp(process_sp ? process_sp->GetUnixSignals() : nullptr) {} + +SBUnixSignals::SBUnixSignals(PlatformSP &platform_sp) + : m_opaque_wp(platform_sp ? platform_sp->GetUnixSignals() : nullptr) {} + +const SBUnixSignals &SBUnixSignals::operator=(const SBUnixSignals &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_wp = rhs.m_opaque_wp; + return *this; +} + +SBUnixSignals::~SBUnixSignals() = default; + +UnixSignalsSP SBUnixSignals::GetSP() const { return m_opaque_wp.lock(); } + +void SBUnixSignals::SetSP(const UnixSignalsSP &signals_sp) { + m_opaque_wp = signals_sp; +} + +void SBUnixSignals::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_wp.reset(); +} + +bool SBUnixSignals::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBUnixSignals::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return static_cast<bool>(GetSP()); +} + +const char *SBUnixSignals::GetSignalAsCString(int32_t signo) const { + LLDB_INSTRUMENT_VA(this, signo); + + if (auto signals_sp = GetSP()) + return ConstString(signals_sp->GetSignalAsStringRef(signo)).GetCString(); + + return nullptr; +} + +int32_t SBUnixSignals::GetSignalNumberFromName(const char *name) const { + LLDB_INSTRUMENT_VA(this, name); + + if (auto signals_sp = GetSP()) + return signals_sp->GetSignalNumberFromName(name); + + return LLDB_INVALID_SIGNAL_NUMBER; +} + +bool SBUnixSignals::GetShouldSuppress(int32_t signo) const { + LLDB_INSTRUMENT_VA(this, signo); + + if (auto signals_sp = GetSP()) + return signals_sp->GetShouldSuppress(signo); + + return false; +} + +bool SBUnixSignals::SetShouldSuppress(int32_t signo, bool value) { + LLDB_INSTRUMENT_VA(this, signo, value); + + auto signals_sp = GetSP(); + + if (signals_sp) + return signals_sp->SetShouldSuppress(signo, value); + + return false; +} + +bool SBUnixSignals::GetShouldStop(int32_t signo) const { + LLDB_INSTRUMENT_VA(this, signo); + + if (auto signals_sp = GetSP()) + return signals_sp->GetShouldStop(signo); + + return false; +} + +bool SBUnixSignals::SetShouldStop(int32_t signo, bool value) { + LLDB_INSTRUMENT_VA(this, signo, value); + + auto signals_sp = GetSP(); + + if (signals_sp) + return signals_sp->SetShouldStop(signo, value); + + return false; +} + +bool SBUnixSignals::GetShouldNotify(int32_t signo) const { + LLDB_INSTRUMENT_VA(this, signo); + + if (auto signals_sp = GetSP()) + return signals_sp->GetShouldNotify(signo); + + return false; +} + +bool SBUnixSignals::SetShouldNotify(int32_t signo, bool value) { + LLDB_INSTRUMENT_VA(this, signo, value); + + auto signals_sp = GetSP(); + + if (signals_sp) + return signals_sp->SetShouldNotify(signo, value); + + return false; +} + +int32_t SBUnixSignals::GetNumSignals() const { + LLDB_INSTRUMENT_VA(this); + + if (auto signals_sp = GetSP()) + return signals_sp->GetNumSignals(); + + return -1; +} + +int32_t SBUnixSignals::GetSignalAtIndex(int32_t index) const { + LLDB_INSTRUMENT_VA(this, index); + + if (auto signals_sp = GetSP()) + return signals_sp->GetSignalAtIndex(index); + + return LLDB_INVALID_SIGNAL_NUMBER; +} diff --git a/contrib/llvm-project/lldb/source/API/SBValue.cpp b/contrib/llvm-project/lldb/source/API/SBValue.cpp new file mode 100644 index 000000000000..96670481eca3 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBValue.cpp @@ -0,0 +1,1545 @@ +//===-- SBValue.cpp -------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBValue.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/API/SBDeclaration.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBTypeFilter.h" +#include "lldb/API/SBTypeFormat.h" +#include "lldb/API/SBTypeSummary.h" +#include "lldb/API/SBTypeSynthetic.h" + +#include "lldb/Breakpoint/Watchpoint.h" +#include "lldb/Core/Declaration.h" +#include "lldb/Core/Module.h" +#include "lldb/Core/Section.h" +#include "lldb/Core/Value.h" +#include "lldb/Core/ValueObject.h" +#include "lldb/Core/ValueObjectConstResult.h" +#include "lldb/DataFormatters/DataVisualization.h" +#include "lldb/DataFormatters/DumpValueObjectOptions.h" +#include "lldb/Symbol/Block.h" +#include "lldb/Symbol/ObjectFile.h" +#include "lldb/Symbol/Type.h" +#include "lldb/Symbol/Variable.h" +#include "lldb/Symbol/VariableList.h" +#include "lldb/Target/ExecutionContext.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/StackFrame.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" +#include "lldb/Utility/DataExtractor.h" +#include "lldb/Utility/Scalar.h" +#include "lldb/Utility/Stream.h" + +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBExpressionOptions.h" +#include "lldb/API/SBFrame.h" +#include "lldb/API/SBProcess.h" +#include "lldb/API/SBTarget.h" +#include "lldb/API/SBThread.h" + +#include <memory> + +using namespace lldb; +using namespace lldb_private; + +class ValueImpl { +public: + ValueImpl() = default; + + ValueImpl(lldb::ValueObjectSP in_valobj_sp, + lldb::DynamicValueType use_dynamic, bool use_synthetic, + const char *name = nullptr) + : m_use_dynamic(use_dynamic), m_use_synthetic(use_synthetic), + m_name(name) { + if (in_valobj_sp) { + if ((m_valobj_sp = in_valobj_sp->GetQualifiedRepresentationIfAvailable( + lldb::eNoDynamicValues, false))) { + if (!m_name.IsEmpty()) + m_valobj_sp->SetName(m_name); + } + } + } + + ValueImpl(const ValueImpl &rhs) = default; + + ValueImpl &operator=(const ValueImpl &rhs) { + if (this != &rhs) { + m_valobj_sp = rhs.m_valobj_sp; + m_use_dynamic = rhs.m_use_dynamic; + m_use_synthetic = rhs.m_use_synthetic; + m_name = rhs.m_name; + } + return *this; + } + + bool IsValid() { + if (m_valobj_sp.get() == nullptr) + return false; + else { + // FIXME: This check is necessary but not sufficient. We for sure don't + // want to touch SBValues whose owning + // targets have gone away. This check is a little weak in that it + // enforces that restriction when you call IsValid, but since IsValid + // doesn't lock the target, you have no guarantee that the SBValue won't + // go invalid after you call this... Also, an SBValue could depend on + // data from one of the modules in the target, and those could go away + // independently of the target, for instance if a module is unloaded. + // But right now, neither SBValues nor ValueObjects know which modules + // they depend on. So I have no good way to make that check without + // tracking that in all the ValueObject subclasses. + TargetSP target_sp = m_valobj_sp->GetTargetSP(); + return target_sp && target_sp->IsValid(); + } + } + + lldb::ValueObjectSP GetRootSP() { return m_valobj_sp; } + + lldb::ValueObjectSP GetSP(Process::StopLocker &stop_locker, + std::unique_lock<std::recursive_mutex> &lock, + Status &error) { + if (!m_valobj_sp) { + error.SetErrorString("invalid value object"); + return m_valobj_sp; + } + + lldb::ValueObjectSP value_sp = m_valobj_sp; + + Target *target = value_sp->GetTargetSP().get(); + // If this ValueObject holds an error, then it is valuable for that. + if (value_sp->GetError().Fail()) + return value_sp; + + if (!target) + return ValueObjectSP(); + + lock = std::unique_lock<std::recursive_mutex>(target->GetAPIMutex()); + + ProcessSP process_sp(value_sp->GetProcessSP()); + if (process_sp && !stop_locker.TryLock(&process_sp->GetRunLock())) { + // We don't allow people to play around with ValueObject if the process + // is running. If you want to look at values, pause the process, then + // look. + error.SetErrorString("process must be stopped."); + return ValueObjectSP(); + } + + if (m_use_dynamic != eNoDynamicValues) { + ValueObjectSP dynamic_sp = value_sp->GetDynamicValue(m_use_dynamic); + if (dynamic_sp) + value_sp = dynamic_sp; + } + + if (m_use_synthetic) { + ValueObjectSP synthetic_sp = value_sp->GetSyntheticValue(); + if (synthetic_sp) + value_sp = synthetic_sp; + } + + if (!value_sp) + error.SetErrorString("invalid value object"); + if (!m_name.IsEmpty()) + value_sp->SetName(m_name); + + return value_sp; + } + + void SetUseDynamic(lldb::DynamicValueType use_dynamic) { + m_use_dynamic = use_dynamic; + } + + void SetUseSynthetic(bool use_synthetic) { m_use_synthetic = use_synthetic; } + + lldb::DynamicValueType GetUseDynamic() { return m_use_dynamic; } + + bool GetUseSynthetic() { return m_use_synthetic; } + + // All the derived values that we would make from the m_valobj_sp will share + // the ExecutionContext with m_valobj_sp, so we don't need to do the + // calculations in GetSP to return the Target, Process, Thread or Frame. It + // is convenient to provide simple accessors for these, which I do here. + TargetSP GetTargetSP() { + if (m_valobj_sp) + return m_valobj_sp->GetTargetSP(); + else + return TargetSP(); + } + + ProcessSP GetProcessSP() { + if (m_valobj_sp) + return m_valobj_sp->GetProcessSP(); + else + return ProcessSP(); + } + + ThreadSP GetThreadSP() { + if (m_valobj_sp) + return m_valobj_sp->GetThreadSP(); + else + return ThreadSP(); + } + + StackFrameSP GetFrameSP() { + if (m_valobj_sp) + return m_valobj_sp->GetFrameSP(); + else + return StackFrameSP(); + } + +private: + lldb::ValueObjectSP m_valobj_sp; + lldb::DynamicValueType m_use_dynamic; + bool m_use_synthetic; + ConstString m_name; +}; + +class ValueLocker { +public: + ValueLocker() = default; + + ValueObjectSP GetLockedSP(ValueImpl &in_value) { + return in_value.GetSP(m_stop_locker, m_lock, m_lock_error); + } + + Status &GetError() { return m_lock_error; } + +private: + Process::StopLocker m_stop_locker; + std::unique_lock<std::recursive_mutex> m_lock; + Status m_lock_error; +}; + +SBValue::SBValue() { LLDB_INSTRUMENT_VA(this); } + +SBValue::SBValue(const lldb::ValueObjectSP &value_sp) { + LLDB_INSTRUMENT_VA(this, value_sp); + + SetSP(value_sp); +} + +SBValue::SBValue(const SBValue &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + SetSP(rhs.m_opaque_sp); +} + +SBValue &SBValue::operator=(const SBValue &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + SetSP(rhs.m_opaque_sp); + } + return *this; +} + +SBValue::~SBValue() = default; + +bool SBValue::IsValid() { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBValue::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + // If this function ever changes to anything that does more than just check + // if the opaque shared pointer is non NULL, then we need to update all "if + // (m_opaque_sp)" code in this file. + return m_opaque_sp.get() != nullptr && m_opaque_sp->IsValid() && + m_opaque_sp->GetRootSP().get() != nullptr; +} + +void SBValue::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_sp.reset(); +} + +SBError SBValue::GetError() { + LLDB_INSTRUMENT_VA(this); + + SBError sb_error; + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + sb_error.SetError(value_sp->GetError()); + else + sb_error.SetErrorStringWithFormat("error: %s", + locker.GetError().AsCString()); + + return sb_error; +} + +user_id_t SBValue::GetID() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->GetID(); + return LLDB_INVALID_UID; +} + +const char *SBValue::GetName() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (!value_sp) + return nullptr; + + return value_sp->GetName().GetCString(); +} + +const char *SBValue::GetTypeName() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (!value_sp) + return nullptr; + + return value_sp->GetQualifiedTypeName().GetCString(); +} + +const char *SBValue::GetDisplayTypeName() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (!value_sp) + return nullptr; + + return value_sp->GetDisplayTypeName().GetCString(); +} + +size_t SBValue::GetByteSize() { + LLDB_INSTRUMENT_VA(this); + + size_t result = 0; + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + result = value_sp->GetByteSize().value_or(0); + } + + return result; +} + +bool SBValue::IsInScope() { + LLDB_INSTRUMENT_VA(this); + + bool result = false; + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + result = value_sp->IsInScope(); + } + + return result; +} + +const char *SBValue::GetValue() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (!value_sp) + return nullptr; + return ConstString(value_sp->GetValueAsCString()).GetCString(); +} + +ValueType SBValue::GetValueType() { + LLDB_INSTRUMENT_VA(this); + + ValueType result = eValueTypeInvalid; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + result = value_sp->GetValueType(); + + return result; +} + +const char *SBValue::GetObjectDescription() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (!value_sp) + return nullptr; + + llvm::Expected<std::string> str = value_sp->GetObjectDescription(); + if (!str) + return ConstString("error: " + toString(str.takeError())).AsCString(); + return ConstString(*str).AsCString(); +} + +SBType SBValue::GetType() { + LLDB_INSTRUMENT_VA(this); + + SBType sb_type; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + TypeImplSP type_sp; + if (value_sp) { + type_sp = std::make_shared<TypeImpl>(value_sp->GetTypeImpl()); + sb_type.SetSP(type_sp); + } + + return sb_type; +} + +bool SBValue::GetValueDidChange() { + LLDB_INSTRUMENT_VA(this); + + bool result = false; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + if (value_sp->UpdateValueIfNeeded(false)) + result = value_sp->GetValueDidChange(); + } + + return result; +} + +const char *SBValue::GetSummary() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (!value_sp) + return nullptr; + + return ConstString(value_sp->GetSummaryAsCString()).GetCString(); +} + +const char *SBValue::GetSummary(lldb::SBStream &stream, + lldb::SBTypeSummaryOptions &options) { + LLDB_INSTRUMENT_VA(this, stream, options); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + std::string buffer; + if (value_sp->GetSummaryAsCString(buffer, options.ref()) && !buffer.empty()) + stream.Printf("%s", buffer.c_str()); + } + return ConstString(stream.GetData()).GetCString(); +} + +const char *SBValue::GetLocation() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (!value_sp) + return nullptr; + + return ConstString(value_sp->GetLocationAsCString()).GetCString(); +} + +// Deprecated - use the one that takes an lldb::SBError +bool SBValue::SetValueFromCString(const char *value_str) { + LLDB_INSTRUMENT_VA(this, value_str); + + lldb::SBError dummy; + return SetValueFromCString(value_str, dummy); +} + +bool SBValue::SetValueFromCString(const char *value_str, lldb::SBError &error) { + LLDB_INSTRUMENT_VA(this, value_str, error); + + bool success = false; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + success = value_sp->SetValueFromCString(value_str, error.ref()); + } else + error.SetErrorStringWithFormat("Could not get value: %s", + locker.GetError().AsCString()); + + return success; +} + +lldb::SBTypeFormat SBValue::GetTypeFormat() { + LLDB_INSTRUMENT_VA(this); + + lldb::SBTypeFormat format; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + if (value_sp->UpdateValueIfNeeded(true)) { + lldb::TypeFormatImplSP format_sp = value_sp->GetValueFormat(); + if (format_sp) + format.SetSP(format_sp); + } + } + return format; +} + +lldb::SBTypeSummary SBValue::GetTypeSummary() { + LLDB_INSTRUMENT_VA(this); + + lldb::SBTypeSummary summary; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + if (value_sp->UpdateValueIfNeeded(true)) { + lldb::TypeSummaryImplSP summary_sp = value_sp->GetSummaryFormat(); + if (summary_sp) + summary.SetSP(summary_sp); + } + } + return summary; +} + +lldb::SBTypeFilter SBValue::GetTypeFilter() { + LLDB_INSTRUMENT_VA(this); + + lldb::SBTypeFilter filter; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + if (value_sp->UpdateValueIfNeeded(true)) { + lldb::SyntheticChildrenSP synthetic_sp = value_sp->GetSyntheticChildren(); + + if (synthetic_sp && !synthetic_sp->IsScripted()) { + TypeFilterImplSP filter_sp = + std::static_pointer_cast<TypeFilterImpl>(synthetic_sp); + filter.SetSP(filter_sp); + } + } + } + return filter; +} + +lldb::SBTypeSynthetic SBValue::GetTypeSynthetic() { + LLDB_INSTRUMENT_VA(this); + + lldb::SBTypeSynthetic synthetic; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + if (value_sp->UpdateValueIfNeeded(true)) { + lldb::SyntheticChildrenSP children_sp = value_sp->GetSyntheticChildren(); + + if (children_sp && children_sp->IsScripted()) { + ScriptedSyntheticChildrenSP synth_sp = + std::static_pointer_cast<ScriptedSyntheticChildren>(children_sp); + synthetic.SetSP(synth_sp); + } + } + } + return synthetic; +} + +lldb::SBValue SBValue::CreateChildAtOffset(const char *name, uint32_t offset, + SBType type) { + LLDB_INSTRUMENT_VA(this, name, offset, type); + + lldb::SBValue sb_value; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + lldb::ValueObjectSP new_value_sp; + if (value_sp) { + TypeImplSP type_sp(type.GetSP()); + if (type.IsValid()) { + sb_value.SetSP(value_sp->GetSyntheticChildAtOffset( + offset, type_sp->GetCompilerType(false), true), + GetPreferDynamicValue(), GetPreferSyntheticValue(), name); + } + } + return sb_value; +} + +lldb::SBValue SBValue::Cast(SBType type) { + LLDB_INSTRUMENT_VA(this, type); + + lldb::SBValue sb_value; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + TypeImplSP type_sp(type.GetSP()); + if (value_sp && type_sp) + sb_value.SetSP(value_sp->Cast(type_sp->GetCompilerType(false)), + GetPreferDynamicValue(), GetPreferSyntheticValue()); + return sb_value; +} + +lldb::SBValue SBValue::CreateValueFromExpression(const char *name, + const char *expression) { + LLDB_INSTRUMENT_VA(this, name, expression); + + SBExpressionOptions options; + options.ref().SetKeepInMemory(true); + return CreateValueFromExpression(name, expression, options); +} + +lldb::SBValue SBValue::CreateValueFromExpression(const char *name, + const char *expression, + SBExpressionOptions &options) { + LLDB_INSTRUMENT_VA(this, name, expression, options); + + lldb::SBValue sb_value; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + lldb::ValueObjectSP new_value_sp; + if (value_sp) { + ExecutionContext exe_ctx(value_sp->GetExecutionContextRef()); + new_value_sp = ValueObject::CreateValueObjectFromExpression( + name, expression, exe_ctx, options.ref()); + if (new_value_sp) + new_value_sp->SetName(ConstString(name)); + } + sb_value.SetSP(new_value_sp); + return sb_value; +} + +lldb::SBValue SBValue::CreateValueFromAddress(const char *name, + lldb::addr_t address, + SBType sb_type) { + LLDB_INSTRUMENT_VA(this, name, address, sb_type); + + lldb::SBValue sb_value; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + lldb::ValueObjectSP new_value_sp; + lldb::TypeImplSP type_impl_sp(sb_type.GetSP()); + if (value_sp && type_impl_sp) { + CompilerType ast_type(type_impl_sp->GetCompilerType(true)); + ExecutionContext exe_ctx(value_sp->GetExecutionContextRef()); + new_value_sp = ValueObject::CreateValueObjectFromAddress(name, address, + exe_ctx, ast_type); + } + sb_value.SetSP(new_value_sp); + return sb_value; +} + +lldb::SBValue SBValue::CreateValueFromData(const char *name, SBData data, + SBType sb_type) { + LLDB_INSTRUMENT_VA(this, name, data, sb_type); + + lldb::SBValue sb_value; + lldb::ValueObjectSP new_value_sp; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + lldb::TypeImplSP type_impl_sp(sb_type.GetSP()); + if (value_sp && type_impl_sp) { + ExecutionContext exe_ctx(value_sp->GetExecutionContextRef()); + new_value_sp = ValueObject::CreateValueObjectFromData( + name, **data, exe_ctx, type_impl_sp->GetCompilerType(true)); + new_value_sp->SetAddressTypeOfChildren(eAddressTypeLoad); + } + sb_value.SetSP(new_value_sp); + return sb_value; +} + +SBValue SBValue::GetChildAtIndex(uint32_t idx) { + LLDB_INSTRUMENT_VA(this, idx); + + const bool can_create_synthetic = false; + lldb::DynamicValueType use_dynamic = eNoDynamicValues; + TargetSP target_sp; + if (m_opaque_sp) + target_sp = m_opaque_sp->GetTargetSP(); + + if (target_sp) + use_dynamic = target_sp->GetPreferDynamicValue(); + + return GetChildAtIndex(idx, use_dynamic, can_create_synthetic); +} + +SBValue SBValue::GetChildAtIndex(uint32_t idx, + lldb::DynamicValueType use_dynamic, + bool can_create_synthetic) { + LLDB_INSTRUMENT_VA(this, idx, use_dynamic, can_create_synthetic); + + lldb::ValueObjectSP child_sp; + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + const bool can_create = true; + child_sp = value_sp->GetChildAtIndex(idx); + if (can_create_synthetic && !child_sp) { + child_sp = value_sp->GetSyntheticArrayMember(idx, can_create); + } + } + + SBValue sb_value; + sb_value.SetSP(child_sp, use_dynamic, GetPreferSyntheticValue()); + + return sb_value; +} + +uint32_t SBValue::GetIndexOfChildWithName(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + + uint32_t idx = UINT32_MAX; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + idx = value_sp->GetIndexOfChildWithName(name); + } + return idx; +} + +SBValue SBValue::GetChildMemberWithName(const char *name) { + LLDB_INSTRUMENT_VA(this, name); + + lldb::DynamicValueType use_dynamic_value = eNoDynamicValues; + TargetSP target_sp; + if (m_opaque_sp) + target_sp = m_opaque_sp->GetTargetSP(); + + if (target_sp) + use_dynamic_value = target_sp->GetPreferDynamicValue(); + return GetChildMemberWithName(name, use_dynamic_value); +} + +SBValue +SBValue::GetChildMemberWithName(const char *name, + lldb::DynamicValueType use_dynamic_value) { + LLDB_INSTRUMENT_VA(this, name, use_dynamic_value); + + lldb::ValueObjectSP child_sp; + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + child_sp = value_sp->GetChildMemberWithName(name); + } + + SBValue sb_value; + sb_value.SetSP(child_sp, use_dynamic_value, GetPreferSyntheticValue()); + + return sb_value; +} + +lldb::SBValue SBValue::GetDynamicValue(lldb::DynamicValueType use_dynamic) { + LLDB_INSTRUMENT_VA(this, use_dynamic); + + SBValue value_sb; + if (IsValid()) { + ValueImplSP proxy_sp(new ValueImpl(m_opaque_sp->GetRootSP(), use_dynamic, + m_opaque_sp->GetUseSynthetic())); + value_sb.SetSP(proxy_sp); + } + return value_sb; +} + +lldb::SBValue SBValue::GetStaticValue() { + LLDB_INSTRUMENT_VA(this); + + SBValue value_sb; + if (IsValid()) { + ValueImplSP proxy_sp(new ValueImpl(m_opaque_sp->GetRootSP(), + eNoDynamicValues, + m_opaque_sp->GetUseSynthetic())); + value_sb.SetSP(proxy_sp); + } + return value_sb; +} + +lldb::SBValue SBValue::GetNonSyntheticValue() { + LLDB_INSTRUMENT_VA(this); + + SBValue value_sb; + if (IsValid()) { + ValueImplSP proxy_sp(new ValueImpl(m_opaque_sp->GetRootSP(), + m_opaque_sp->GetUseDynamic(), false)); + value_sb.SetSP(proxy_sp); + } + return value_sb; +} + +lldb::SBValue SBValue::GetSyntheticValue() { + LLDB_INSTRUMENT_VA(this); + + SBValue value_sb; + if (IsValid()) { + ValueImplSP proxy_sp(new ValueImpl(m_opaque_sp->GetRootSP(), + m_opaque_sp->GetUseDynamic(), true)); + value_sb.SetSP(proxy_sp); + if (!value_sb.IsSynthetic()) { + return {}; + } + } + return value_sb; +} + +lldb::DynamicValueType SBValue::GetPreferDynamicValue() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return eNoDynamicValues; + return m_opaque_sp->GetUseDynamic(); +} + +void SBValue::SetPreferDynamicValue(lldb::DynamicValueType use_dynamic) { + LLDB_INSTRUMENT_VA(this, use_dynamic); + + if (IsValid()) + return m_opaque_sp->SetUseDynamic(use_dynamic); +} + +bool SBValue::GetPreferSyntheticValue() { + LLDB_INSTRUMENT_VA(this); + + if (!IsValid()) + return false; + return m_opaque_sp->GetUseSynthetic(); +} + +void SBValue::SetPreferSyntheticValue(bool use_synthetic) { + LLDB_INSTRUMENT_VA(this, use_synthetic); + + if (IsValid()) + return m_opaque_sp->SetUseSynthetic(use_synthetic); +} + +bool SBValue::IsDynamic() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->IsDynamic(); + return false; +} + +bool SBValue::IsSynthetic() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->IsSynthetic(); + return false; +} + +bool SBValue::IsSyntheticChildrenGenerated() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->IsSyntheticChildrenGenerated(); + return false; +} + +void SBValue::SetSyntheticChildrenGenerated(bool is) { + LLDB_INSTRUMENT_VA(this, is); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->SetSyntheticChildrenGenerated(is); +} + +lldb::SBValue SBValue::GetValueForExpressionPath(const char *expr_path) { + LLDB_INSTRUMENT_VA(this, expr_path); + + lldb::ValueObjectSP child_sp; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + // using default values for all the fancy options, just do it if you can + child_sp = value_sp->GetValueForExpressionPath(expr_path); + } + + SBValue sb_value; + sb_value.SetSP(child_sp, GetPreferDynamicValue(), GetPreferSyntheticValue()); + + return sb_value; +} + +int64_t SBValue::GetValueAsSigned(SBError &error, int64_t fail_value) { + LLDB_INSTRUMENT_VA(this, error, fail_value); + + error.Clear(); + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + bool success = true; + uint64_t ret_val = fail_value; + ret_val = value_sp->GetValueAsSigned(fail_value, &success); + if (!success) + error.SetErrorString("could not resolve value"); + return ret_val; + } else + error.SetErrorStringWithFormat("could not get SBValue: %s", + locker.GetError().AsCString()); + + return fail_value; +} + +uint64_t SBValue::GetValueAsUnsigned(SBError &error, uint64_t fail_value) { + LLDB_INSTRUMENT_VA(this, error, fail_value); + + error.Clear(); + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + bool success = true; + uint64_t ret_val = fail_value; + ret_val = value_sp->GetValueAsUnsigned(fail_value, &success); + if (!success) + error.SetErrorString("could not resolve value"); + return ret_val; + } else + error.SetErrorStringWithFormat("could not get SBValue: %s", + locker.GetError().AsCString()); + + return fail_value; +} + +int64_t SBValue::GetValueAsSigned(int64_t fail_value) { + LLDB_INSTRUMENT_VA(this, fail_value); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + return value_sp->GetValueAsSigned(fail_value); + } + return fail_value; +} + +uint64_t SBValue::GetValueAsUnsigned(uint64_t fail_value) { + LLDB_INSTRUMENT_VA(this, fail_value); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + return value_sp->GetValueAsUnsigned(fail_value); + } + return fail_value; +} + +lldb::addr_t SBValue::GetValueAsAddress() { + addr_t fail_value = LLDB_INVALID_ADDRESS; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + bool success = true; + uint64_t ret_val = fail_value; + ret_val = value_sp->GetValueAsUnsigned(fail_value, &success); + if (!success) + return fail_value; + ProcessSP process_sp = m_opaque_sp->GetProcessSP(); + if (!process_sp) + return ret_val; + return process_sp->FixDataAddress(ret_val); + } + + return fail_value; +} + +bool SBValue::MightHaveChildren() { + LLDB_INSTRUMENT_VA(this); + + bool has_children = false; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + has_children = value_sp->MightHaveChildren(); + + return has_children; +} + +bool SBValue::IsRuntimeSupportValue() { + LLDB_INSTRUMENT_VA(this); + + bool is_support = false; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + is_support = value_sp->IsRuntimeSupportValue(); + + return is_support; +} + +uint32_t SBValue::GetNumChildren() { + LLDB_INSTRUMENT_VA(this); + + return GetNumChildren(UINT32_MAX); +} + +uint32_t SBValue::GetNumChildren(uint32_t max) { + LLDB_INSTRUMENT_VA(this, max); + + uint32_t num_children = 0; + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + num_children = value_sp->GetNumChildrenIgnoringErrors(max); + + return num_children; +} + +SBValue SBValue::Dereference() { + LLDB_INSTRUMENT_VA(this); + + SBValue sb_value; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + Status error; + sb_value = value_sp->Dereference(error); + } + + return sb_value; +} + +// Deprecated - please use GetType().IsPointerType() instead. +bool SBValue::TypeIsPointerType() { + LLDB_INSTRUMENT_VA(this); + + return GetType().IsPointerType(); +} + +void *SBValue::GetOpaqueType() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->GetCompilerType().GetOpaqueQualType(); + return nullptr; +} + +lldb::SBTarget SBValue::GetTarget() { + LLDB_INSTRUMENT_VA(this); + + SBTarget sb_target; + TargetSP target_sp; + if (m_opaque_sp) { + target_sp = m_opaque_sp->GetTargetSP(); + sb_target.SetSP(target_sp); + } + + return sb_target; +} + +lldb::SBProcess SBValue::GetProcess() { + LLDB_INSTRUMENT_VA(this); + + SBProcess sb_process; + ProcessSP process_sp; + if (m_opaque_sp) { + process_sp = m_opaque_sp->GetProcessSP(); + sb_process.SetSP(process_sp); + } + + return sb_process; +} + +lldb::SBThread SBValue::GetThread() { + LLDB_INSTRUMENT_VA(this); + + SBThread sb_thread; + ThreadSP thread_sp; + if (m_opaque_sp) { + thread_sp = m_opaque_sp->GetThreadSP(); + sb_thread.SetThread(thread_sp); + } + + return sb_thread; +} + +lldb::SBFrame SBValue::GetFrame() { + LLDB_INSTRUMENT_VA(this); + + SBFrame sb_frame; + StackFrameSP frame_sp; + if (m_opaque_sp) { + frame_sp = m_opaque_sp->GetFrameSP(); + sb_frame.SetFrameSP(frame_sp); + } + + return sb_frame; +} + +lldb::ValueObjectSP SBValue::GetSP(ValueLocker &locker) const { + // IsValid means that the SBValue has a value in it. But that's not the + // only time that ValueObjects are useful. We also want to return the value + // if there's an error state in it. + if (!m_opaque_sp || (!m_opaque_sp->IsValid() + && (m_opaque_sp->GetRootSP() + && !m_opaque_sp->GetRootSP()->GetError().Fail()))) { + locker.GetError().SetErrorString("No value"); + return ValueObjectSP(); + } + return locker.GetLockedSP(*m_opaque_sp.get()); +} + +lldb::ValueObjectSP SBValue::GetSP() const { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + return GetSP(locker); +} + +void SBValue::SetSP(ValueImplSP impl_sp) { m_opaque_sp = impl_sp; } + +void SBValue::SetSP(const lldb::ValueObjectSP &sp) { + if (sp) { + lldb::TargetSP target_sp(sp->GetTargetSP()); + if (target_sp) { + lldb::DynamicValueType use_dynamic = target_sp->GetPreferDynamicValue(); + bool use_synthetic = + target_sp->TargetProperties::GetEnableSyntheticValue(); + m_opaque_sp = ValueImplSP(new ValueImpl(sp, use_dynamic, use_synthetic)); + } else + m_opaque_sp = ValueImplSP(new ValueImpl(sp, eNoDynamicValues, true)); + } else + m_opaque_sp = ValueImplSP(new ValueImpl(sp, eNoDynamicValues, false)); +} + +void SBValue::SetSP(const lldb::ValueObjectSP &sp, + lldb::DynamicValueType use_dynamic) { + if (sp) { + lldb::TargetSP target_sp(sp->GetTargetSP()); + if (target_sp) { + bool use_synthetic = + target_sp->TargetProperties::GetEnableSyntheticValue(); + SetSP(sp, use_dynamic, use_synthetic); + } else + SetSP(sp, use_dynamic, true); + } else + SetSP(sp, use_dynamic, false); +} + +void SBValue::SetSP(const lldb::ValueObjectSP &sp, bool use_synthetic) { + if (sp) { + lldb::TargetSP target_sp(sp->GetTargetSP()); + if (target_sp) { + lldb::DynamicValueType use_dynamic = target_sp->GetPreferDynamicValue(); + SetSP(sp, use_dynamic, use_synthetic); + } else + SetSP(sp, eNoDynamicValues, use_synthetic); + } else + SetSP(sp, eNoDynamicValues, use_synthetic); +} + +void SBValue::SetSP(const lldb::ValueObjectSP &sp, + lldb::DynamicValueType use_dynamic, bool use_synthetic) { + m_opaque_sp = ValueImplSP(new ValueImpl(sp, use_dynamic, use_synthetic)); +} + +void SBValue::SetSP(const lldb::ValueObjectSP &sp, + lldb::DynamicValueType use_dynamic, bool use_synthetic, + const char *name) { + m_opaque_sp = + ValueImplSP(new ValueImpl(sp, use_dynamic, use_synthetic, name)); +} + +bool SBValue::GetExpressionPath(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + value_sp->GetExpressionPath(description.ref()); + return true; + } + return false; +} + +bool SBValue::GetExpressionPath(SBStream &description, + bool qualify_cxx_base_classes) { + LLDB_INSTRUMENT_VA(this, description, qualify_cxx_base_classes); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + value_sp->GetExpressionPath(description.ref()); + return true; + } + return false; +} + +lldb::SBValue SBValue::EvaluateExpression(const char *expr) const { + LLDB_INSTRUMENT_VA(this, expr); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (!value_sp) + return SBValue(); + + lldb::TargetSP target_sp = value_sp->GetTargetSP(); + if (!target_sp) + return SBValue(); + + lldb::SBExpressionOptions options; + options.SetFetchDynamicValue(target_sp->GetPreferDynamicValue()); + options.SetUnwindOnError(true); + options.SetIgnoreBreakpoints(true); + + return EvaluateExpression(expr, options, nullptr); +} + +lldb::SBValue +SBValue::EvaluateExpression(const char *expr, + const SBExpressionOptions &options) const { + LLDB_INSTRUMENT_VA(this, expr, options); + + return EvaluateExpression(expr, options, nullptr); +} + +lldb::SBValue SBValue::EvaluateExpression(const char *expr, + const SBExpressionOptions &options, + const char *name) const { + LLDB_INSTRUMENT_VA(this, expr, options, name); + + if (!expr || expr[0] == '\0') { + return SBValue(); + } + + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (!value_sp) { + return SBValue(); + } + + lldb::TargetSP target_sp = value_sp->GetTargetSP(); + if (!target_sp) { + return SBValue(); + } + + std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex()); + ExecutionContext exe_ctx(target_sp.get()); + + StackFrame *frame = exe_ctx.GetFramePtr(); + if (!frame) { + return SBValue(); + } + + ValueObjectSP res_val_sp; + target_sp->EvaluateExpression(expr, frame, res_val_sp, options.ref(), nullptr, + value_sp.get()); + + if (name) + res_val_sp->SetName(ConstString(name)); + + SBValue result; + result.SetSP(res_val_sp, options.GetFetchDynamicValue()); + return result; +} + +bool SBValue::GetDescription(SBStream &description) { + LLDB_INSTRUMENT_VA(this, description); + + Stream &strm = description.ref(); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + DumpValueObjectOptions options; + options.SetUseDynamicType(m_opaque_sp->GetUseDynamic()); + options.SetUseSyntheticValue(m_opaque_sp->GetUseSynthetic()); + if (llvm::Error error = value_sp->Dump(strm, options)) { + strm << "error: " << toString(std::move(error)); + return false; + } + } else { + strm.PutCString("No value"); + } + + return true; +} + +lldb::Format SBValue::GetFormat() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->GetFormat(); + return eFormatDefault; +} + +void SBValue::SetFormat(lldb::Format format) { + LLDB_INSTRUMENT_VA(this, format); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + value_sp->SetFormat(format); +} + +lldb::SBValue SBValue::AddressOf() { + LLDB_INSTRUMENT_VA(this); + + SBValue sb_value; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + Status error; + sb_value.SetSP(value_sp->AddressOf(error), GetPreferDynamicValue(), + GetPreferSyntheticValue()); + } + + return sb_value; +} + +lldb::addr_t SBValue::GetLoadAddress() { + LLDB_INSTRUMENT_VA(this); + + lldb::addr_t value = LLDB_INVALID_ADDRESS; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->GetLoadAddress(); + + return value; +} + +lldb::SBAddress SBValue::GetAddress() { + LLDB_INSTRUMENT_VA(this); + + Address addr; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + TargetSP target_sp(value_sp->GetTargetSP()); + if (target_sp) { + lldb::addr_t value = LLDB_INVALID_ADDRESS; + const bool scalar_is_load_address = true; + AddressType addr_type; + value = value_sp->GetAddressOf(scalar_is_load_address, &addr_type); + if (addr_type == eAddressTypeFile) { + ModuleSP module_sp(value_sp->GetModule()); + if (module_sp) + module_sp->ResolveFileAddress(value, addr); + } else if (addr_type == eAddressTypeLoad) { + // no need to check the return value on this.. if it can actually do + // the resolve addr will be in the form (section,offset), otherwise it + // will simply be returned as (NULL, value) + addr.SetLoadAddress(value, target_sp.get()); + } + } + } + + return SBAddress(addr); +} + +lldb::SBData SBValue::GetPointeeData(uint32_t item_idx, uint32_t item_count) { + LLDB_INSTRUMENT_VA(this, item_idx, item_count); + + lldb::SBData sb_data; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + TargetSP target_sp(value_sp->GetTargetSP()); + if (target_sp) { + DataExtractorSP data_sp(new DataExtractor()); + value_sp->GetPointeeData(*data_sp, item_idx, item_count); + if (data_sp->GetByteSize() > 0) + *sb_data = data_sp; + } + } + + return sb_data; +} + +lldb::SBData SBValue::GetData() { + LLDB_INSTRUMENT_VA(this); + + lldb::SBData sb_data; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + DataExtractorSP data_sp(new DataExtractor()); + Status error; + value_sp->GetData(*data_sp, error); + if (error.Success()) + *sb_data = data_sp; + } + + return sb_data; +} + +bool SBValue::SetData(lldb::SBData &data, SBError &error) { + LLDB_INSTRUMENT_VA(this, data, error); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + bool ret = true; + + if (value_sp) { + DataExtractor *data_extractor = data.get(); + + if (!data_extractor) { + error.SetErrorString("No data to set"); + ret = false; + } else { + Status set_error; + + value_sp->SetData(*data_extractor, set_error); + + if (!set_error.Success()) { + error.SetErrorStringWithFormat("Couldn't set data: %s", + set_error.AsCString()); + ret = false; + } + } + } else { + error.SetErrorStringWithFormat( + "Couldn't set data: could not get SBValue: %s", + locker.GetError().AsCString()); + ret = false; + } + + return ret; +} + +lldb::SBValue SBValue::Clone(const char *new_name) { + LLDB_INSTRUMENT_VA(this, new_name); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + + if (value_sp) + return lldb::SBValue(value_sp->Clone(ConstString(new_name))); + else + return lldb::SBValue(); +} + +lldb::SBDeclaration SBValue::GetDeclaration() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + SBDeclaration decl_sb; + if (value_sp) { + Declaration decl; + if (value_sp->GetDeclaration(decl)) + decl_sb.SetDeclaration(decl); + } + return decl_sb; +} + +lldb::SBWatchpoint SBValue::Watch(bool resolve_location, bool read, bool write, + SBError &error) { + LLDB_INSTRUMENT_VA(this, resolve_location, read, write, error); + + SBWatchpoint sb_watchpoint; + + // If the SBValue is not valid, there's no point in even trying to watch it. + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + TargetSP target_sp(GetTarget().GetSP()); + if (value_sp && target_sp) { + // Read and Write cannot both be false. + if (!read && !write) + return sb_watchpoint; + + // If the value is not in scope, don't try and watch and invalid value + if (!IsInScope()) + return sb_watchpoint; + + addr_t addr = GetLoadAddress(); + if (addr == LLDB_INVALID_ADDRESS) + return sb_watchpoint; + size_t byte_size = GetByteSize(); + if (byte_size == 0) + return sb_watchpoint; + + uint32_t watch_type = 0; + if (read) { + watch_type |= LLDB_WATCH_TYPE_READ; + // read + write, the most likely intention + // is to catch all writes to this, not just + // value modifications. + if (write) + watch_type |= LLDB_WATCH_TYPE_WRITE; + } else { + if (write) + watch_type |= LLDB_WATCH_TYPE_MODIFY; + } + + Status rc; + CompilerType type(value_sp->GetCompilerType()); + WatchpointSP watchpoint_sp = + target_sp->CreateWatchpoint(addr, byte_size, &type, watch_type, rc); + error.SetError(rc); + + if (watchpoint_sp) { + sb_watchpoint.SetSP(watchpoint_sp); + Declaration decl; + if (value_sp->GetDeclaration(decl)) { + if (decl.GetFile()) { + StreamString ss; + // True to show fullpath for declaration file. + decl.DumpStopContext(&ss, true); + watchpoint_sp->SetDeclInfo(std::string(ss.GetString())); + } + } + } + } else if (target_sp) { + error.SetErrorStringWithFormat("could not get SBValue: %s", + locker.GetError().AsCString()); + } else { + error.SetErrorString("could not set watchpoint, a target is required"); + } + + return sb_watchpoint; +} + +// FIXME: Remove this method impl (as well as the decl in .h) once it is no +// longer needed. +// Backward compatibility fix in the interim. +lldb::SBWatchpoint SBValue::Watch(bool resolve_location, bool read, + bool write) { + LLDB_INSTRUMENT_VA(this, resolve_location, read, write); + + SBError error; + return Watch(resolve_location, read, write, error); +} + +lldb::SBWatchpoint SBValue::WatchPointee(bool resolve_location, bool read, + bool write, SBError &error) { + LLDB_INSTRUMENT_VA(this, resolve_location, read, write, error); + + SBWatchpoint sb_watchpoint; + if (IsInScope() && GetType().IsPointerType()) + sb_watchpoint = Dereference().Watch(resolve_location, read, write, error); + return sb_watchpoint; +} + +lldb::SBValue SBValue::Persist() { + LLDB_INSTRUMENT_VA(this); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + SBValue persisted_sb; + if (value_sp) { + persisted_sb.SetSP(value_sp->Persist()); + } + return persisted_sb; +} + +lldb::SBValue SBValue::GetVTable() { + SBValue vtable_sb; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (!value_sp) + return vtable_sb; + + vtable_sb.SetSP(value_sp->GetVTable()); + return vtable_sb; +} diff --git a/contrib/llvm-project/lldb/source/API/SBValueList.cpp b/contrib/llvm-project/lldb/source/API/SBValueList.cpp new file mode 100644 index 000000000000..ba7e06971dc3 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBValueList.cpp @@ -0,0 +1,214 @@ +//===-- SBValueList.cpp ---------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBValueList.h" +#include "lldb/API/SBError.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBValue.h" +#include "lldb/Core/ValueObjectList.h" +#include "lldb/Utility/Instrumentation.h" +#include "lldb/Utility/Status.h" +#include <vector> + +using namespace lldb; +using namespace lldb_private; + +class ValueListImpl { +public: + ValueListImpl() = default; + + ValueListImpl(const ValueListImpl &rhs) = default; + + ValueListImpl &operator=(const ValueListImpl &rhs) { + if (this == &rhs) + return *this; + m_values = rhs.m_values; + m_error = rhs.m_error; + return *this; + } + + uint32_t GetSize() { return m_values.size(); } + + void Append(const lldb::SBValue &sb_value) { m_values.push_back(sb_value); } + + void Append(const ValueListImpl &list) { + for (auto val : list.m_values) + Append(val); + } + + lldb::SBValue GetValueAtIndex(uint32_t index) { + if (index >= GetSize()) + return lldb::SBValue(); + return m_values[index]; + } + + lldb::SBValue FindValueByUID(lldb::user_id_t uid) { + for (auto val : m_values) { + if (val.IsValid() && val.GetID() == uid) + return val; + } + return lldb::SBValue(); + } + + lldb::SBValue GetFirstValueByName(const char *name) const { + if (name) { + for (auto val : m_values) { + if (val.IsValid() && val.GetName() && strcmp(name, val.GetName()) == 0) + return val; + } + } + return lldb::SBValue(); + } + + const Status &GetError() const { return m_error; } + + void SetError(const Status &error) { m_error = error; } + +private: + std::vector<lldb::SBValue> m_values; + Status m_error; +}; + +SBValueList::SBValueList() { LLDB_INSTRUMENT_VA(this); } + +SBValueList::SBValueList(const SBValueList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (rhs.IsValid()) + m_opaque_up = std::make_unique<ValueListImpl>(*rhs); +} + +SBValueList::SBValueList(const ValueListImpl *lldb_object_ptr) { + if (lldb_object_ptr) + m_opaque_up = std::make_unique<ValueListImpl>(*lldb_object_ptr); +} + +SBValueList::~SBValueList() = default; + +bool SBValueList::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBValueList::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return (m_opaque_up != nullptr); +} + +void SBValueList::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_up.reset(); +} + +const SBValueList &SBValueList::operator=(const SBValueList &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) { + if (rhs.IsValid()) + m_opaque_up = std::make_unique<ValueListImpl>(*rhs); + else + m_opaque_up.reset(); + } + return *this; +} + +ValueListImpl *SBValueList::operator->() { return m_opaque_up.get(); } + +ValueListImpl &SBValueList::operator*() { return *m_opaque_up; } + +const ValueListImpl *SBValueList::operator->() const { + return m_opaque_up.get(); +} + +const ValueListImpl &SBValueList::operator*() const { return *m_opaque_up; } + +void SBValueList::Append(const SBValue &val_obj) { + LLDB_INSTRUMENT_VA(this, val_obj); + + CreateIfNeeded(); + m_opaque_up->Append(val_obj); +} + +void SBValueList::Append(lldb::ValueObjectSP &val_obj_sp) { + if (val_obj_sp) { + CreateIfNeeded(); + m_opaque_up->Append(SBValue(val_obj_sp)); + } +} + +void SBValueList::Append(const lldb::SBValueList &value_list) { + LLDB_INSTRUMENT_VA(this, value_list); + + if (value_list.IsValid()) { + CreateIfNeeded(); + m_opaque_up->Append(*value_list); + } +} + +SBValue SBValueList::GetValueAtIndex(uint32_t idx) const { + LLDB_INSTRUMENT_VA(this, idx); + + SBValue sb_value; + if (m_opaque_up) + sb_value = m_opaque_up->GetValueAtIndex(idx); + + return sb_value; +} + +uint32_t SBValueList::GetSize() const { + LLDB_INSTRUMENT_VA(this); + + uint32_t size = 0; + if (m_opaque_up) + size = m_opaque_up->GetSize(); + + return size; +} + +void SBValueList::CreateIfNeeded() { + if (m_opaque_up == nullptr) + m_opaque_up = std::make_unique<ValueListImpl>(); +} + +SBValue SBValueList::FindValueObjectByUID(lldb::user_id_t uid) { + LLDB_INSTRUMENT_VA(this, uid); + + SBValue sb_value; + if (m_opaque_up) + sb_value = m_opaque_up->FindValueByUID(uid); + return sb_value; +} + +SBValue SBValueList::GetFirstValueByName(const char *name) const { + LLDB_INSTRUMENT_VA(this, name); + + SBValue sb_value; + if (m_opaque_up) + sb_value = m_opaque_up->GetFirstValueByName(name); + return sb_value; +} + +void *SBValueList::opaque_ptr() { return m_opaque_up.get(); } + +ValueListImpl &SBValueList::ref() { + CreateIfNeeded(); + return *m_opaque_up; +} + +lldb::SBError SBValueList::GetError() { + LLDB_INSTRUMENT_VA(this); + SBError sb_error; + if (m_opaque_up) + sb_error.SetError(m_opaque_up->GetError()); + return sb_error; +} + +void SBValueList::SetError(const lldb_private::Status &status) { + ref().SetError(status); +} diff --git a/contrib/llvm-project/lldb/source/API/SBVariablesOptions.cpp b/contrib/llvm-project/lldb/source/API/SBVariablesOptions.cpp new file mode 100644 index 000000000000..989d159139cc --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBVariablesOptions.cpp @@ -0,0 +1,218 @@ +//===-- SBVariablesOptions.cpp --------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBVariablesOptions.h" +#include "lldb/API/SBTarget.h" +#include "lldb/Target/Target.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/lldb-private.h" + +using namespace lldb; +using namespace lldb_private; + +class VariablesOptionsImpl { +public: + VariablesOptionsImpl() + : m_include_arguments(false), m_include_locals(false), + m_include_statics(false), m_in_scope_only(false), + m_include_runtime_support_values(false) {} + + VariablesOptionsImpl(const VariablesOptionsImpl &) = default; + + ~VariablesOptionsImpl() = default; + + VariablesOptionsImpl &operator=(const VariablesOptionsImpl &) = default; + + bool GetIncludeArguments() const { return m_include_arguments; } + + void SetIncludeArguments(bool b) { m_include_arguments = b; } + + bool GetIncludeRecognizedArguments(const lldb::TargetSP &target_sp) const { + if (m_include_recognized_arguments != eLazyBoolCalculate) + return m_include_recognized_arguments; + return target_sp ? target_sp->GetDisplayRecognizedArguments() : false; + } + + void SetIncludeRecognizedArguments(bool b) { + m_include_recognized_arguments = b ? eLazyBoolYes : eLazyBoolNo; + } + + bool GetIncludeLocals() const { return m_include_locals; } + + void SetIncludeLocals(bool b) { m_include_locals = b; } + + bool GetIncludeStatics() const { return m_include_statics; } + + void SetIncludeStatics(bool b) { m_include_statics = b; } + + bool GetInScopeOnly() const { return m_in_scope_only; } + + void SetInScopeOnly(bool b) { m_in_scope_only = b; } + + bool GetIncludeRuntimeSupportValues() const { + return m_include_runtime_support_values; + } + + void SetIncludeRuntimeSupportValues(bool b) { + m_include_runtime_support_values = b; + } + + lldb::DynamicValueType GetUseDynamic() const { return m_use_dynamic; } + + void SetUseDynamic(lldb::DynamicValueType d) { m_use_dynamic = d; } + +private: + bool m_include_arguments : 1; + bool m_include_locals : 1; + bool m_include_statics : 1; + bool m_in_scope_only : 1; + bool m_include_runtime_support_values : 1; + LazyBool m_include_recognized_arguments = + eLazyBoolCalculate; // can be overridden with a setting + lldb::DynamicValueType m_use_dynamic = lldb::eNoDynamicValues; +}; + +SBVariablesOptions::SBVariablesOptions() + : m_opaque_up(new VariablesOptionsImpl()) { + LLDB_INSTRUMENT_VA(this); +} + +SBVariablesOptions::SBVariablesOptions(const SBVariablesOptions &options) + : m_opaque_up(new VariablesOptionsImpl(options.ref())) { + LLDB_INSTRUMENT_VA(this, options); +} + +SBVariablesOptions &SBVariablesOptions:: +operator=(const SBVariablesOptions &options) { + LLDB_INSTRUMENT_VA(this, options); + + m_opaque_up = std::make_unique<VariablesOptionsImpl>(options.ref()); + return *this; +} + +SBVariablesOptions::~SBVariablesOptions() = default; + +bool SBVariablesOptions::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBVariablesOptions::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up != nullptr; +} + +bool SBVariablesOptions::GetIncludeArguments() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetIncludeArguments(); +} + +void SBVariablesOptions::SetIncludeArguments(bool arguments) { + LLDB_INSTRUMENT_VA(this, arguments); + + m_opaque_up->SetIncludeArguments(arguments); +} + +bool SBVariablesOptions::GetIncludeRecognizedArguments( + const lldb::SBTarget &target) const { + LLDB_INSTRUMENT_VA(this, target); + + return m_opaque_up->GetIncludeRecognizedArguments(target.GetSP()); +} + +void SBVariablesOptions::SetIncludeRecognizedArguments(bool arguments) { + LLDB_INSTRUMENT_VA(this, arguments); + + m_opaque_up->SetIncludeRecognizedArguments(arguments); +} + +bool SBVariablesOptions::GetIncludeLocals() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetIncludeLocals(); +} + +void SBVariablesOptions::SetIncludeLocals(bool locals) { + LLDB_INSTRUMENT_VA(this, locals); + + m_opaque_up->SetIncludeLocals(locals); +} + +bool SBVariablesOptions::GetIncludeStatics() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetIncludeStatics(); +} + +void SBVariablesOptions::SetIncludeStatics(bool statics) { + LLDB_INSTRUMENT_VA(this, statics); + + m_opaque_up->SetIncludeStatics(statics); +} + +bool SBVariablesOptions::GetInScopeOnly() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetInScopeOnly(); +} + +void SBVariablesOptions::SetInScopeOnly(bool in_scope_only) { + LLDB_INSTRUMENT_VA(this, in_scope_only); + + m_opaque_up->SetInScopeOnly(in_scope_only); +} + +bool SBVariablesOptions::GetIncludeRuntimeSupportValues() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetIncludeRuntimeSupportValues(); +} + +void SBVariablesOptions::SetIncludeRuntimeSupportValues( + bool runtime_support_values) { + LLDB_INSTRUMENT_VA(this, runtime_support_values); + + m_opaque_up->SetIncludeRuntimeSupportValues(runtime_support_values); +} + +lldb::DynamicValueType SBVariablesOptions::GetUseDynamic() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_up->GetUseDynamic(); +} + +void SBVariablesOptions::SetUseDynamic(lldb::DynamicValueType dynamic) { + LLDB_INSTRUMENT_VA(this, dynamic); + + m_opaque_up->SetUseDynamic(dynamic); +} + +VariablesOptionsImpl *SBVariablesOptions::operator->() { + return m_opaque_up.operator->(); +} + +const VariablesOptionsImpl *SBVariablesOptions::operator->() const { + return m_opaque_up.operator->(); +} + +VariablesOptionsImpl *SBVariablesOptions::get() { return m_opaque_up.get(); } + +VariablesOptionsImpl &SBVariablesOptions::ref() { return *m_opaque_up; } + +const VariablesOptionsImpl &SBVariablesOptions::ref() const { + return *m_opaque_up; +} + +SBVariablesOptions::SBVariablesOptions(VariablesOptionsImpl *lldb_object_ptr) + : m_opaque_up(std::move(lldb_object_ptr)) {} + +void SBVariablesOptions::SetOptions(VariablesOptionsImpl *lldb_object_ptr) { + m_opaque_up.reset(std::move(lldb_object_ptr)); +} diff --git a/contrib/llvm-project/lldb/source/API/SBWatchpoint.cpp b/contrib/llvm-project/lldb/source/API/SBWatchpoint.cpp new file mode 100644 index 000000000000..9664bbe61860 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBWatchpoint.cpp @@ -0,0 +1,357 @@ +//===-- SBWatchpoint.cpp --------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBWatchpoint.h" +#include "lldb/API/SBAddress.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBDefines.h" +#include "lldb/API/SBEvent.h" +#include "lldb/API/SBStream.h" +#include "lldb/Utility/Instrumentation.h" + +#include "lldb/Breakpoint/Watchpoint.h" +#include "lldb/Breakpoint/WatchpointList.h" +#include "lldb/Symbol/CompilerType.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/Target.h" +#include "lldb/Utility/Stream.h" +#include "lldb/lldb-defines.h" +#include "lldb/lldb-types.h" + +using namespace lldb; +using namespace lldb_private; + +SBWatchpoint::SBWatchpoint() { LLDB_INSTRUMENT_VA(this); } + +SBWatchpoint::SBWatchpoint(const lldb::WatchpointSP &wp_sp) + : m_opaque_wp(wp_sp) { + LLDB_INSTRUMENT_VA(this, wp_sp); +} + +SBWatchpoint::SBWatchpoint(const SBWatchpoint &rhs) + : m_opaque_wp(rhs.m_opaque_wp) { + LLDB_INSTRUMENT_VA(this, rhs); +} + +const SBWatchpoint &SBWatchpoint::operator=(const SBWatchpoint &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_wp = rhs.m_opaque_wp; + return *this; +} + +SBWatchpoint::~SBWatchpoint() = default; + +watch_id_t SBWatchpoint::GetID() { + LLDB_INSTRUMENT_VA(this); + + watch_id_t watch_id = LLDB_INVALID_WATCH_ID; + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) + watch_id = watchpoint_sp->GetID(); + + return watch_id; +} + +bool SBWatchpoint::IsValid() const { + LLDB_INSTRUMENT_VA(this); + return this->operator bool(); +} +SBWatchpoint::operator bool() const { + LLDB_INSTRUMENT_VA(this); + + return bool(m_opaque_wp.lock()); +} + +bool SBWatchpoint::operator==(const SBWatchpoint &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return GetSP() == rhs.GetSP(); +} + +bool SBWatchpoint::operator!=(const SBWatchpoint &rhs) const { + LLDB_INSTRUMENT_VA(this, rhs); + + return !(*this == rhs); +} + +SBError SBWatchpoint::GetError() { + LLDB_INSTRUMENT_VA(this); + + SBError sb_error; + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + sb_error.SetError(watchpoint_sp->GetError()); + } + return sb_error; +} + +int32_t SBWatchpoint::GetHardwareIndex() { + LLDB_INSTRUMENT_VA(this); + + // For processes using gdb remote protocol, + // we cannot determine the hardware breakpoint + // index reliably; providing possibly correct + // guesses is not useful to anyone. + return -1; +} + +addr_t SBWatchpoint::GetWatchAddress() { + LLDB_INSTRUMENT_VA(this); + + addr_t ret_addr = LLDB_INVALID_ADDRESS; + + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + ret_addr = watchpoint_sp->GetLoadAddress(); + } + + return ret_addr; +} + +size_t SBWatchpoint::GetWatchSize() { + LLDB_INSTRUMENT_VA(this); + + size_t watch_size = 0; + + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + watch_size = watchpoint_sp->GetByteSize(); + } + + return watch_size; +} + +void SBWatchpoint::SetEnabled(bool enabled) { + LLDB_INSTRUMENT_VA(this, enabled); + + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + Target &target = watchpoint_sp->GetTarget(); + std::lock_guard<std::recursive_mutex> guard(target.GetAPIMutex()); + ProcessSP process_sp = target.GetProcessSP(); + const bool notify = true; + if (process_sp) { + if (enabled) + process_sp->EnableWatchpoint(watchpoint_sp, notify); + else + process_sp->DisableWatchpoint(watchpoint_sp, notify); + } else { + watchpoint_sp->SetEnabled(enabled, notify); + } + } +} + +bool SBWatchpoint::IsEnabled() { + LLDB_INSTRUMENT_VA(this); + + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + return watchpoint_sp->IsEnabled(); + } else + return false; +} + +uint32_t SBWatchpoint::GetHitCount() { + LLDB_INSTRUMENT_VA(this); + + uint32_t count = 0; + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + count = watchpoint_sp->GetHitCount(); + } + + return count; +} + +uint32_t SBWatchpoint::GetIgnoreCount() { + LLDB_INSTRUMENT_VA(this); + + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + return watchpoint_sp->GetIgnoreCount(); + } else + return 0; +} + +void SBWatchpoint::SetIgnoreCount(uint32_t n) { + LLDB_INSTRUMENT_VA(this, n); + + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + watchpoint_sp->SetIgnoreCount(n); + } +} + +const char *SBWatchpoint::GetCondition() { + LLDB_INSTRUMENT_VA(this); + + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (!watchpoint_sp) + return nullptr; + + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + return ConstString(watchpoint_sp->GetConditionText()).GetCString(); +} + +void SBWatchpoint::SetCondition(const char *condition) { + LLDB_INSTRUMENT_VA(this, condition); + + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + watchpoint_sp->SetCondition(condition); + } +} + +bool SBWatchpoint::GetDescription(SBStream &description, + DescriptionLevel level) { + LLDB_INSTRUMENT_VA(this, description, level); + + Stream &strm = description.ref(); + + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + watchpoint_sp->GetDescription(&strm, level); + strm.EOL(); + } else + strm.PutCString("No value"); + + return true; +} + +void SBWatchpoint::Clear() { + LLDB_INSTRUMENT_VA(this); + + m_opaque_wp.reset(); +} + +lldb::WatchpointSP SBWatchpoint::GetSP() const { + LLDB_INSTRUMENT_VA(this); + + return m_opaque_wp.lock(); +} + +void SBWatchpoint::SetSP(const lldb::WatchpointSP &sp) { + LLDB_INSTRUMENT_VA(this, sp); + + m_opaque_wp = sp; +} + +bool SBWatchpoint::EventIsWatchpointEvent(const lldb::SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + return Watchpoint::WatchpointEventData::GetEventDataFromEvent(event.get()) != + nullptr; +} + +WatchpointEventType +SBWatchpoint::GetWatchpointEventTypeFromEvent(const SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + if (event.IsValid()) + return Watchpoint::WatchpointEventData::GetWatchpointEventTypeFromEvent( + event.GetSP()); + return eWatchpointEventTypeInvalidType; +} + +SBWatchpoint SBWatchpoint::GetWatchpointFromEvent(const lldb::SBEvent &event) { + LLDB_INSTRUMENT_VA(event); + + SBWatchpoint sb_watchpoint; + if (event.IsValid()) + sb_watchpoint = + Watchpoint::WatchpointEventData::GetWatchpointFromEvent(event.GetSP()); + return sb_watchpoint; +} + +lldb::SBType SBWatchpoint::GetType() { + LLDB_INSTRUMENT_VA(this); + + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + const CompilerType &type = watchpoint_sp->GetCompilerType(); + return lldb::SBType(type); + } + return lldb::SBType(); +} + +WatchpointValueKind SBWatchpoint::GetWatchValueKind() { + LLDB_INSTRUMENT_VA(this); + + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + if (watchpoint_sp->IsWatchVariable()) + return WatchpointValueKind::eWatchPointValueKindVariable; + return WatchpointValueKind::eWatchPointValueKindExpression; + } + return WatchpointValueKind::eWatchPointValueKindInvalid; +} + +const char *SBWatchpoint::GetWatchSpec() { + LLDB_INSTRUMENT_VA(this); + + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (!watchpoint_sp) + return nullptr; + + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + // Store the result of `GetWatchSpec()` as a ConstString + // so that the C string we return has a sufficiently long + // lifetime. Note this a memory leak but should be fairly + // low impact. + return ConstString(watchpoint_sp->GetWatchSpec()).AsCString(); +} + +bool SBWatchpoint::IsWatchingReads() { + LLDB_INSTRUMENT_VA(this); + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + + return watchpoint_sp->WatchpointRead(); + } + + return false; +} + +bool SBWatchpoint::IsWatchingWrites() { + LLDB_INSTRUMENT_VA(this); + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard<std::recursive_mutex> guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + + return watchpoint_sp->WatchpointWrite() || + watchpoint_sp->WatchpointModify(); + } + + return false; +} diff --git a/contrib/llvm-project/lldb/source/API/SBWatchpointOptions.cpp b/contrib/llvm-project/lldb/source/API/SBWatchpointOptions.cpp new file mode 100644 index 000000000000..62e9c21a8579 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SBWatchpointOptions.cpp @@ -0,0 +1,73 @@ +//===-- SBWatchpointOptions.cpp -------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/API/SBWatchpointOptions.h" +#include "lldb/Breakpoint/Watchpoint.h" +#include "lldb/Utility/Instrumentation.h" + +#include "Utils.h" + +using namespace lldb; +using namespace lldb_private; + +class WatchpointOptionsImpl { +public: + bool m_read = false; + bool m_write = false; + bool m_modify = false; +}; + + +SBWatchpointOptions::SBWatchpointOptions() + : m_opaque_up(new WatchpointOptionsImpl()) { + LLDB_INSTRUMENT_VA(this); +} + +SBWatchpointOptions::SBWatchpointOptions(const SBWatchpointOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + m_opaque_up = clone(rhs.m_opaque_up); +} + +const SBWatchpointOptions & +SBWatchpointOptions::operator=(const SBWatchpointOptions &rhs) { + LLDB_INSTRUMENT_VA(this, rhs); + + if (this != &rhs) + m_opaque_up = clone(rhs.m_opaque_up); + return *this; +} + +SBWatchpointOptions::~SBWatchpointOptions() = default; + +void SBWatchpointOptions::SetWatchpointTypeRead(bool read) { + m_opaque_up->m_read = read; +} +bool SBWatchpointOptions::GetWatchpointTypeRead() const { + return m_opaque_up->m_read; +} + +void SBWatchpointOptions::SetWatchpointTypeWrite( + WatchpointWriteType write_type) { + if (write_type == eWatchpointWriteTypeOnModify) { + m_opaque_up->m_write = false; + m_opaque_up->m_modify = true; + } else if (write_type == eWatchpointWriteTypeAlways) { + m_opaque_up->m_write = true; + m_opaque_up->m_modify = false; + } else + m_opaque_up->m_write = m_opaque_up->m_modify = false; +} + +WatchpointWriteType SBWatchpointOptions::GetWatchpointTypeWrite() const { + if (m_opaque_up->m_modify) + return eWatchpointWriteTypeOnModify; + if (m_opaque_up->m_write) + return eWatchpointWriteTypeAlways; + return eWatchpointWriteTypeDisabled; +} diff --git a/contrib/llvm-project/lldb/source/API/SystemInitializerFull.cpp b/contrib/llvm-project/lldb/source/API/SystemInitializerFull.cpp new file mode 100644 index 000000000000..995d14f7c1fa --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SystemInitializerFull.cpp @@ -0,0 +1,106 @@ +//===-- SystemInitializerFull.cpp -----------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "SystemInitializerFull.h" +#include "lldb/API/SBCommandInterpreter.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Core/PluginManager.h" +#include "lldb/Core/Progress.h" +#include "lldb/Host/Config.h" +#include "lldb/Host/Host.h" +#include "lldb/Initialization/SystemInitializerCommon.h" +#include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Target/ProcessTrace.h" +#include "lldb/Utility/Timer.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/TargetSelect.h" + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wglobal-constructors" +#include "llvm/ExecutionEngine/MCJIT.h" +#pragma clang diagnostic pop + +#include <string> + +#define LLDB_PLUGIN(p) LLDB_PLUGIN_DECLARE(p) +#include "Plugins/Plugins.def" + +#if LLDB_ENABLE_PYTHON +#include "Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h" + +constexpr lldb_private::HostInfo::SharedLibraryDirectoryHelper + *g_shlib_dir_helper = + lldb_private::ScriptInterpreterPython::SharedLibraryDirectoryHelper; + +#else +constexpr lldb_private::HostInfo::SharedLibraryDirectoryHelper + *g_shlib_dir_helper = nullptr; +#endif + +using namespace lldb_private; + +SystemInitializerFull::SystemInitializerFull() + : SystemInitializerCommon(g_shlib_dir_helper) {} +SystemInitializerFull::~SystemInitializerFull() = default; + +llvm::Error SystemInitializerFull::Initialize() { + llvm::Error error = SystemInitializerCommon::Initialize(); + if (error) + return error; + + // Initialize LLVM and Clang + llvm::InitializeAllTargets(); + llvm::InitializeAllAsmPrinters(); + llvm::InitializeAllTargetMCs(); + llvm::InitializeAllDisassemblers(); + + // Initialize the command line parser in LLVM. This usually isn't necessary + // as we aren't dealing with command line options here, but otherwise some + // other code in Clang/LLVM might be tempted to call this function from a + // different thread later on which won't work (as the function isn't + // thread-safe). + const char *arg0 = "lldb"; + llvm::cl::ParseCommandLineOptions(1, &arg0); + + // Initialize the progress manager. + ProgressManager::Initialize(); + +#define LLDB_PLUGIN(p) LLDB_PLUGIN_INITIALIZE(p); +#include "Plugins/Plugins.def" + + // Scan for any system or user LLDB plug-ins. + PluginManager::Initialize(); + + // The process settings need to know about installed plug-ins, so the + // Settings must be initialized AFTER PluginManager::Initialize is called. + Debugger::SettingsInitialize(); + + // Use the Debugger's LLDBAssert callback. + SetLLDBAssertCallback(Debugger::AssertCallback); + + return llvm::Error::success(); +} + +void SystemInitializerFull::Terminate() { + Debugger::SettingsTerminate(); + + // Terminate plug-ins in core LLDB. + ProcessTrace::Terminate(); + + // Terminate and unload and loaded system or user LLDB plug-ins. + PluginManager::Terminate(); + +#define LLDB_PLUGIN(p) LLDB_PLUGIN_TERMINATE(p); +#include "Plugins/Plugins.def" + + // Terminate the progress manager. + ProgressManager::Terminate(); + + // Now shutdown the common parts, in reverse order. + SystemInitializerCommon::Terminate(); +} diff --git a/contrib/llvm-project/lldb/source/API/SystemInitializerFull.h b/contrib/llvm-project/lldb/source/API/SystemInitializerFull.h new file mode 100644 index 000000000000..7cab6cb97533 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/SystemInitializerFull.h @@ -0,0 +1,32 @@ +//===-- SystemInitializerFull.h ---------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLDB_SOURCE_API_SYSTEMINITIALIZERFULL_H +#define LLDB_SOURCE_API_SYSTEMINITIALIZERFULL_H + +#include "lldb/Initialization/SystemInitializerCommon.h" + +namespace lldb_private { +/// Initializes lldb. +/// +/// This class is responsible for initializing all of lldb system +/// services needed to use the full LLDB application. This class is +/// not intended to be used externally, but is instead used +/// internally by SBDebugger to initialize the system. +class SystemInitializerFull : public SystemInitializerCommon { +public: + SystemInitializerFull(); + ~SystemInitializerFull() override; + + llvm::Error Initialize() override; + void Terminate() override; +}; + +} // namespace lldb_private + +#endif // LLDB_SOURCE_API_SYSTEMINITIALIZERFULL_H diff --git a/contrib/llvm-project/lldb/source/API/Utils.h b/contrib/llvm-project/lldb/source/API/Utils.h new file mode 100644 index 000000000000..4201e825c446 --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/Utils.h @@ -0,0 +1,30 @@ +//===-- Utils.h -------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLDB_SOURCE_API_UTILS_H +#define LLDB_SOURCE_API_UTILS_H + +#include "llvm/ADT/STLExtras.h" +#include <memory> + +namespace lldb_private { + +template <typename T> std::unique_ptr<T> clone(const std::unique_ptr<T> &src) { + if (src) + return std::make_unique<T>(*src); + return nullptr; +} + +template <typename T> std::shared_ptr<T> clone(const std::shared_ptr<T> &src) { + if (src) + return std::make_shared<T>(*src); + return nullptr; +} + +} // namespace lldb_private +#endif diff --git a/contrib/llvm-project/lldb/source/API/liblldb-private.exports b/contrib/llvm-project/lldb/source/API/liblldb-private.exports new file mode 100644 index 000000000000..cf1360021c6c --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/liblldb-private.exports @@ -0,0 +1,7 @@ +_ZN4lldb* +_ZNK4lldb* +_ZN12lldb_private* +_ZNK12lldb_private* +init_lld* +PyInit__lldb* +luaopen_lldb* diff --git a/contrib/llvm-project/lldb/source/API/liblldb.exports b/contrib/llvm-project/lldb/source/API/liblldb.exports new file mode 100644 index 000000000000..5835cf0a02ea --- /dev/null +++ b/contrib/llvm-project/lldb/source/API/liblldb.exports @@ -0,0 +1,5 @@ +_ZN4lldb* +_ZNK4lldb* +init_lld* +PyInit__lldb* +luaopen_lldb* |